code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*
This file is a part of JRTPLIB
Copyright (c) 1999-2004 Jori Liesenborgs
Contact: jori@lumumba.luc.ac.be
This library was developed at the "Expertisecentrum Digitale Media"
(http://www.edm.luc.ac.be), a research center of the "Limburgs Universitair
Centrum" (http://www.luc.ac.be). The library is based upon work done for
my thesis at the School for Knowledge Technology (Belgium/The Netherlands).
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include "rtpsources.h"
#include "rtperrors.h"
#include "rtprawpacket.h"
#include "rtpinternalsourcedata.h"
#include "rtptimeutilities.h"
#include "rtpdefines.h"
#include "rtcpcompoundpacket.h"
#include "rtcppacket.h"
#include "rtcpapppacket.h"
#include "rtcpbyepacket.h"
#include "rtcpsdespacket.h"
#include "rtcpsrpacket.h"
#include "rtcprrpacket.h"
#include "rtptransmitter.h"
#ifdef RTPDEBUG
#include <iostream>
#endif // RTPDEBUG
#include "rtpdebug.h"
#ifndef RTP_SUPPORT_INLINETEMPLATEPARAM
int RTPSources_GetHashIndex(const u_int32_t &ssrc) { return ssrc%RTPSOURCES_HASHSIZE; }
#endif // !RTP_SUPPORT_INLINETEMPLATEPARAM
RTPSources::RTPSources()
{
totalcount = 0;
sendercount = 0;
activecount = 0;
owndata = 0;
}
RTPSources::~RTPSources()
{
Clear();
}
void RTPSources::Clear()
{
ClearSourceList();
}
void RTPSources::ClearSourceList()
{
sourcelist.GotoFirstElement();
while (sourcelist.HasCurrentElement())
{
RTPInternalSourceData *sourcedata;
sourcedata = sourcelist.GetCurrentElement();
delete sourcedata;
sourcelist.GotoNextElement();
}
sourcelist.Clear();
owndata = 0;
}
int RTPSources::CreateOwnSSRC(u_int32_t ssrc)
{
if (owndata != 0)
return ERR_RTP_SOURCES_ALREADYHAVEOWNSSRC;
if (GotEntry(ssrc))
return ERR_RTP_SOURCES_SSRCEXISTS;
int status;
bool created;
status = ObtainSourceDataInstance(ssrc,&owndata,&created);
if (status < 0)
{
owndata = 0; // just to make sure
return status;
}
owndata->SetOwnSSRC();
owndata->SetRTPDataAddress(0);
owndata->SetRTCPDataAddress(0);
// we've created a validated ssrc, so we should increase activecount
activecount++;
OnNewSource(owndata);
return 0;
}
int RTPSources::DeleteOwnSSRC()
{
if (owndata == 0)
return ERR_RTP_SOURCES_DONTHAVEOWNSSRC;
u_int32_t ssrc = owndata->GetSSRC();
sourcelist.GotoElement(ssrc);
sourcelist.DeleteCurrentElement();
totalcount--;
if (owndata->IsSender())
sendercount--;
if (owndata->IsActive())
activecount--;
OnRemoveSource(owndata);
delete owndata;
owndata = 0;
return 0;
}
void RTPSources::SentRTPPacket()
{
if (owndata == 0)
return;
bool prevsender = owndata->IsSender();
owndata->SentRTPPacket();
if (!prevsender && owndata->IsSender())
sendercount++;
}
int RTPSources::ProcessRawPacket(RTPRawPacket *rawpack,RTPTransmitter *rtptrans,bool acceptownpackets)
{
RTPTransmitter *transmitters[1];
int num;
transmitters[0] = rtptrans;
if (rtptrans == 0)
num = 0;
else
num = 1;
return ProcessRawPacket(rawpack,transmitters,num,acceptownpackets);
}
int RTPSources::ProcessRawPacket(RTPRawPacket *rawpack,RTPTransmitter *rtptrans[],int numtrans,bool acceptownpackets)
{
int status;
if (rawpack->IsRTP()) // RTP packet
{
RTPPacket *rtppack;
// First, we'll see if the packet can be parsed
rtppack = new RTPPacket(*rawpack);
if (rtppack == 0)
return ERR_RTP_OUTOFMEM;
if ((status = rtppack->GetCreationError()) < 0)
{
if (status == ERR_RTP_PACKET_INVALIDPACKET)
{
delete rtppack;
rtppack = 0;
}
else
{
delete rtppack;
return status;
}
}
// Check if the packet was valid
if (rtppack != 0)
{
bool stored = false;
bool ownpacket = false;
int i;
const RTPAddress *senderaddress = rawpack->GetSenderAddress();
for (i = 0 ; !ownpacket && i < numtrans ; i++)
{
if (rtptrans[i]->ComesFromThisTransmitter(senderaddress))
ownpacket = true;
}
// Check if the packet is our own.
if (ownpacket)
{
// Now it depends on the user's preference
// what to do with this packet:
if (acceptownpackets)
{
// sender addres for own packets has to be NULL!
if ((status = ProcessRTPPacket(rtppack,rawpack->GetReceiveTime(),0,&stored)) < 0)
{
if (!stored)
delete rtppack;
return status;
}
}
}
else
{
if ((status = ProcessRTPPacket(rtppack,rawpack->GetReceiveTime(),senderaddress,&stored)) < 0)
{
if (!stored)
delete rtppack;
return status;
}
}
if (!stored)
delete rtppack;
}
}
else // RTCP packet
{
RTCPCompoundPacket rtcpcomppack(*rawpack);
bool valid = false;
if ((status = rtcpcomppack.GetCreationError()) < 0)
{
if (status != ERR_RTP_RTCPCOMPOUND_INVALIDPACKET)
return status;
}
else
valid = true;
if (valid)
{
bool ownpacket = false;
int i;
const RTPAddress *senderaddress = rawpack->GetSenderAddress();
for (i = 0 ; !ownpacket && i < numtrans ; i++)
{
if (rtptrans[i]->ComesFromThisTransmitter(senderaddress))
ownpacket = true;
}
// First check if it's a packet of this session.
if (ownpacket)
{
if (acceptownpackets)
{
// sender address for own packets has to be NULL
status = ProcessRTCPCompoundPacket(&rtcpcomppack,rawpack->GetReceiveTime(),0);
if (status < 0)
return status;
}
}
else // not our own packet
{
status = ProcessRTCPCompoundPacket(&rtcpcomppack,rawpack->GetReceiveTime(),rawpack->GetSenderAddress());
if (status < 0)
return status;
}
}
}
return 0;
}
int RTPSources::ProcessRTPPacket(RTPPacket *rtppack,const RTPTime &receivetime,const RTPAddress *senderaddress,bool *stored)
{
u_int32_t ssrc;
RTPInternalSourceData *srcdat;
int status;
bool created;
OnRTPPacket(rtppack,receivetime,senderaddress);
*stored = false;
ssrc = rtppack->GetSSRC();
if ((status = ObtainSourceDataInstance(ssrc,&srcdat,&created)) < 0)
return status;
if (created)
{
if ((status = srcdat->SetRTPDataAddress(senderaddress)) < 0)
return status;
}
else // got a previously existing source
{
if (CheckCollision(srcdat,senderaddress,true))
return 0; // ignore packet on collision
}
bool prevsender = srcdat->IsSender();
bool prevactive = srcdat->IsActive();
// The packet comes from a valid source, we can process it further now
// The following function should delete rtppack itself if something goes
// wrong
if ((status = srcdat->ProcessRTPPacket(rtppack,receivetime,stored)) < 0)
return status;
if (!prevsender && srcdat->IsSender())
sendercount++;
if (!prevactive && srcdat->IsActive())
activecount++;
if (created)
OnNewSource(srcdat);
if (srcdat->IsValidated()) // process the CSRCs
{
RTPInternalSourceData *csrcdat;
bool createdcsrc;
int num = rtppack->GetCSRCCount();
int i;
for (i = 0 ; i < num ; i++)
{
if ((status = ObtainSourceDataInstance(rtppack->GetCSRC(i),&csrcdat,&createdcsrc)) < 0)
return status;
if (createdcsrc)
{
csrcdat->SetCSRC();
if (csrcdat->IsActive())
activecount++;
OnNewSource(csrcdat);
}
else // already found an entry, possibly because of RTCP data
{
if (!CheckCollision(csrcdat,senderaddress,true))
csrcdat->SetCSRC();
}
}
}
return 0;
}
int RTPSources::ProcessRTCPCompoundPacket(RTCPCompoundPacket *rtcpcomppack,const RTPTime &receivetime,const RTPAddress *senderaddress)
{
RTCPPacket *rtcppack;
int status;
bool gotownssrc = ((owndata == 0)?false:true);
u_int32_t ownssrc = ((owndata != 0)?owndata->GetSSRC():0);
OnRTCPCompoundPacket(rtcpcomppack,receivetime,senderaddress);
rtcpcomppack->GotoFirstPacket();
while ((rtcppack = rtcpcomppack->GetNextPacket()) != 0)
{
if (rtcppack->IsKnownFormat())
{
switch (rtcppack->GetPacketType())
{
case RTCPPacket::SR:
{
RTCPSRPacket *p = (RTCPSRPacket *)rtcppack;
u_int32_t senderssrc = p->GetSenderSSRC();
status = ProcessRTCPSenderInfo(senderssrc,p->GetNTPTimestamp(),p->GetRTPTimestamp(),
p->GetSenderPacketCount(),p->GetSenderOctetCount(),
receivetime,senderaddress);
if (status < 0)
return status;
bool gotinfo = false;
if (gotownssrc)
{
int i;
int num = p->GetReceptionReportCount();
for (i = 0 ; i < num ; i++)
{
if (p->GetSSRC(i) == ownssrc) // data is meant for us
{
gotinfo = true;
status = ProcessRTCPReportBlock(senderssrc,p->GetFractionLost(i),p->GetLostPacketCount(i),
p->GetExtendedHighestSequenceNumber(i),p->GetJitter(i),p->GetLSR(i),
p->GetDLSR(i),receivetime,senderaddress);
if (status < 0)
return status;
}
}
}
if (!gotinfo)
{
status = UpdateReceiveTime(senderssrc,receivetime,senderaddress);
if (status < 0)
return status;
}
}
break;
case RTCPPacket::RR:
{
RTCPRRPacket *p = (RTCPRRPacket *)rtcppack;
u_int32_t senderssrc = p->GetSenderSSRC();
bool gotinfo = false;
if (gotownssrc)
{
int i;
int num = p->GetReceptionReportCount();
for (i = 0 ; i < num ; i++)
{
if (p->GetSSRC(i) == ownssrc)
{
gotinfo = true;
status = ProcessRTCPReportBlock(senderssrc,p->GetFractionLost(i),p->GetLostPacketCount(i),
p->GetExtendedHighestSequenceNumber(i),p->GetJitter(i),p->GetLSR(i),
p->GetDLSR(i),receivetime,senderaddress);
if (status < 0)
return status;
}
}
}
if (!gotinfo)
{
status = UpdateReceiveTime(senderssrc,receivetime,senderaddress);
if (status < 0)
return status;
}
}
break;
case RTCPPacket::SDES:
{
RTCPSDESPacket *p = (RTCPSDESPacket *)rtcppack;
if (p->GotoFirstChunk())
{
do
{
u_int32_t sdesssrc = p->GetChunkSSRC();
bool updated = false;
if (p->GotoFirstItem())
{
do
{
RTCPSDESPacket::ItemType t;
if ((t = p->GetItemType()) != RTCPSDESPacket::PRIV)
{
updated = true;
status = ProcessSDESNormalItem(sdesssrc,t,p->GetItemLength(),p->GetItemData(),receivetime,senderaddress);
if (status < 0)
return status;
}
#ifdef RTP_SUPPORT_SDESPRIV
else
{
updated = true;
status = ProcessSDESPrivateItem(sdesssrc,p->GetPRIVPrefixLength(),p->GetPRIVPrefixData(),p->GetPRIVValueLength(),
p->GetPRIVValueData(),receivetime,senderaddress);
if (status < 0)
return status;
}
#endif // RTP_SUPPORT_SDESPRIV
} while (p->GotoNextItem());
}
if (!updated)
{
status = UpdateReceiveTime(sdesssrc,receivetime,senderaddress);
if (status < 0)
return status;
}
} while (p->GotoNextChunk());
}
}
break;
case RTCPPacket::BYE:
{
RTCPBYEPacket *p = (RTCPBYEPacket *)rtcppack;
int i;
int num = p->GetSSRCCount();
for (i = 0 ; i < num ; i++)
{
u_int32_t byessrc = p->GetSSRC(i);
status = ProcessBYE(byessrc,p->GetReasonLength(),p->GetReasonData(),receivetime,senderaddress);
if (status < 0)
return status;
}
}
break;
case RTCPPacket::APP:
{
RTCPAPPPacket *p = (RTCPAPPPacket *)rtcppack;
OnAPPPacket(p,receivetime,senderaddress);
}
break;
case RTCPPacket::Unknown:
default:
{
OnUnknownPacketType(rtcppack,receivetime,senderaddress);
}
break;
}
}
else
{
OnUnknownPacketFormat(rtcppack,receivetime,senderaddress);
}
}
return 0;
}
bool RTPSources::GotoFirstSource()
{
sourcelist.GotoFirstElement();
if (sourcelist.HasCurrentElement())
return true;
return false;
}
bool RTPSources::GotoNextSource()
{
sourcelist.GotoNextElement();
if (sourcelist.HasCurrentElement())
return true;
return false;
}
bool RTPSources::GotoPreviousSource()
{
sourcelist.GotoPreviousElement();
if (sourcelist.HasCurrentElement())
return true;
return false;
}
bool RTPSources::GotoFirstSourceWithData()
{
bool found = false;
sourcelist.GotoFirstElement();
while (!found && sourcelist.HasCurrentElement())
{
RTPInternalSourceData *srcdat;
srcdat = sourcelist.GetCurrentElement();
if (srcdat->HasData())
found = true;
else
sourcelist.GotoNextElement();
}
return found;
}
bool RTPSources::GotoNextSourceWithData()
{
bool found = false;
sourcelist.GotoNextElement();
while (!found && sourcelist.HasCurrentElement())
{
RTPInternalSourceData *srcdat;
srcdat = sourcelist.GetCurrentElement();
if (srcdat->HasData())
found = true;
else
sourcelist.GotoNextElement();
}
return found;
}
bool RTPSources::GotoPreviousSourceWithData()
{
bool found = false;
sourcelist.GotoPreviousElement();
while (!found && sourcelist.HasCurrentElement())
{
RTPInternalSourceData *srcdat;
srcdat = sourcelist.GetCurrentElement();
if (srcdat->HasData())
found = true;
else
sourcelist.GotoNextElement();
}
return found;
}
RTPSourceData *RTPSources::GetCurrentSourceInfo()
{
if (!sourcelist.HasCurrentElement())
return 0;
return sourcelist.GetCurrentElement();
}
RTPSourceData *RTPSources::GetSourceInfo(u_int32_t ssrc)
{
if (sourcelist.GotoElement(ssrc) < 0)
return 0;
if (!sourcelist.HasCurrentElement())
return 0;
return sourcelist.GetCurrentElement();
}
bool RTPSources::GotEntry(u_int32_t ssrc)
{
return sourcelist.HasElement(ssrc);
}
RTPPacket *RTPSources::GetNextPacket()
{
if (!sourcelist.HasCurrentElement())
return 0;
RTPInternalSourceData *srcdat = sourcelist.GetCurrentElement();
RTPPacket *pack = srcdat->GetNextPacket();
return pack;
}
int RTPSources::ProcessRTCPSenderInfo(u_int32_t ssrc,const RTPNTPTime &ntptime,u_int32_t rtptime,
u_int32_t packetcount,u_int32_t octetcount,const RTPTime &receivetime,
const RTPAddress *senderaddress)
{
RTPInternalSourceData *srcdat;
bool created;
int status;
status = GetRTCPSourceData(ssrc,senderaddress,&srcdat,&created);
if (status < 0)
return status;
if (srcdat == 0)
return 0;
srcdat->ProcessSenderInfo(ntptime,rtptime,packetcount,octetcount,receivetime);
// Call the callback
if (created)
OnNewSource(srcdat);
return 0;
}
int RTPSources::ProcessRTCPReportBlock(u_int32_t ssrc,u_int8_t fractionlost,int32_t lostpackets,
u_int32_t exthighseqnr,u_int32_t jitter,u_int32_t lsr,
u_int32_t dlsr,const RTPTime &receivetime,const RTPAddress *senderaddress)
{
RTPInternalSourceData *srcdat;
bool created;
int status;
status = GetRTCPSourceData(ssrc,senderaddress,&srcdat,&created);
if (status < 0)
return status;
if (srcdat == 0)
return 0;
srcdat->ProcessReportBlock(fractionlost,lostpackets,exthighseqnr,jitter,lsr,dlsr,receivetime);
// Call the callback
if (created)
OnNewSource(srcdat);
return 0;
}
int RTPSources::ProcessSDESNormalItem(u_int32_t ssrc,RTCPSDESPacket::ItemType t,size_t itemlength,
const void *itemdata,const RTPTime &receivetime,const RTPAddress *senderaddress)
{
RTPInternalSourceData *srcdat;
bool created,cnamecollis;
int status;
u_int8_t id;
bool prevactive;
switch(t)
{
case RTCPSDESPacket::CNAME:
id = RTCP_SDES_ID_CNAME;
break;
case RTCPSDESPacket::NAME:
id = RTCP_SDES_ID_NAME;
break;
case RTCPSDESPacket::EMAIL:
id = RTCP_SDES_ID_EMAIL;
break;
case RTCPSDESPacket::PHONE:
id = RTCP_SDES_ID_PHONE;
break;
case RTCPSDESPacket::LOC:
id = RTCP_SDES_ID_LOCATION;
break;
case RTCPSDESPacket::TOOL:
id = RTCP_SDES_ID_TOOL;
break;
case RTCPSDESPacket::NOTE:
id = RTCP_SDES_ID_NOTE;
break;
default:
return ERR_RTP_SOURCES_ILLEGALSDESTYPE;
}
status = GetRTCPSourceData(ssrc,senderaddress,&srcdat,&created);
if (status < 0)
return status;
if (srcdat == 0)
return 0;
prevactive = srcdat->IsActive();
status = srcdat->ProcessSDESItem(id,(const u_int8_t *)itemdata,itemlength,receivetime,&cnamecollis);
if (!prevactive && srcdat->IsActive())
activecount++;
// Call the callback
if (created)
OnNewSource(srcdat);
if (cnamecollis)
OnCNAMECollision(srcdat,senderaddress,(const u_int8_t *)itemdata,itemlength);
return status;
}
#ifdef RTP_SUPPORT_SDESPRIV
int RTPSources::ProcessSDESPrivateItem(u_int32_t ssrc,size_t prefixlen,const void *prefixdata,
size_t valuelen,const void *valuedata,const RTPTime &receivetime,
const RTPAddress *senderaddress)
{
RTPInternalSourceData *srcdat;
bool created;
int status;
status = GetRTCPSourceData(ssrc,senderaddress,&srcdat,&created);
if (status < 0)
return status;
if (srcdat == 0)
return 0;
status = srcdat->ProcessPrivateSDESItem((const u_int8_t *)prefixdata,prefixlen,(const u_int8_t *)valuedata,valuelen,receivetime);
// Call the callback
if (created)
OnNewSource(srcdat);
return status;
}
#endif //RTP_SUPPORT_SDESPRIV
int RTPSources::ProcessBYE(u_int32_t ssrc,size_t reasonlength,const void *reasondata,
const RTPTime &receivetime,const RTPAddress *senderaddress)
{
RTPInternalSourceData *srcdat;
bool created;
int status;
bool prevactive;
status = GetRTCPSourceData(ssrc,senderaddress,&srcdat,&created);
if (status < 0)
return status;
if (srcdat == 0)
return 0;
// we'll ignore BYE packets for our own ssrc
if (srcdat == owndata)
return 0;
prevactive = srcdat->IsActive();
srcdat->ProcessBYEPacket((const u_int8_t *)reasondata,reasonlength,receivetime);
if (prevactive && !srcdat->IsActive())
activecount--;
// Call the callback
if (created)
OnNewSource(srcdat);
OnBYEPacket(srcdat);
return 0;
}
int RTPSources::ObtainSourceDataInstance(u_int32_t ssrc,RTPInternalSourceData **srcdat,bool *created)
{
RTPInternalSourceData *srcdat2;
int status;
if (sourcelist.GotoElement(ssrc) < 0) // No entry for this source
{
srcdat2 = new RTPInternalSourceData(ssrc);
if (srcdat2 == 0)
return ERR_RTP_OUTOFMEM;
if ((status = sourcelist.AddElement(ssrc,srcdat2)) < 0)
{
delete srcdat2;
return status;
}
*srcdat = srcdat2;
*created = true;
totalcount++;
}
else
{
*srcdat = sourcelist.GetCurrentElement();
*created = false;
}
return 0;
}
int RTPSources::GetRTCPSourceData(u_int32_t ssrc,const RTPAddress *senderaddress,
RTPInternalSourceData **srcdat2,bool *newsource)
{
int status;
bool created;
RTPInternalSourceData *srcdat;
*srcdat2 = 0;
if ((status = ObtainSourceDataInstance(ssrc,&srcdat,&created)) < 0)
return status;
if (created)
{
if ((status = srcdat->SetRTCPDataAddress(senderaddress)) < 0)
return status;
}
else // got a previously existing source
{
if (CheckCollision(srcdat,senderaddress,false))
return 0; // ignore packet on collision
}
*srcdat2 = srcdat;
*newsource = created;
return 0;
}
int RTPSources::UpdateReceiveTime(u_int32_t ssrc,const RTPTime &receivetime,const RTPAddress *senderaddress)
{
RTPInternalSourceData *srcdat;
bool created;
int status;
status = GetRTCPSourceData(ssrc,senderaddress,&srcdat,&created);
if (status < 0)
return status;
if (srcdat == 0)
return 0;
// We got valid SSRC info
srcdat->UpdateMessageTime(receivetime);
// Call the callback
if (created)
OnNewSource(srcdat);
return 0;
}
void RTPSources::Timeout(const RTPTime &curtime,const RTPTime &timeoutdelay)
{
int newtotalcount = 0;
int newsendercount = 0;
int newactivecount = 0;
RTPTime checktime = curtime;
checktime -= timeoutdelay;
sourcelist.GotoFirstElement();
while (sourcelist.HasCurrentElement())
{
RTPInternalSourceData *srcdat = sourcelist.GetCurrentElement();
RTPTime lastmsgtime = srcdat->INF_GetLastMessageTime();
// we don't want to time out ourselves
if ((srcdat != owndata) && (lastmsgtime < checktime)) // timeout
{
totalcount--;
if (srcdat->IsSender())
sendercount--;
if (srcdat->IsActive())
activecount--;
sourcelist.DeleteCurrentElement();
OnTimeout(srcdat);
OnRemoveSource(srcdat);
delete srcdat;
}
else
{
newtotalcount++;
if (srcdat->IsSender())
newsendercount++;
if (srcdat->IsActive())
newactivecount++;
sourcelist.GotoNextElement();
}
}
#ifdef RTPDEBUG
if (newtotalcount != totalcount)
{
std::cout << "New total count " << newtotalcount << " doesnt match old total count " << totalcount << std::endl;
SafeCountTotal();
}
if (newsendercount != sendercount)
{
std::cout << "New sender count " << newsendercount << " doesnt match old sender count " << sendercount << std::endl;
SafeCountSenders();
}
if (newactivecount != activecount)
{
std::cout << "New active count " << newactivecount << " doesnt match old active count " << activecount << std::endl;
SafeCountActive();
}
#endif // RTPDEBUG
totalcount = newtotalcount; // just to play it safe
sendercount = newsendercount;
activecount = newactivecount;
}
void RTPSources::SenderTimeout(const RTPTime &curtime,const RTPTime &timeoutdelay)
{
int newtotalcount = 0;
int newsendercount = 0;
int newactivecount = 0;
RTPTime checktime = curtime;
checktime -= timeoutdelay;
sourcelist.GotoFirstElement();
while (sourcelist.HasCurrentElement())
{
RTPInternalSourceData *srcdat = sourcelist.GetCurrentElement();
newtotalcount++;
if (srcdat->IsActive())
newactivecount++;
if (srcdat->IsSender())
{
RTPTime lastrtppacktime = srcdat->INF_GetLastRTPPacketTime();
if (lastrtppacktime < checktime) // timeout
{
srcdat->ClearSenderFlag();
sendercount--;
}
else
newsendercount++;
}
sourcelist.GotoNextElement();
}
#ifdef RTPDEBUG
if (newtotalcount != totalcount)
{
std::cout << "New total count " << newtotalcount << " doesnt match old total count " << totalcount << std::endl;
SafeCountTotal();
}
if (newsendercount != sendercount)
{
std::cout << "New sender count " << newsendercount << " doesnt match old sender count " << sendercount << std::endl;
SafeCountSenders();
}
if (newactivecount != activecount)
{
std::cout << "New active count " << newactivecount << " doesnt match old active count " << activecount << std::endl;
SafeCountActive();
}
#endif // RTPDEBUG
totalcount = newtotalcount; // just to play it safe
sendercount = newsendercount;
activecount = newactivecount;
}
void RTPSources::BYETimeout(const RTPTime &curtime,const RTPTime &timeoutdelay)
{
int newtotalcount = 0;
int newsendercount = 0;
int newactivecount = 0;
RTPTime checktime = curtime;
checktime -= timeoutdelay;
sourcelist.GotoFirstElement();
while (sourcelist.HasCurrentElement())
{
RTPInternalSourceData *srcdat = sourcelist.GetCurrentElement();
if (srcdat->ReceivedBYE())
{
RTPTime byetime = srcdat->GetBYETime();
if ((srcdat != owndata) && (checktime > byetime))
{
totalcount--;
if (srcdat->IsSender())
sendercount--;
if (srcdat->IsActive())
activecount--;
sourcelist.DeleteCurrentElement();
OnBYETimeout(srcdat);
OnRemoveSource(srcdat);
delete srcdat;
}
else
{
newtotalcount++;
if (srcdat->IsSender())
newsendercount++;
if (srcdat->IsActive())
newactivecount++;
sourcelist.GotoNextElement();
}
}
else
{
newtotalcount++;
if (srcdat->IsSender())
newsendercount++;
if (srcdat->IsActive())
newactivecount++;
sourcelist.GotoNextElement();
}
}
#ifdef RTPDEBUG
if (newtotalcount != totalcount)
{
std::cout << "New total count " << newtotalcount << " doesnt match old total count " << totalcount << std::endl;
SafeCountTotal();
}
if (newsendercount != sendercount)
{
std::cout << "New sender count " << newsendercount << " doesnt match old sender count " << sendercount << std::endl;
SafeCountSenders();
}
if (newactivecount != activecount)
{
std::cout << "New active count " << newactivecount << " doesnt match old active count " << activecount << std::endl;
SafeCountActive();
}
#endif // RTPDEBUG
totalcount = newtotalcount; // just to play it safe
sendercount = newsendercount;
activecount = newactivecount;
}
void RTPSources::NoteTimeout(const RTPTime &curtime,const RTPTime &timeoutdelay)
{
int newtotalcount = 0;
int newsendercount = 0;
int newactivecount = 0;
RTPTime checktime = curtime;
checktime -= timeoutdelay;
sourcelist.GotoFirstElement();
while (sourcelist.HasCurrentElement())
{
RTPInternalSourceData *srcdat = sourcelist.GetCurrentElement();
u_int8_t *note;
size_t notelen;
note = srcdat->SDES_GetNote(¬elen);
if (notelen != 0) // Note has been set
{
RTPTime notetime = srcdat->INF_GetLastSDESNoteTime();
if (checktime > notetime)
{
srcdat->ClearNote();
OnNoteTimeout(srcdat);
}
}
newtotalcount++;
if (srcdat->IsSender())
newsendercount++;
if (srcdat->IsActive())
newactivecount++;
sourcelist.GotoNextElement();
}
#ifdef RTPDEBUG
if (newtotalcount != totalcount)
{
std::cout << "New total count " << newtotalcount << " doesnt match old total count " << totalcount << std::endl;
SafeCountTotal();
}
if (newsendercount != sendercount)
{
std::cout << "New sender count " << newsendercount << " doesnt match old sender count " << sendercount << std::endl;
SafeCountSenders();
}
if (newactivecount != activecount)
{
std::cout << "New active count " << newactivecount << " doesnt match old active count " << activecount << std::endl;
SafeCountActive();
}
#endif // RTPDEBUG
totalcount = newtotalcount; // just to play it safe
sendercount = newsendercount;
activecount = newactivecount;
}
void RTPSources::MultipleTimeouts(const RTPTime &curtime,const RTPTime &sendertimeout,const RTPTime &byetimeout,const RTPTime &generaltimeout,const RTPTime ¬etimeout)
{
int newtotalcount = 0;
int newsendercount = 0;
int newactivecount = 0;
RTPTime senderchecktime = curtime;
RTPTime byechecktime = curtime;
RTPTime generaltchecktime = curtime;
RTPTime notechecktime = curtime;
senderchecktime -= sendertimeout;
byechecktime -= byetimeout;
generaltchecktime -= generaltimeout;
notechecktime -= notetimeout;
sourcelist.GotoFirstElement();
while (sourcelist.HasCurrentElement())
{
RTPInternalSourceData *srcdat = sourcelist.GetCurrentElement();
bool deleted,issender,isactive;
bool byetimeout,normaltimeout,notetimeout;
u_int8_t *note;
size_t notelen;
issender = srcdat->IsSender();
isactive = srcdat->IsActive();
deleted = false;
byetimeout = false;
normaltimeout = false;
notetimeout = false;
note = srcdat->SDES_GetNote(¬elen);
if (notelen != 0) // Note has been set
{
RTPTime notetime = srcdat->INF_GetLastSDESNoteTime();
if (notechecktime > notetime)
{
notetimeout = true;
srcdat->ClearNote();
}
}
if (srcdat->ReceivedBYE())
{
RTPTime byetime = srcdat->GetBYETime();
if ((srcdat != owndata) && (byechecktime > byetime))
{
sourcelist.DeleteCurrentElement();
deleted = true;
byetimeout = true;
}
}
if (!deleted)
{
RTPTime lastmsgtime = srcdat->INF_GetLastMessageTime();
if ((srcdat != owndata) && (lastmsgtime < generaltchecktime))
{
sourcelist.DeleteCurrentElement();
deleted = true;
normaltimeout = true;
}
}
if (!deleted)
{
newtotalcount++;
if (issender)
{
RTPTime lastrtppacktime = srcdat->INF_GetLastRTPPacketTime();
if (lastrtppacktime < senderchecktime)
{
srcdat->ClearSenderFlag();
sendercount--;
}
else
newsendercount++;
}
if (isactive)
newactivecount++;
if (notetimeout)
OnNoteTimeout(srcdat);
sourcelist.GotoNextElement();
}
else // deleted entry
{
if (issender)
sendercount--;
if (isactive)
activecount--;
totalcount--;
if (byetimeout)
OnBYETimeout(srcdat);
if (normaltimeout)
OnTimeout(srcdat);
delete srcdat;
}
}
#ifdef RTPDEBUG
if (newtotalcount != totalcount)
{
SafeCountTotal();
std::cout << "New total count " << newtotalcount << " doesnt match old total count " << totalcount << std::endl;
}
if (newsendercount != sendercount)
{
SafeCountSenders();
std::cout << "New sender count " << newsendercount << " doesnt match old sender count " << sendercount << std::endl;
}
if (newactivecount != activecount)
{
std::cout << "New active count " << newactivecount << " doesnt match old active count " << activecount << std::endl;
SafeCountActive();
}
#endif // RTPDEBUG
totalcount = newtotalcount; // just to play it safe
sendercount = newsendercount;
activecount = newactivecount;
}
#ifdef RTPDEBUG
void RTPSources::Dump()
{
std::cout << "Total count: " << totalcount << std::endl;
std::cout << "Sender count: " << sendercount << std::endl;
std::cout << "Active count: " << activecount << std::endl;
if (GotoFirstSource())
{
do
{
RTPSourceData *s;
s = GetCurrentSourceInfo();
s->Dump();
std::cout << std::endl;
} while (GotoNextSource());
}
}
void RTPSources::SafeCountTotal()
{
int count = 0;
if (GotoFirstSource())
{
do
{
count++;
} while (GotoNextSource());
}
std::cout << "Actual total count: " << count << std::endl;
}
void RTPSources::SafeCountSenders()
{
int count = 0;
if (GotoFirstSource())
{
do
{
RTPSourceData *s;
s = GetCurrentSourceInfo();
if (s->IsSender())
count++;
} while (GotoNextSource());
}
std::cout << "Actual sender count: " << count << std::endl;
}
void RTPSources::SafeCountActive()
{
int count = 0;
if (GotoFirstSource())
{
do
{
RTPSourceData *s;
s = GetCurrentSourceInfo();
if (s->IsActive())
count++;
} while (GotoNextSource());
}
std::cout << "Actual active count: " << count << std::endl;
}
#endif // RTPDEBUG
bool RTPSources::CheckCollision(RTPInternalSourceData *srcdat,const RTPAddress *senderaddress,bool isrtp)
{
bool isset,otherisset;
const RTPAddress *addr,*otheraddr;
if (isrtp)
{
isset = srcdat->IsRTPAddressSet();
addr = srcdat->GetRTPDataAddress();
otherisset = srcdat->IsRTCPAddressSet();
otheraddr = srcdat->GetRTCPDataAddress();
}
else
{
isset = srcdat->IsRTCPAddressSet();
addr = srcdat->GetRTCPDataAddress();
otherisset = srcdat->IsRTPAddressSet();
otheraddr = srcdat->GetRTPDataAddress();
}
if (!isset)
{
if (otherisset) // got other address, can check if it comes from same host
{
if (otheraddr == 0) // other came from our own session
{
if (senderaddress != 0)
{
OnSSRCCollision(srcdat,senderaddress,isrtp);
return true;
}
// Ok, store it
if (isrtp)
srcdat->SetRTPDataAddress(senderaddress);
else
srcdat->SetRTCPDataAddress(senderaddress);
}
else
{
if (!otheraddr->IsFromSameHost(senderaddress))
{
OnSSRCCollision(srcdat,senderaddress,isrtp);
return true;
}
// Ok, comes from same host, store the address
if (isrtp)
srcdat->SetRTPDataAddress(senderaddress);
else
srcdat->SetRTCPDataAddress(senderaddress);
}
}
else // no other address, store this one
{
if (isrtp)
srcdat->SetRTPDataAddress(senderaddress);
else
srcdat->SetRTCPDataAddress(senderaddress);
}
}
else // already got an address
{
if (addr == 0)
{
if (senderaddress != 0)
{
OnSSRCCollision(srcdat,senderaddress,isrtp);
return true;
}
}
else
{
if (!addr->IsSameAddress(senderaddress))
{
OnSSRCCollision(srcdat,senderaddress,isrtp);
return true;
}
}
}
return false;
}
| AlekSi/Jabbin | third-party/jrtplib/rtpsources.cpp | C++ | gpl-2.0 | 32,695 |
<?php
/*
* @version $Id: HEADER 15930 2011-10-30 15:47:55Z tsmr $
-------------------------------------------------------------------------
typology plugin for GLPI
Copyright (C) 2009-2022 by the typology Development Team.
https://github.com/InfotelGLPI/typology
-------------------------------------------------------------------------
LICENSE
This file is part of typology.
typology is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
typology is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with typology. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
include ('../../../inc/includes.php');
$rulecollection = new PluginTypologyRuleTypologyCollection($_SESSION['glpiactive_entity']);
include (GLPI_ROOT . "/front/rule.common.form.php");
| InfotelGLPI/typology | front/ruletypology.form.php | PHP | gpl-2.0 | 1,264 |
#define DEBUG_RECONSTRUCTED
#undef DEBUG_RECONSTRUCTED
using System;
using LibDL.Interface;
using LibDL.Utils;
using System.Threading;
using System.Threading.Tasks;
using LibDL.ActivationFunction;
namespace LibDL.Learning
{
public class ContrastiveDivergence : IDisposable
{
//tambahan parameter momentum pada update gradien decent
private double momentum = 0.9;
public double Momentum
{
get { return momentum; }
set { momentum = value; }
}
//learning rate pada proses pelatihan (update gradien decent)
private double learningRate = 0.1;
public double LearningRate
{
get { return learningRate; }
set { learningRate = value; }
}
//weigt decay untuk tambahan pada gradien, Istilah tambahan turunan dari fungsi yang melakukan pinalize
//"menghukum" weight yg tertalu besar
private double weightDecay = 0.01;
public double WeightDecay
{
get { return weightDecay; }
set { weightDecay = value; }
}
//step pada gibbs sampling
//parameter untuk membentuk bobot pada gradien dan membentuk output product dari positive gradien dan negative gradien
//yang dihasilkan dari visible dan hidden unit
private double[][] weightsGradient;
private double[] vBiasGradient;
private double[] hBiasGradient;
//parameter update nilai pada bobot, output dari visible dan hidden
private double[][] weightsUpdates;
private double[] vBiasUpdates;
private double[] hBiasUpdates;
private int inputsCount;
private int hiddenCount;
private StochasticNetworkLayer hidden;
private StochasticNetworkLayer visible;
private ThreadLocal<ParallelStorage> storage;
#if DEBUG_RECONSTRUCTED
public ReconstructImage Data = new ReconstructImage();
#endif
public ContrastiveDivergence(RBM network)
{
init(network.Hidden, network.Visible);
}
public ContrastiveDivergence(StochasticNetworkLayer hidden, StochasticNetworkLayer visible)
{
init(hidden, visible);
}
/*
* Inisialisasikan gradien
*
*/
private void init(StochasticNetworkLayer hidden, StochasticNetworkLayer visible)
{
//inisialisasi visible dan hidden unit
this.hidden = hidden;
this.visible = visible;
//input count dari banyaknya neuron visible layer pada RBM
inputsCount = hidden.InputsCount;
//hidden count dari banykanya heuron pada hidden layer pada RBM
hiddenCount = hidden.Neurons.Length;
//inisialisasi bobot gradien matrik dengan ukuran visible x hidden
weightsGradient = new double[inputsCount][];
for (int i = 0; i < weightsGradient.Length; i++)
weightsGradient[i] = new double[hiddenCount];
//buat objek visible/hidden gradien
vBiasGradient = new double[inputsCount];
hBiasGradient = new double[hiddenCount];
//inisialisasi bobot update matrik dengan ukuran matrik vsible x hidden
weightsUpdates = new double[inputsCount][];
for (int i = 0; i < weightsUpdates.Length; i++)
weightsUpdates[i] = new double[hiddenCount];
//buat objek update visible/hidden
vBiasUpdates = new double[inputsCount];
hBiasUpdates = new double[hiddenCount];
//siapkan penyimpanan local pada class pararellstorage
storage = new ThreadLocal<ParallelStorage>(() =>
new ParallelStorage(inputsCount, hiddenCount));
}
/// <summary>
/// Not supported.
/// </summary>
///
public double Run(double[] input)
{
throw new NotSupportedException();
}
public double RunEpoch(double[][] input)
{
// Initialize iteration karena training ini terjadi pada setiap perulangan/iterasi (epoch) maka nilai bobot gradien,visble gradien,
// hidden gradien dari epoch sebelumnya harus dibersihkan terlebih dahulu nilai-nilainya.
for (int i = 0; i < weightsGradient.Length; i++)
Array.Clear(weightsGradient[i], 0, weightsGradient[i].Length);
Array.Clear(hBiasGradient, 0, hBiasGradient.Length);
Array.Clear(vBiasGradient, 0, vBiasGradient.Length);
// HItung gradien dan erro pada model (error reconstruction dari layer)
double error = ComputeGradient(input);
// calculate weights updates
CalculateUpdates(input);
// update the network
UpdateNetwork();
#if DEBUG_RECONSTRUCTED
Data.Save(@"D:\reconstruct");
#endif
return error;
}
private double ComputeGradient(double[][] input)
{
double errors = 0;
#if NET35
var partial = storage.Value.Clear();
for (int i = 0; i < input.Length; i++)
{
int observationIndex = i;
#else
Object lockObj = new Object();
// For each training instance
Parallel.For(0, input.Length,
#if DEBUG
new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount / 2 + Environment.ProcessorCount / 3 },
#endif
// Initialize
() => storage.Value.Clear(),
// Map
(observationIndex, loopState, partial) =>
#endif
{
var observation = input[observationIndex];
var probability = partial.OriginalProbability;
var activations = partial.OriginalActivations;
var reconstruction = partial.ReconstructedInput;
var reprobability = partial.ReconstructedProbs;
var weightGradient = partial.WeightGradient;
var hiddenGradient = partial.HBiasGradient;
var visibleGradient = partial.VBiasGradient;
// for information: http://www.cs.toronto.edu/~hinton/code/rbm.m
// 1. Compute a forward pass. The network is being
// driven by data, so we will gather activations
for (int j = 0; j < hidden.Neurons.Length; j++)
{
probability[j] = hidden.Neurons[j].Compute(observation); // output probabilities
activations[j] = hidden.Neurons[j].Generate(probability[j]); // state activations ==> h0
}
// 2. Reconstruct inputs from previous outputs ==> v1
for (int j = 0; j < visible.Neurons.Length; j++)
reconstruction[j] = visible.Neurons[j].Compute(activations);
#if DEBUG_RECONSTRUCTED
Data.reconstruct.Add(reconstruction);
#endif
// 3. Compute outputs for the reconstruction. The network
// is now being driven by reconstructions, so we should
// gather the output probabilities without sampling ==> h1
for (int j = 0; j < hidden.Neurons.Length; j++)
reprobability[j] = hidden.Neurons[j].Compute(reconstruction);
// 4.1. Compute positive associations
for (int k = 0; k < observation.Length; k++)
for (int j = 0; j < probability.Length; j++)
weightGradient[k][j] += observation[k] * probability[j];
for (int j = 0; j < hiddenGradient.Length; j++)
hiddenGradient[j] += probability[j];
for (int j = 0; j < visibleGradient.Length; j++)
visibleGradient[j] += observation[j];
// 4.2. Compute negative associations
for (int k = 0; k < reconstruction.Length; k++)
for (int j = 0; j < reprobability.Length; j++)
weightGradient[k][j] -= reconstruction[k] * reprobability[j];
for (int j = 0; j < reprobability.Length; j++)
hiddenGradient[j] -= reprobability[j];
for (int j = 0; j < reconstruction.Length; j++)
visibleGradient[j] -= reconstruction[j];
// Compute current error
for (int j = 0; j < observation.Length; j++)
{
double e = observation[j] - reconstruction[j];
partial.ErrorSumOfSquares += e * e;
}
#if !NET35
return partial; // Report partial solution
},
// Reduce
(partial) =>
{
lock (lockObj)
{
// Accumulate partial solutions
for (int i = 0; i < weightsGradient.Length; i++)
for (int j = 0; j < weightsGradient[i].Length; j++)
weightsGradient[i][j] += partial.WeightGradient[i][j];
for (int i = 0; i < hBiasGradient.Length; i++)
hBiasGradient[i] += partial.HBiasGradient[i];
for (int i = 0; i < vBiasGradient.Length; i++)
vBiasGradient[i] += partial.VBiasGradient[i];
errors += partial.ErrorSumOfSquares;
}
});
#else
}
}
weightsGradient = partial.WeightGradient;
hiddenBiasGradient = partial.HiddenBiasGradient;
visibleBiasGradient = partial.VisibleBiasGradient;
errors = partial.ErrorSumOfSquares;
#endif
return errors;
}
private void CalculateUpdates(double[][] input)
{
double rate = learningRate;
// Assume all neurons in the layer have the same act function
rate = learningRate / (input.Length);
// 5. Compute gradient descent updates
for (int i = 0; i < weightsGradient.Length; i++)
for (int j = 0; j < weightsGradient[i].Length; j++)
weightsUpdates[i][j] = momentum * weightsUpdates[i][j]
+ (rate * weightsGradient[i][j]);
for (int i = 0; i < hBiasUpdates.Length; i++)
hBiasUpdates[i] = momentum * hBiasUpdates[i]
+ (rate * hBiasGradient[i]);
for (int i = 0; i < vBiasUpdates.Length; i++)
vBiasUpdates[i] = momentum * vBiasUpdates[i]
+ (rate * vBiasGradient[i]);
//System.Diagnostics.Debug.Assert(!weightsGradient.HasNaN());
//System.Diagnostics.Debug.Assert(!vBiasUpdates.HasNaN());
//System.Diagnostics.Debug.Assert(!hBiasUpdates.HasNaN());
}
private void UpdateNetwork()
{
// 6.1 Update hidden layer weights
for (int i = 0; i < hidden.Neurons.Length; i++)
{
StochasticNeuron neuron = hidden.Neurons[i];
for (int j = 0; j < neuron.Weights.Length; j++)
neuron.Weights[j] += weightsUpdates[j][i] - learningRate * weightDecay * neuron.Weights[j];
neuron.Threshold += hBiasUpdates[i];
}
// 6.2 Update visible layer with reverse weights
for (int i = 0; i < visible.Neurons.Length; i++)
visible.Neurons[i].Threshold += vBiasUpdates[i];
visible.CopyReversedWeightsFrom(hidden);
}
private class ParallelStorage
{
public double[][] WeightGradient { get; set; }
public double[] VBiasGradient { get; set; }
public double[] HBiasGradient { get; set; }
public double[] OriginalActivations { get; set; }
public double[] OriginalProbability { get; set; }
public double[] ReconstructedInput { get; set; }
public double[] ReconstructedProbs { get; set; }
public double ErrorSumOfSquares { get; set; }
public ParallelStorage(int inputsCount, int hiddenCount)
{
WeightGradient = new double[inputsCount][];
for (int i = 0; i < WeightGradient.Length; i++)
WeightGradient[i] = new double[hiddenCount];
VBiasGradient = new double[inputsCount];
HBiasGradient = new double[hiddenCount];
OriginalActivations = new double[hiddenCount];
OriginalProbability = new double[hiddenCount];
ReconstructedInput = new double[inputsCount];
ReconstructedProbs = new double[hiddenCount];
}
public ParallelStorage Clear()
{
ErrorSumOfSquares = 0;
for (int i = 0; i < WeightGradient.Length; i++)
Array.Clear(WeightGradient[i], 0, WeightGradient[i].Length);
Array.Clear(VBiasGradient, 0, VBiasGradient.Length);
Array.Clear(HBiasGradient, 0, HBiasGradient.Length);
return this;
}
}
#region IDisposable members
/// <summary>
/// Performs application-defined tasks associated with
/// freeing, releasing, or resetting unmanaged resources.
/// </summary>
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
///
/// <param name="disposing"><c>true</c> to release both managed and unmanaged
/// resources; <c>false</c> to release only unmanaged resources.</param>
///
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
if (storage != null)
{
storage.Dispose();
storage = null;
}
}
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="ContrastiveDivergenceLearning"/> is reclaimed by garbage collection.
/// </summary>
///
~ContrastiveDivergence()
{
Dispose(false);
}
#endregion
}
}
| sukasenyumm/DL | LibDL/Learning/ContrastiveDivergence.cs | C# | gpl-2.0 | 14,903 |
<?php
/**
* Created by PhpStorm.
* User: Anh Tuan
* Date: 4/22/14
* Time: 12:27 AM
*/
//////////////////////////////////////////////////////////////////
// Highlight shortcode
//////////////////////////////////////////////////////////////////
add_shortcode( 'highlight', 'shortcode_highlight' );
function shortcode_highlight( $atts, $content = null ) {
$atts = shortcode_atts(
array(
'color' => 'yellow',
), $atts );
if ( $atts['color'] == 'black' ) {
return '<span class="highlight2" style="background-color:' . $atts['color'] . ';">' . do_shortcode( $content ) . '</span>';
} else {
return '<span class="highlight1" style="background-color:' . $atts['color'] . ';">' . do_shortcode( $content ) . '</span>';
}
} | yogaValdlabs/shopingchart | wp-content/themes/aloxo/inc/shortcodes/highlight/highlight.php | PHP | gpl-2.0 | 734 |
<?php
/**
* Page Template
*
* Loaded automatically by index.php?main_page=checkout_confirmation.<br />
* Displays final checkout details, cart, payment and shipping info details.
*
* @package templateSystem
* @copyright Copyright 2003-2006 Zen Cart Development Team
* @copyright Portions Copyright 2003 osCommerce
* @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
* @version $Id: tpl_checkout_confirmation_default.php 6247 2007-04-21 21:34:47Z wilt $
*/
?>
<div class="centerColumn" id="checkoutConfirmDefault">
<h1 id="checkoutConfirmDefaultHeading"><?php echo HEADING_TITLE; ?></h1>
<?php if ($messageStack->size('redemptions') > 0) echo $messageStack->output('redemptions'); ?>
<?php if ($messageStack->size('checkout_confirmation') > 0) echo $messageStack->output('checkout_confirmation'); ?>
<?php if ($messageStack->size('checkout') > 0) echo $messageStack->output('checkout'); ?>
<div id="checkoutBillto" style="display:none">
<h2 id="checkoutConfirmDefaultBillingAddress"><?php echo HEADING_BILLING_ADDRESS; ?></h2>
<?php if (!$flagDisablePaymentAddressChange) { ?>
<div class="buttonRow forward"><?php echo '<a href="' . zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL') . '">' . zen_image_button(BUTTON_IMAGE_EDIT_SMALL, BUTTON_EDIT_SMALL_ALT) . '</a>'; ?></div>
<?php } ?>
<address><?php echo zen_address_format($order->billing['format_id'], $order->billing, 1, ' ', '<br />'); ?></address>
<?php
$class =& $_SESSION['payment'];
?>
<h3 id="checkoutConfirmDefaultPayment"><?php echo HEADING_PAYMENT_METHOD; ?></h3>
<h4 id="checkoutConfirmDefaultPaymentTitle"><?php echo $GLOBALS[$class]->title; ?></h4>
<?php
if (is_array($payment_modules->modules)) {
if ($confirmation = $payment_modules->confirmation()) {
?>
<div class="important"><?php echo $confirmation['title']; ?></div>
<?php
}
?>
<div class="important">
<?php
for ($i=0, $n=is_array($confirmation['fields'])?sizeof($confirmation['fields']):0; $i<$n; $i++) {
?>
<div class="back"><?php echo $confirmation['fields'][$i]['title']; ?></div>
<div ><?php echo $confirmation['fields'][$i]['field']; ?></div>
<?php
}
?>
</div>
<?php
}
?>
<br class="clearBoth" />
</div>
<?php
if ($_SESSION['sendto'] != false) {
?>
<div id="checkoutShipto">
<h2 id="checkoutConfirmDefaultShippingAddress"><?php echo HEADING_DELIVERY_ADDRESS; ?></h2>
<div class="buttonRow forward" style="display:none"><?php echo '<a href="' . $editShippingButtonLink . '">' . zen_image_button(BUTTON_IMAGE_EDIT_SMALL, BUTTON_EDIT_SMALL_ALT) . '</a>'; ?></div>
<address><?php echo zen_address_format($order->delivery['format_id'], $order->delivery, 1, ' ', '<br />'); ?></address>
<?php
if ($order->info['shipping_method']) {
?>
<h3 id="checkoutConfirmDefaultShipment"><?php echo HEADING_SHIPPING_METHOD; ?></h3>
<h4 id="checkoutConfirmDefaultShipmentTitle"><?php echo $order->info['shipping_method']; ?></h4>
<?php
}
?>
</div>
<?php
}
?>
<br class="clearBoth" />
<hr />
<?php
//print_r($order->info);
if ($order->info['comments']) {
?>
<h2 id="checkoutConfirmDefaultHeadingComments"><?php echo HEADING_ORDER_COMMENTS; ?></h2>
<!---<div class="buttonRow forward"><?php echo '<a href="' . zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL') . '">' . zen_image_button(BUTTON_IMAGE_EDIT_SMALL, BUTTON_EDIT_SMALL_ALT) . '</a>'; ?></div> -->
<div><?php echo (empty($order->info['comments']) ? NO_COMMENTS_TEXT : nl2br(zen_output_string_protected($order->info['comments'])) . zen_draw_hidden_field('comments', $order->info['comments'])); ?></div>
<br class="clearBoth" />
<?php
}
?>
<hr />
<h2 id="checkoutConfirmDefaultHeadingCart"><?php echo HEADING_PRODUCTS; ?></h2>
<div class="buttonRow forward" style="display:none"><?php echo '<a href="' . zen_href_link(FILENAME_SHOPPING_CART, '', 'SSL') . '">' . zen_image_button(BUTTON_IMAGE_EDIT_SMALL, BUTTON_EDIT_SMALL_ALT) . '</a>'; ?></div>
<br class="clearBoth" />
<?php if ($flagAnyOutOfStock) { ?>
<?php if (STOCK_ALLOW_CHECKOUT == 'true') { ?>
<div class="messageStackError"><?php echo OUT_OF_STOCK_CAN_CHECKOUT; ?></div>
<?php } else { ?>
<div class="messageStackError"><?php echo OUT_OF_STOCK_CANT_CHECKOUT; ?></div>
<?php } //endif STOCK_ALLOW_CHECKOUT ?>
<?php } //endif flagAnyOutOfStock ?>
<table border="0" width="100%" cellspacing="0" cellpadding="0" id="cartContentsDisplay">
<tr class="cartTableHeading">
<th scope="col" id="ccTypeHeading" width="10" class="showBorder"><?php echo TABLE_HEADING_TERMS; ?></th>
<th scope="col" id="ccProductsHeading" class="showBorder"><?php echo TABLE_HEADING_PRODUCTS; ?></th>
<th scope="col" id="ccQuantityHeading" width="10" class="showBorder"><?php echo TABLE_HEADING_QUANTITY; ?></th>
<th scope="col" id="ccProductsHeading" width="5" class="showBorder"><?php echo ($order->products[0]['payment_plan'] && ($order->products[0]['products_type'] != WAP_TYPE_ID)) ? TABLE_HEADING_ANNUAL_COST : TABLE_HEADING_ITEM_COST; ?></th>
<th scope="col" id="ccTotalHeading" class="showBorder"><?php echo ($order->products[0]['payment_plan'] && ($order->products[0]['products_type'] != WAP_TYPE_ID)) ? TABLE_HEADING_TOTAL_COST : TABLE_HEADING_TOTAL; ?></th>
</tr>
<?php
// bubble WAP config to the bottom of the list
$leaveInOrder = [];
$pushToEnd = [];
foreach ($order->products as $product) {
if( in_array($product["id"], [WAP_CONFIG_SERVICE,WAP_CLOUD_MANAGEMENT]) ) {
$pushToEnd[] = $product;
} else {
$leaveInOrder[] = $product;
}
}
$order->products = array_merge($leaveInOrder, $pushToEnd);
?>
<?php // now loop thru all products to display quantity and price ?>
<?php for ($i=0, $n=sizeof($order->products); $i<$n; $i++) { ?>
<tr class="<?php echo $order->products[$i]['rowClass']; ?>">
<td class="cartProductDisplay showBorder"><a href="<?php echo $order->products[$i]['terms_link']; ?>"><?php echo $order->products[$i]['type_name']; ?></a></td>
<td class="cartProductDisplay showBorder"><?php echo $order->products[$i]['name']; ?>
<?php echo $stock_check[$i]; ?>
<?php // if there are attributes, loop thru them and display one per line
if (isset($order->products[$i]['attributes']) && sizeof($order->products[$i]['attributes']) > 0 ) {
echo '<ul class="cartAttribsList">';
for ($j=0, $n2=sizeof($order->products[$i]['attributes']); $j<$n2; $j++) {
?>
<li><?php echo $order->products[$i]['attributes'][$j]['option'] . ': ' . nl2br(zen_output_string_protected($order->products[$i]['attributes'][$j]['value'])); ?></li>
<?php
} // end loop
echo '</ul>';
} // endif attribute-info
$wapConfig = in_array($order->products[$i]["id"], [WAP_CONFIG_SERVICE,WAP_CLOUD_MANAGEMENT]);
?>
</td>
<td class="cartQuantity showBorder"><?php echo $order->products[$i]['qty']; ?></td>
<td class="cartProductDisplay showBorder"><?php echo $currencies->display_price($order->products[$i]['final_price'], $order->products[$i]['tax'], 1); ?>
<td class="cartTotalDisplay showBorder">
<?php
// show the payment plan
if( $order->products[$i]['payment_plan'] ) {
$tokens = explode("[[[", $order->products[$i]['payment_plan']);
echo (($order->products[$i]["id"] == WAP_INSTALL) ? ("Base Price: " . $currencies->display_price(WAP_INSTALL_BASE_PRICE, 0, 1) . "<br>") : "") . $tokens[0];
$total = $order->products[$i]['final_price'] * $order->products[$i]['qty'] + (($order->products[$i]["id"] == WAP_INSTALL) ? WAP_INSTALL_BASE_PRICE : 0);
$eratable = $order->products[$i]['erate_eligible'] * $order->products[$i]['qty'] + (($order->products[$i]["id"] == WAP_INSTALL) ? WAP_INSTALL_BASE_PRICE : 0);
for( $j=1; $j<count($tokens); $j++ ) {
$tokenSplit = explode("]]]", $tokens[$j]);
if( is_numeric($tokenSplit[0]) ) {
echo $currencies->display_price($order->products[$i]['final_price'] * $tokenSplit[0], $order->products[$i]['tax'], $order->products[$i]['qty']) . ((count($tokenSplit) > 1)? $tokenSplit[1] : "");
} else if( $tokenSplit[0] == "p" ) {
echo $currencies->display_price($total, 0, 1) . ((count($tokenSplit) > 1) ? $tokenSplit[1] : "");
} else if( $tokenSplit[0] == "el" ) {
echo $currencies->display_price($eratable, 0, 1) . ((count($tokenSplit) > 1) ? $tokenSplit[1] : "");
} else if( $tokenSplit[0] == "er" ) {
$thisVal = $eratable * $_SESSION["selected_erate_discount"];
echo $currencies->display_price($thisVal, 0, 1) . ((count($tokenSplit) > 1) ? $tokenSplit[1] : "");
} else if( $tokenSplit[0] == "ap" ) {
$thisVal = $total - $eratable * $_SESSION["selected_erate_discount"];
echo $currencies->display_price($thisVal, 0, 1) . ((count($tokenSplit) > 1) ? $tokenSplit[1] : "");
} else if( $tokenSplit[0] == "r" ) {
echo (100 * $_SESSION["selected_erate_discount"]) . "%" . ((count($tokenSplit) > 1) ? $tokenSplit[1] : "");
} else {
echo $tokenSplit[0] . ((count($tokenSplit) > 1) ? $tokenSplit[1] : "");
}
}
if( $wapConfig ) {
$thisVal = ($order->products[$i]['final_price'] - ($order->products[$i]['erate_eligible'] * $_SESSION["selected_erate_discount"])) * $order->products[$i]['qty'];
echo "<br>eiNetwork pays: " . $currencies->display_price($thisVal, 0, 1) . "<br>Due up front by library: " . $currencies->display_price(0, 0, 1);
}
// show the single payment
} else {
echo $currencies->display_price($order->products[$i]['final_price'], $order->products[$i]['tax'], $order->products[$i]['qty']);
if ($order->products[$i]['onetime_charges'] != 0 )
echo '<br /> ' . $currencies->display_price($order->products[$i]['onetime_charges'], $order->products[$i]['tax'], 1);
}
?>
</td>
</tr>
<?php } // end for loopthru all products ?>
</table>
<hr />
<?php
if (MODULE_ORDER_TOTAL_INSTALLED) {
$order_totals = $order_total_modules->process();
?>
<div id="orderTotals"><?php $order_total_modules->output(); ?></div>
<?php
}
?>
<?php
echo zen_draw_form('checkout_confirmation', $form_action_url . "&products_type=" . $_REQUEST["products_type"], 'post', 'id="checkout_confirmation" onsubmit="submitonce();"');
if (is_array($payment_modules->modules)) {
echo $payment_modules->process_button();
}
?>
<div class="buttonRow forward"><?php echo zen_image_submit(BUTTON_IMAGE_CONFIRM_ORDER, BUTTON_CONFIRM_ORDER_ALT, 'name="btn_submit" id="btn_submit"') ;?></div>
</form>
<div class="buttonRow back"><?php echo TITLE_CONTINUE_CHECKOUT_PROCEDURE . '<br />' . TEXT_CONTINUE_CHECKOUT_PROCEDURE; ?></div>
</div>
| eiNetwork/zenCart | includes/templates/theme659/templates/tpl_checkout_confirmation_default.php | PHP | gpl-2.0 | 10,701 |
/*
* *************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
* *************************************************************************************
*/
package com.espertech.esper.regression.epl;
import com.espertech.esper.client.Configuration;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPServiceProviderManager;
import com.espertech.esper.client.EPStatement;
import com.espertech.esper.client.annotation.Hint;
import com.espertech.esper.client.scopetest.EPAssertionUtil;
import com.espertech.esper.client.scopetest.SupportUpdateListener;
import com.espertech.esper.support.bean.SupportBean;
import com.espertech.esper.support.bean.SupportBean_S0;
import com.espertech.esper.support.bean.SupportSimpleBeanOne;
import com.espertech.esper.support.bean.SupportSimpleBeanTwo;
import com.espertech.esper.support.client.SupportConfigFactory;
import com.espertech.esper.support.epl.SupportQueryPlanIndexHook;
import com.espertech.esper.support.util.IndexAssertionEventSend;
import com.espertech.esper.support.util.IndexBackingTableInfo;
import junit.framework.TestCase;
public class TestSubselectIndex extends TestCase implements IndexBackingTableInfo
{
private EPServiceProvider epService;
private SupportUpdateListener listener;
public void setUp()
{
Configuration config = SupportConfigFactory.getConfiguration();
config.getEngineDefaults().getLogging().setEnableQueryPlan(true);
epService = EPServiceProviderManager.getDefaultProvider(config);
epService.initialize();
listener = new SupportUpdateListener();
}
protected void tearDown() throws Exception {
listener = null;
}
public void testIndexChoicesOverdefinedWhere() {
epService.getEPAdministrator().getConfiguration().addEventType("SSB1", SupportSimpleBeanOne.class);
epService.getEPAdministrator().getConfiguration().addEventType("SSB2", SupportSimpleBeanTwo.class);
// test no where clause with unique
IndexAssertionEventSend assertNoWhere = new IndexAssertionEventSend() {
public void run() {
String[] fields = "c0,c1".split(",");
epService.getEPRuntime().sendEvent(new SupportSimpleBeanTwo("E1", 1, 2, 3));
epService.getEPRuntime().sendEvent(new SupportSimpleBeanOne("EX", 10, 11, 12));
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[]{"EX", "E1"});
epService.getEPRuntime().sendEvent(new SupportSimpleBeanTwo("E2", 1, 2, 3));
epService.getEPRuntime().sendEvent(new SupportSimpleBeanOne("EY", 10, 11, 12));
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[]{"EY", null});
}
};
runAssertion(false, "s2,i2", "", BACKING_UNINDEXED, assertNoWhere);
// test no where clause with unique on multiple props, exact specification of where-clause
IndexAssertionEventSend assertSendEvents = new IndexAssertionEventSend() {
public void run() {
String[] fields = "c0,c1".split(",");
epService.getEPRuntime().sendEvent(new SupportSimpleBeanTwo("E1", 1, 3, 10));
epService.getEPRuntime().sendEvent(new SupportSimpleBeanTwo("E2", 1, 2, 0));
epService.getEPRuntime().sendEvent(new SupportSimpleBeanTwo("E3", 1, 3, 9));
epService.getEPRuntime().sendEvent(new SupportSimpleBeanOne("EX", 1, 3, 9));
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[]{"EX", "E3"});
}
};
runAssertion(false, "d2,i2", "where ssb2.i2 = ssb1.i1 and ssb2.d2 = ssb1.d1", BACKING_MULTI_UNIQUE, assertSendEvents);
runAssertion(false, "d2,i2", "where ssb2.d2 = ssb1.d1 and ssb2.i2 = ssb1.i1", BACKING_MULTI_UNIQUE, assertSendEvents);
runAssertion(false, "d2,i2", "where ssb2.l2 = ssb1.l1 and ssb2.d2 = ssb1.d1 and ssb2.i2 = ssb1.i1", BACKING_MULTI_UNIQUE, assertSendEvents);
runAssertion(false, "d2,i2", "where ssb2.l2 = ssb1.l1 and ssb2.i2 = ssb1.i1", BACKING_MULTI_DUPS, assertSendEvents);
runAssertion(false, "d2,i2", "where ssb2.d2 = ssb1.d1", BACKING_SINGLE_DUPS, assertSendEvents);
runAssertion(false, "d2,i2", "where ssb2.i2 = ssb1.i1 and ssb2.d2 = ssb1.d1 and ssb2.l2 between 1 and 1000", BACKING_MULTI_UNIQUE, assertSendEvents);
runAssertion(false, "d2,i2", "where ssb2.d2 = ssb1.d1 and ssb2.l2 between 1 and 1000", BACKING_COMPOSITE, assertSendEvents);
runAssertion(false, "i2,d2,l2", "where ssb2.l2 = ssb1.l1 and ssb2.d2 = ssb1.d1", BACKING_MULTI_DUPS, assertSendEvents);
runAssertion(false, "i2,d2,l2", "where ssb2.l2 = ssb1.l1 and ssb2.i2 = ssb1.i1 and ssb2.d2 = ssb1.d1", BACKING_MULTI_UNIQUE, assertSendEvents);
runAssertion(false, "d2,l2,i2", "where ssb2.l2 = ssb1.l1 and ssb2.i2 = ssb1.i1 and ssb2.d2 = ssb1.d1", BACKING_MULTI_UNIQUE, assertSendEvents);
runAssertion(false, "d2,l2,i2", "where ssb2.l2 = ssb1.l1 and ssb2.i2 = ssb1.i1 and ssb2.d2 = ssb1.d1 and ssb2.s2 between 'E3' and 'E4'", BACKING_MULTI_UNIQUE, assertSendEvents);
runAssertion(false, "l2", "where ssb2.l2 = ssb1.l1", BACKING_SINGLE_UNIQUE, assertSendEvents);
runAssertion(true, "l2", "where ssb2.l2 = ssb1.l1", BACKING_SINGLE_DUPS, assertSendEvents);
runAssertion(false, "l2", "where ssb2.l2 = ssb1.l1 and ssb1.i1 between 1 and 20", BACKING_SINGLE_UNIQUE, assertSendEvents);
}
private void runAssertion(boolean disableImplicitUniqueIdx, String uniqueFields, String whereClause, String backingTable, IndexAssertionEventSend assertion) {
String eplUnique = INDEX_CALLBACK_HOOK + "select s1 as c0, " +
"(select s2 from SSB2.std:unique(" + uniqueFields + ") as ssb2 " + whereClause + ") as c1 " +
"from SSB1 as ssb1";
if (disableImplicitUniqueIdx) {
eplUnique = "@Hint('DISABLE_UNIQUE_IMPLICIT_IDX')" + eplUnique;
}
EPStatement stmtUnique = epService.getEPAdministrator().createEPL(eplUnique);
stmtUnique.addListener(listener);
SupportQueryPlanIndexHook.assertSubqueryAndReset(0, null, backingTable);
assertion.run();
stmtUnique.destroy();
}
public void testUniqueIndexCorrelated() {
epService.getEPAdministrator().getConfiguration().addEventType("SupportBean", SupportBean.class);
epService.getEPAdministrator().getConfiguration().addEventType("S0", SupportBean_S0.class);
String[] fields = "c0,c1".split(",");
// test std:unique
String eplUnique = INDEX_CALLBACK_HOOK + "select id as c0, " +
"(select intPrimitive from SupportBean.std:unique(theString) where theString = s0.p00) as c1 " +
"from S0 as s0";
EPStatement stmtUnique = epService.getEPAdministrator().createEPL(eplUnique);
stmtUnique.addListener(listener);
SupportQueryPlanIndexHook.assertSubqueryAndReset(0, null, BACKING_SINGLE_UNIQUE);
epService.getEPRuntime().sendEvent(new SupportBean("E1", 1));
epService.getEPRuntime().sendEvent(new SupportBean("E2", 2));
epService.getEPRuntime().sendEvent(new SupportBean("E1", 3));
epService.getEPRuntime().sendEvent(new SupportBean("E2", 4));
epService.getEPRuntime().sendEvent(new SupportBean_S0(10, "E2"));
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[] {10, 4});
epService.getEPRuntime().sendEvent(new SupportBean_S0(11, "E1"));
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[]{11, 3});
stmtUnique.destroy();
// test std:firstunique
String eplFirstUnique = INDEX_CALLBACK_HOOK + "select id as c0, " +
"(select intPrimitive from SupportBean.std:firstunique(theString) where theString = s0.p00) as c1 " +
"from S0 as s0";
EPStatement stmtFirstUnique = epService.getEPAdministrator().createEPL(eplFirstUnique);
stmtFirstUnique.addListener(listener);
SupportQueryPlanIndexHook.assertSubqueryAndReset(0, null, BACKING_SINGLE_UNIQUE);
epService.getEPRuntime().sendEvent(new SupportBean("E1", 1));
epService.getEPRuntime().sendEvent(new SupportBean("E2", 2));
epService.getEPRuntime().sendEvent(new SupportBean("E1", 3));
epService.getEPRuntime().sendEvent(new SupportBean("E2", 4));
epService.getEPRuntime().sendEvent(new SupportBean_S0(10, "E2"));
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[] {10, 2});
epService.getEPRuntime().sendEvent(new SupportBean_S0(11, "E1"));
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[]{11, 1});
stmtFirstUnique.destroy();
// test intersection std:firstunique
String eplIntersection = INDEX_CALLBACK_HOOK + "select id as c0, " +
"(select intPrimitive from SupportBean.win:time(1).std:unique(theString) where theString = s0.p00) as c1 " +
"from S0 as s0";
EPStatement stmtIntersection = epService.getEPAdministrator().createEPL(eplIntersection);
stmtIntersection.addListener(listener);
SupportQueryPlanIndexHook.assertSubqueryAndReset(0, null, BACKING_SINGLE_UNIQUE);
epService.getEPRuntime().sendEvent(new SupportBean("E1", 1));
epService.getEPRuntime().sendEvent(new SupportBean("E1", 2));
epService.getEPRuntime().sendEvent(new SupportBean("E1", 3));
epService.getEPRuntime().sendEvent(new SupportBean("E2", 4));
epService.getEPRuntime().sendEvent(new SupportBean_S0(10, "E2"));
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[] {10, 4});
epService.getEPRuntime().sendEvent(new SupportBean_S0(11, "E1"));
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[]{11, 3});
stmtIntersection.destroy();
// test grouped unique
String eplGrouped = INDEX_CALLBACK_HOOK + "select id as c0, " +
"(select longPrimitive from SupportBean.std:groupwin(theString).std:unique(intPrimitive) where theString = s0.p00 and intPrimitive = s0.id) as c1 " +
"from S0 as s0";
EPStatement stmtGrouped = epService.getEPAdministrator().createEPL(eplGrouped);
stmtGrouped.addListener(listener);
SupportQueryPlanIndexHook.assertSubqueryAndReset(0, null, BACKING_MULTI_UNIQUE);
epService.getEPRuntime().sendEvent(makeBean("E1", 1, 100));
epService.getEPRuntime().sendEvent(makeBean("E1", 2, 101));
epService.getEPRuntime().sendEvent(makeBean("E1", 1, 102));
epService.getEPRuntime().sendEvent(new SupportBean_S0(1, "E1"));
EPAssertionUtil.assertProps(listener.assertOneGetNewAndReset(), fields, new Object[] {1, 102L});
stmtGrouped.destroy();
}
private SupportBean makeBean(String theString, int intPrimitive, long longPrimitive) {
SupportBean bean = new SupportBean(theString, intPrimitive);
bean.setLongPrimitive(longPrimitive);
return bean;
}
}
| sungsoo/esper | esper/src/test/java/com/espertech/esper/regression/epl/TestSubselectIndex.java | Java | gpl-2.0 | 12,082 |
<?php
if (!defined('WEB_ROOT')) {
exit;
}
$changeMessage = (isset($_GET['info']) && $_GET['info'] != '') ? $_GET['info'] : ' ';
$sql = "Select ctype, pid, pdate, pdesc
From tbl_categories c, tbl_history h
Where h.cid=c.cid order by pdate desc";
$result = dbQuery($sql);
$total = mysqli_num_rows($result);
if(!isset($_GET["page"])) //ÊÇ·ñ»ñµÃGET²ÎÊý
{
$thispage = 1; //δ»ñµÃ¼´ÎªµÚ1Ò³
}
else
{
$thispage = $_GET["page"];
}
$perpage = 15; //ÿҳÏÔʾ¼Ç¼Êý
$limit = $perpage*($thispage-1); //±¾Ò³¼Ç¼ÊýÆðʼλÖÃ
?>
<div class="prepend-1 span-17">
<table>
<tr>
<td>
<strong>Products You Have Purchased Before</strong>
<br>
The historical list of grocery products you have already purchased before
</td>
<td>
<p><img src="<?php echo WEB_ROOT; ?>images/order-icon.png" class="right"/>
</td>
</tr>
</table>
<?php
$sql = "Select hid, ctype, pid, pdate, pdesc
From tbl_categories c, tbl_history h
Where h.cid=c.cid order by pdate desc limit ".$limit.",".$perpage;
$result = dbQuery($sql);
?>
<table border="0" align="center" cellpadding="2" cellspacing="1" class="text">
<tr align="center" id="listTableHeader">
<td>Category</td>
<td>Product</td>
<td>Purchase Time</td>
</tr>
<?php
while($row = dbFetchAssoc($result)) {
extract($row);
if ($i%2) {
$class = 'row1';
} else {
$class = 'row2';
}
$i += 1;
?>
<tr class="<?php echo $class; ?>">
<td><?php echo $ctype; ?></td>
<td align="center"><?php echo $pdesc; ?></td>
<td align="center"><?php echo $pdate; ?></td>
</tr>
<?php
} // end of while
?>
<tr>
<td colspan="3"> </td>
</tr>
</table>
<tr><td colspan = "3"><?php page($total, $perpage, $thispage,"?v=HISTORYORDER&page=");?></td></tr>
<br>
<tr><td colspan="1" align="right"><input name="btnSendOrder" type="button" id="btnSendOrder" value="Back" class="button" onClick="BacktoList()"></td></tr>
<FONT COLOR="blue"><?php echo $changeMessage?></FONT><br>
<p> </p>
</div>
| HongbiaoYang/SmartKitchen | shoplist/history.php | PHP | gpl-2.0 | 2,085 |
# ------------------------------------------------------------------------------------------------
# Software: Stem Applier (staply)
# Description: Applies inflections to stem morphemes
# Version: 0.0.1a
# Module: Main
#
# Author: Frederic Bayer
# Email: f.bayer@computer.org
# Institution: University of Aberdeen
#
# Copyright: (c) Frederic S. Bayer 2015
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-13SA.
# -----------------------------------------------------------------------------------------------
__author__ = 'Frederic Bayer' | fsbayer/staply | staply/__init__.py | Python | gpl-2.0 | 1,227 |
from socket import *
import sys
clientSocket = socket(AF_INET, SOCK_STREAM) #creates socket
server_address = ('127.0.0.1', 80)#create connection at this given port
print >>sys.stderr, 'CONNECTING TO %s AT PORT %s' % server_address
clientSocket.connect(server_address)#connect to server at given address
filename=raw_input("ENTER THE FILENAME: ")
f = open(filename[0:])
outputdata = f.read()#read the input file into variable
print "HTML CODE OF THE GIVEN FILE:", outputdata #display the html code of the file
clientSocket.close() #close the connection
| HarmeetDhillon/Socket-Programming | Client.py | Python | gpl-2.0 | 561 |
/**************************************
*Script Name: Message of the Day *
*Author: Joeku *
*For use with RunUO 2.0 *
*Client Tested with: 6.0.2.0 *
*Version: 1.0 *
*Initial Release: 12/04/07 *
*Revision Date: 12/04/07 *
**************************************/
using System;
using Server;
using Server.Gumps;
using Server.Network;
namespace Joeku.MOTD
{
public class MOTD_Gump : Gump
{
public Mobile User;
public bool Help;
public int Index;
public MOTD_Gump( Mobile user, bool help, int index ) : base( 337, 150 )
{
this.User = user;
this.Help = help;
this.Index = index;
AddPage(0);
AddBackground(0, 0, 350, 272, 9270); // Background - Main
AddBackground(10, 35, 330, 227, 9270); // Background - Main - Category
AddTitle();
AddImageTiled(30, 81, 290, 162, 2624); // AlphaBG - Main - Category - Body
AddAlphaRegion(30, 81, 290, 162); // AlphaAA - Main - Category - Body
AddBody();
}
public void AddTitle()
{
if( !this.Help )
AddButton(298, 15, 22153, 22155, 1, GumpButtonType.Reply, 0); // Button - Main - Help
AddButton(319, 15, 22150, 22152, 0, GumpButtonType.Reply, 0); // Button - Main - Close
AddBackground(81, 10, 188, 35, 9270); // Background - Main - Title
AddLabel(!this.Help ? 91 : 92, 17, 2101, String.Format("Message of the Day - {0}", !this.Help ? "Main" : "Help")); // Text - Main - Title
AddBackground(91, 45, 168, 35, 9270); // Background - Main - Category - Title
int width = !this.Help ? MOTD_Main.Info[this.Index].NameWidth : MOTD_Main.HelpInfo[this.Index].NameWidth, offset = 0;
if( width >= 148 )
width = 148;
else
offset = (148-width)/2;
AddLabelCropped(101+offset, 52, width, 16, 2101, !this.Help ? MOTD_Main.Info[this.Index].Name : MOTD_Main.HelpInfo[this.Index].Name); // Text - Main - Category - Title
}
public void AddBody()
{
if( !this.Help )
{
if( MOTD_Main.Info.Length > 1 )
{
int pageBack = this.Index-1, pageForward = this.Index+1;
if( pageBack < 0 )
pageBack = MOTD_Main.Info.Length-1;
if( pageForward == MOTD_Main.Info.Length )
pageForward = 0;
AddButton(30, 55, 5603, 5607, pageBack+10, GumpButtonType.Reply, 0); // Button - Main - Category - Page Back
AddButton(304, 55, 5601, 5605, pageForward+10, GumpButtonType.Reply, 0); // Button - Main - Category - Page Forward
}
AddHtml(30, 81, 290, 162, MOTD_Main.Info[this.Index].Body, false, true); // Text - Main - Category - Body
/*int w = 0;
for( int i = 0; i < MOTD_Main.Length; i++ )
{
w = ((108-MOTD_Main.Info[i].NameWidth)/2);
if( w < 5 )
w = 5;
AddPage( i+1 );
AddLabelCropped(196 + w, 121, 98, 16, 2212, MOTD_Main.Info[i].Name);
AddHtml(95, 160, 315, 162, MOTD_Main.Info[i].Body, false, true);
// 4014/4016 - page back
// 4005/4007 - page forward
if( MOTD_Main.Length > 1 )
{
int pageBack = i-1, pageForward = i+1;
if( pageBack < 0 && MOTD_Main.Length > 2 )
pageBack = MOTD_Main.Length-1;
if( pageForward == MOTD_Main.Length && MOTD_Main.Length > 2 )
pageForward = 0;
if( pageForward >= 0 && pageForward < MOTD_Main.Length )
{
AddButton(309, 120, 4005, 4007, 0, GumpButtonType.Page, pageForward+1 );
AddLabelCropped(344, 121, 85, 16, 0, MOTD_Main.Info[pageForward].Name );
}
if( pageBack >= 0 && pageBack < MOTD_Main.Length )
{
w = MOTD_Main.Info[pageBack].NameWidth;
if( w > 85 )
w = 85;
AddLabelCropped(156 - w, 121, 85, 16, 0, MOTD_Main.Info[pageBack].Name );
AddButton(161, 120, 4014, 4016, 0, GumpButtonType.Page, pageBack+1 );
}
}
}*/
}
else
{
if( MOTD_Main.HelpInfo.Length > 1 )
{
int pageBack = this.Index-1, pageForward = this.Index+1;
if( pageBack < 0 )
pageBack = MOTD_Main.HelpInfo.Length-1;
if( pageForward == MOTD_Main.HelpInfo.Length )
pageForward = 0;
AddButton(30, 55, 5603, 5607, pageBack+10, GumpButtonType.Reply, 0); // Button - Main - Category - Page Back
AddButton(304, 55, 5601, 5605, pageForward+10, GumpButtonType.Reply, 0); // Button - Main - Category - Page Forward
}
switch( this.Index )
{
case 0:
AddHtml(30, 81, 290, 162, String.Format( "<CENTER><U>Message of the Day v{0}</U><BR>Author: Joeku<BR>{1}</CENTER><BR> The MOTD is designed to keep players up to date on shard news. If you do not want to see the MOTD every time you log into the shard, you can change your preferences on the next page.", ((double)MOTD_Main.Version) / 100, MOTD_Main.ReleaseDate ) , false, true); // Text - Main - Category - Body
break;
case 1:
bool login = MOTD_Utility.CheckLogin( this.User.Account );
AddButton(91, 91, login ? 9723 : 9720, login ? 9724 : 9721, 1, GumpButtonType.Reply, 0); // Button - Main - Category - ToggleLogin
AddLabel(125, 96, 2100, @"Show MOTD upon login"); // Label 4
break;
}
}
}
public override void OnResponse( NetState sender, RelayInfo info )
{
Mobile mob = sender.Mobile;
int button = info.ButtonID;
switch( button )
{
case 0: // Close
if( this.Help )
MOTD_Utility.SendGump( mob );
break;
case 1: // Help
if( !this.Help )
MOTD_Utility.SendGump( mob, true );
else
{
MOTD_Utility.ToggleLogin( this.User.Account );
MOTD_Utility.SendGump( mob, true, this.Index );
}
break;
default: // Page Forward/Back
MOTD_Utility.SendGump( mob, this.Help, button-10 );
break;
}
}
}
}
| tbewley10310/Land-of-Archon | Scripts.LV2/Systems/MOTD/Gump.cs | C# | gpl-2.0 | 5,697 |
/************************************************************************
COPYRIGHT (C) SGS-THOMSON Microelectronics 2007
Source file name : codec_mme_audio_spdifin.cpp
Author : Gael Lassure
Implementation of the spdif-input audio codec class for player 2.
Date Modification Name
---- ------------ --------
24-July-07 Created (from codec_mme_audio_eac3.cpp) Gael Lassure
************************************************************************/
////////////////////////////////////////////////////////////////////////////
/// \class Codec_MmeAudioSpdifIn_c
///
/// The SpdifIn audio codec proxy.
///
// /////////////////////////////////////////////////////////////////////
//
// Include any component headers
#define CODEC_TAG "SPDIFIN audio codec"
#include "codec_mme_audio_spdifin.h"
#include "codec_mme_audio_eac3.h"
#include "codec_mme_audio_dtshd.h"
#include "lpcm.h"
#include "spdifin_audio.h"
// /////////////////////////////////////////////////////////////////////////
//
// Locally defined constants
//
// /////////////////////////////////////////////////////////////////////////
//
// Locally defined structures
//
typedef struct SpdifinAudioCodecStreamParameterContext_s
{
CodecBaseStreamParameterContext_t BaseContext;
MME_LxAudioDecoderGlobalParams_t StreamParameters;
} SpdifinAudioCodecStreamParameterContext_t;
//#if __KERNEL__
#if 0
#define BUFFER_SPDIFIN_AUDIO_CODEC_STREAM_PARAMETER_CONTEXT "SpdifinAudioCodecStreamParameterContext"
#define BUFFER_SPDIFIN_AUDIO_CODEC_STREAM_PARAMETER_CONTEXT_TYPE {BUFFER_SPDIFIN_AUDIO_CODEC_STREAM_PARAMETER_CONTEXT, BufferDataTypeBase, AllocateFromDeviceMemory, 32, 0, true, true, sizeof(SpdifinAudioCodecStreamParameterContext_t)}
#else
#define BUFFER_SPDIFIN_AUDIO_CODEC_STREAM_PARAMETER_CONTEXT "SpdifinAudioCodecStreamParameterContext"
#define BUFFER_SPDIFIN_AUDIO_CODEC_STREAM_PARAMETER_CONTEXT_TYPE {BUFFER_SPDIFIN_AUDIO_CODEC_STREAM_PARAMETER_CONTEXT, BufferDataTypeBase, AllocateFromOSMemory, 32, 0, true, true, sizeof(SpdifinAudioCodecStreamParameterContext_t)}
#endif
static BufferDataDescriptor_t SpdifinAudioCodecStreamParameterContextDescriptor = BUFFER_SPDIFIN_AUDIO_CODEC_STREAM_PARAMETER_CONTEXT_TYPE;
// --------
typedef struct SpdifinAudioCodecDecodeContext_s
{
CodecBaseDecodeContext_t BaseContext;
MME_LxAudioDecoderFrameParams_t DecodeParameters;
MME_LxAudioDecoderFrameStatus_t DecodeStatus;
// Input Buffer is sent in a separate Command
MME_Command_t BufferCommand;
MME_SpdifinBufferParams_t BufferParameters;
MME_LxAudioDecoderFrameStatus_t BufferStatus;
} SpdifinAudioCodecDecodeContext_t;
//#if __KERNEL__
#if 0
#define BUFFER_SPDIFIN_AUDIO_CODEC_DECODE_CONTEXT "SpdifinAudioCodecDecodeContext"
#define BUFFER_SPDIFIN_AUDIO_CODEC_DECODE_CONTEXT_TYPE {BUFFER_SPDIFIN_AUDIO_CODEC_DECODE_CONTEXT, BufferDataTypeBase, AllocateFromDeviceMemory, 32, 0, true, true, sizeof(SpdifinAudioCodecDecodeContext_t)}
#else
#define BUFFER_SPDIFIN_AUDIO_CODEC_DECODE_CONTEXT "SpdifinAudioCodecDecodeContext"
#define BUFFER_SPDIFIN_AUDIO_CODEC_DECODE_CONTEXT_TYPE {BUFFER_SPDIFIN_AUDIO_CODEC_DECODE_CONTEXT, BufferDataTypeBase, AllocateFromOSMemory, 32, 0, true, true, sizeof(SpdifinAudioCodecDecodeContext_t)}
#endif
static BufferDataDescriptor_t SpdifinAudioCodecDecodeContextDescriptor = BUFFER_SPDIFIN_AUDIO_CODEC_DECODE_CONTEXT_TYPE;
// --------
////////////////////////////////////////////////////////////////////////////
///
/// Fill in the configuration parameters used by the super-class and reset everything.
///
/// \todo Correctly setup AudioDecoderTransformCapabilityMask
///
Codec_MmeAudioSpdifin_c::Codec_MmeAudioSpdifin_c( void )
{
Configuration.CodecName = "SPDIFIN audio";
// for SPDIFin we know that the incoming data is never longer than 1024 samples giving us a fairly
// small maximum frame size (reducing the maximum frame size allows us to make more efficient use of
/// the coded frame buffer)
Configuration.MaximumCodedFrameSize = 0x8000;
// Large because if it changes each frame we won't be freed until the decodes have rippled through (causing deadlock)
Configuration.StreamParameterContextCount = 10;
Configuration.StreamParameterContextDescriptor = &SpdifinAudioCodecStreamParameterContextDescriptor;
// Send up to 10 frames for look-ahead.
Configuration.DecodeContextCount = 10;
Configuration.DecodeContextDescriptor = &SpdifinAudioCodecDecodeContextDescriptor;
DecodeErrors = 0;
NumberOfSamplesProcessed = 0;
//AudioDecoderTransformCapabilityMask.DecoderCapabilityFlags = (1 << ACC_SPDIFIN);
DecoderId = ACC_SPDIFIN_ID;
memset(&EOF, 0x00, sizeof(Codec_SpdifinEOF_t));
EOF.Command.CmdStatus.State = MME_COMMAND_FAILED; // always park the command in a not-running state
SpdifStatus.State = SPDIFIN_STATE_PCM_BYPASS;
SpdifStatus.StreamType = SPDIFIN_RESERVED;
SpdifStatus.PlayedSamples = 0;
Reset();
}
////////////////////////////////////////////////////////////////////////////
///
/// Destructor function, ensures a full halt and reset
/// are executed for all levels of the class.
///
Codec_MmeAudioSpdifin_c::~Codec_MmeAudioSpdifin_c( void )
{
Halt();
Reset();
}
CodecStatus_t Codec_MmeAudioSpdifin_c::Reset( void )
{
EOF.SentEOFCommand = false;
return Codec_MmeAudio_c::Reset();
}
const static enum eAccFsCode LpcmSpdifin2ACC[] =
{
// DVD Video Supported Frequencies
ACC_FS48k,
ACC_FS96k,
ACC_FS192k,
ACC_FS_reserved,
ACC_FS32k,
ACC_FS16k,
ACC_FS22k,
ACC_FS24k,
// DVD Audio Supported Frequencies
ACC_FS44k,
ACC_FS88k,
ACC_FS176k,
ACC_FS_reserved,
ACC_FS_reserved,
ACC_FS_reserved,
ACC_FS_reserved,
ACC_FS_reserved,
// SPDIFIN Supported frequencies
ACC_FS_reserved,
ACC_FS_reserved,
ACC_FS_reserved,
ACC_FS_reserved,
ACC_FS_reserved,
ACC_FS_reserved,
ACC_FS_reserved,
ACC_FS_reserved,
ACC_FS_reserved,
ACC_FS_reserved,
};
static const LpcmAudioStreamParameters_t DefaultStreamParameters =
{
TypeLpcmSPDIFIN,
ACC_MME_FALSE, // MuteFlag
ACC_MME_FALSE, // EmphasisFlag
LpcmWordSize32,
LpcmWordSizeNone,
LpcmSamplingFreq48,
LpcmSamplingFreqNone,
2, // NbChannels
0,
LPCM_DEFAULT_CHANNEL_ASSIGNMENT, // derived from NbChannels.
/*
0,
0,
0,
0,
0,
0,
0,
0
*/
};
////////////////////////////////////////////////////////////////////////////
///
/// Populate the supplied structure with parameters for SPDIFIN audio.
///
CodecStatus_t Codec_MmeAudioSpdifin_c::FillOutTransformerGlobalParameters( MME_LxAudioDecoderGlobalParams_t *GlobalParams_p )
{
CodecStatus_t Status;
//
LpcmAudioStreamParameters_t *Parsed;
MME_LxAudioDecoderGlobalParams_t &GlobalParams = *GlobalParams_p;
GlobalParams.StructSize = sizeof(MME_LxAudioDecoderGlobalParams_t);
//
if (ParsedFrameParameters == NULL)
{
// At transformer init, stream properties might be unknown...
Parsed = (LpcmAudioStreamParameters_t*) &DefaultStreamParameters;
}
else
{
Parsed = (LpcmAudioStreamParameters_t *)ParsedFrameParameters->StreamParameterStructure;
}
MME_SpdifinConfig_t &Config = *((MME_SpdifinConfig_t *) GlobalParams.DecConfig);
Config.DecoderId = ACC_SPDIFIN_ID;
Config.StructSize = sizeof(MME_SpdifinConfig_t);
// Setup default IEC config
Config.Config[IEC_SFREQ] = LpcmSpdifin2ACC[Parsed->SamplingFrequency1]; // should be 48 by default.
Config.Config[IEC_NBSAMPLES] = Parsed->NumberOfSamples; // should be 1024
Config.Config[IEC_DEEMPH ] = Parsed->EmphasisFlag;
// Setup default DD+ decoder config
memset(&Config.DecConfig[0], 0, sizeof(Config.DecConfig));
Config.DecConfig[DD_CRC_ENABLE] = ACC_MME_TRUE;
Config.DecConfig[DD_LFE_ENABLE] = ACC_MME_TRUE;
Config.DecConfig[DD_COMPRESS_MODE] = DD_LINE_OUT;
Config.DecConfig[DD_HDR] = 0xFF;
Config.DecConfig[DD_LDR] = 0xFF;
//
Status = Codec_MmeAudio_c::FillOutTransformerGlobalParameters( GlobalParams_p );
if( Status != CodecNoError )
{
return Status;
}
//
unsigned char *PcmParams_p = ((unsigned char *) &Config) + Config.StructSize;
MME_LxPcmProcessingGlobalParams_Subset_t &PcmParams =
*((MME_LxPcmProcessingGlobalParams_Subset_t *) PcmParams_p);
MME_Resamplex2GlobalParams_t &resamplex2 = PcmParams.Resamplex2;
// Id already set
// StructSize already set
resamplex2.Apply = ACC_MME_AUTO;
resamplex2.Range = ACC_FSRANGE_48k;
//
return CodecNoError;
}
////////////////////////////////////////////////////////////////////////////
///
/// Populate the AUDIO_DECODER's initialization parameters for SPDIFIN audio.
///
/// When this method completes Codec_MmeAudio_c::AudioDecoderInitializationParameters
/// will have been filled out with valid values sufficient to initialize an
/// SPDIFIN audio decoder.
///
CodecStatus_t Codec_MmeAudioSpdifin_c::FillOutTransformerInitializationParameters( void )
{
CodecStatus_t Status;
MME_LxAudioDecoderInitParams_t &Params = AudioDecoderInitializationParameters;
//
MMEInitializationParameters.TransformerInitParamsSize = sizeof(Params);
MMEInitializationParameters.TransformerInitParams_p = &Params;
//
Status = Codec_MmeAudio_c::FillOutTransformerInitializationParameters();
if (Status != CodecNoError)
return Status;
// Spdifin decoder must be handled as streambase.
AUDIODEC_SET_STREAMBASE((&Params), ACC_MME_TRUE);
//
return FillOutTransformerGlobalParameters( &Params.GlobalParams );
}
////////////////////////////////////////////////////////////////////////////
///
/// Populate the AUDIO_DECODER's MME_SET_GLOBAL_TRANSFORMER_PARAMS parameters for SPDIFIN audio.
///
CodecStatus_t Codec_MmeAudioSpdifin_c::FillOutSetStreamParametersCommand( void )
{
CodecStatus_t Status;
SpdifinAudioCodecStreamParameterContext_t *Context = (SpdifinAudioCodecStreamParameterContext_t *)StreamParameterContext;
//
// Examine the parsed stream parameters and determine what type of codec to instanciate
//
DecoderId = ACC_SPDIFIN_ID;
//
// Now fill out the actual structure
//
memset( &(Context->StreamParameters), 0, sizeof(Context->StreamParameters) );
Status = FillOutTransformerGlobalParameters( &(Context->StreamParameters) );
if( Status != CodecNoError )
return Status;
//
// Fillout the actual command
//
Context->BaseContext.MMECommand.CmdStatus.AdditionalInfoSize = 0;
Context->BaseContext.MMECommand.CmdStatus.AdditionalInfo_p = NULL;
Context->BaseContext.MMECommand.ParamSize = sizeof(Context->StreamParameters);
Context->BaseContext.MMECommand.Param_p = (MME_GenericParams_t)(&Context->StreamParameters);
//
return CodecNoError;
}
////////////////////////////////////////////////////////////////////////////
///
/// Populate the AUDIO_DECODER's MME_TRANSFORM parameters for SPDIFIN audio.
///
CodecStatus_t Codec_MmeAudioSpdifin_c::FillOutDecodeCommand( void )
{
SpdifinAudioCodecDecodeContext_t *Context = (SpdifinAudioCodecDecodeContext_t *)DecodeContext;
//
// Initialize the frame parameters (we don't actually have much to say here)
//
memset( &Context->DecodeParameters, 0, sizeof(Context->DecodeParameters) );
//
// Zero the reply structure
//
memset( &Context->DecodeStatus, 0, sizeof(Context->DecodeStatus) );
//
// Fillout the actual command
//
Context->BaseContext.MMECommand.CmdStatus.AdditionalInfoSize = sizeof(Context->DecodeStatus);
Context->BaseContext.MMECommand.CmdStatus.AdditionalInfo_p = (MME_GenericParams_t)(&Context->DecodeStatus);
Context->BaseContext.MMECommand.ParamSize = sizeof(Context->DecodeParameters);
Context->BaseContext.MMECommand.Param_p = (MME_GenericParams_t)(&Context->DecodeParameters);
return CodecNoError;
}
#ifdef __KERNEL__
extern "C"{void flush_cache_all();};
#endif
////////////////////////////////////////////////////////////////////////////
///
/// Populate the AUDIO_DECODER's MME_SEND_BUFFERS parameters for SPDIFIN audio.
/// Copy some code of codec_mme_base.cpp
/// Do not expect any Callback upon completion of this SEND_BUFFER as its
/// completion must be synchronous with the TRANSFORM command that contains the
/// corresponding decoded buffer.
CodecStatus_t Codec_MmeAudioSpdifin_c::FillOutSendBufferCommand( void )
{
SpdifinAudioCodecDecodeContext_t *Context = (SpdifinAudioCodecDecodeContext_t *)DecodeContext;
if (EOF.SentEOFCommand)
{
CODEC_TRACE("Already sent EOF command - refusing to queue more buffers\n");
return CodecNoError;
}
//
// Initialize the input buffer parameters (we don't actually have much to say here)
//
memset( &Context->BufferParameters, 0, sizeof(Context->BufferParameters) );
//
// Zero the reply structure
//
memset( &Context->BufferStatus, 0, sizeof(Context->BufferStatus) );
//
// Fillout the actual command
//
Context->BufferCommand.CmdStatus.AdditionalInfoSize = sizeof(Context->BufferStatus);
Context->BufferCommand.CmdStatus.AdditionalInfo_p = (MME_GenericParams_t)(&Context->BufferStatus);
Context->BufferCommand.ParamSize = sizeof(Context->BufferParameters);
Context->BufferCommand.Param_p = (MME_GenericParams_t)(&Context->BufferParameters);
// Feed back will be managed at same time as the return of the corresponding MME_TRANSFORM.
Context->BufferCommand.StructSize = sizeof(MME_Command_t);
Context->BufferCommand.CmdCode = MME_SEND_BUFFERS;
Context->BufferCommand.CmdEnd = MME_COMMAND_END_RETURN_NO_INFO;
#ifdef __KERNEL__
flush_cache_all();
#endif
MME_ERROR Status = MME_SendCommand( MMEHandle, &Context->BufferCommand );
if( Status != MME_SUCCESS )
{
report( severity_error, "Codec_MmeAudioSpdifin_c::FillOutSendBufferCommand(%s) - Unable to send buffer command (%08x).\n", Configuration.CodecName, Status );
return CodecError;
}
return CodecNoError;
}
////////////////////////////////////////////////////////////////////////////
///
/// Set SPDIFIN StreamBase style TRANSFORM command IOs
/// Set DecodeContext the same way as for FrameBase TRANSFORMS
/// but Send the Input buffer in a Specific SEND_BUFFER command.
/// TRANSFORM Command is preset to emit only the corresponding Output buffer
void Codec_MmeAudioSpdifin_c::SetCommandIO(void)
{
SpdifinAudioCodecDecodeContext_t *Context = (SpdifinAudioCodecDecodeContext_t *)DecodeContext;
// Attach both I/O buffers to DecodeContext.
PresetIOBuffers();
// StreamBase Transformer : 1 Input Buffer sent through SEND_BUFFER / 1 Output Buffer sent through MME_TRANSFORM
// Prepare SEND_BUFFER Command to transmit Input Buffer
Context->BufferCommand.NumberInputBuffers = 1;
Context->BufferCommand.NumberOutputBuffers = 0;
Context->BufferCommand.DataBuffers_p = &DecodeContext->MMEBufferList[0];
// Prepare MME_TRANSFORM Command to transmit Output Buffer
DecodeContext->MMECommand.NumberInputBuffers = 0;
DecodeContext->MMECommand.NumberOutputBuffers = 1;
DecodeContext->MMECommand.DataBuffers_p = &DecodeContext->MMEBufferList[1];
//
// Load the parameters into MME SendBuffer command
//
FillOutSendBufferCommand();
}
CodecStatus_t Codec_MmeAudioSpdifin_c::SendEofCommand()
{
MME_Command_t *eof = &EOF.Command;
if (EOF.SentEOFCommand) {
CODEC_TRACE("Already sent EOF command once, refusing to do it again.\n");
return CodecNoError;
}
EOF.SentEOFCommand = true;
// Setup EOF Command ::
eof->StructSize = sizeof(MME_Command_t);
eof->CmdCode = MME_SEND_BUFFERS;
eof->CmdEnd = MME_COMMAND_END_RETURN_NO_INFO;
eof->NumberInputBuffers = 1;
eof->NumberOutputBuffers = 0;
eof->DataBuffers_p = (MME_DataBuffer_t **) &EOF.DataBuffers;
eof->ParamSize = sizeof(MME_SpdifinBufferParams_t);
eof->Param_p = &EOF.Params;
//
// The following fields were reset during the Class Instantiation ::
//
//eof->DueTime = 0;
//eof->CmdStatus.AdditionalInfoSize = 0;
//eof->CmdStatus.AdditionalInfo_p = NULL;
// Setup EOF Params
EOF.Params.StructSize = sizeof(MME_SpdifinBufferParams_t);
STREAMING_SET_BUFFER_TYPE(EOF.Params.BufferParams, STREAMING_DEC_EOF);
// Setup DataBuffer ::
EOF.DataBuffers[0] = &EOF.DataBuffer;
EOF.DataBuffer.StructSize = sizeof(MME_DataBuffer_t);
EOF.DataBuffer.UserData_p = NULL;
EOF.DataBuffer.NumberOfScatterPages = 1;
EOF.DataBuffer.ScatterPages_p = &EOF.ScatterPage;
//
// The following fields were reset during the Class Instantiation ::
//
//eof->DueTime = 0; // immediate.
//EOF.DataBuffer.Flags = 0;
//EOF.DataBuffer.StreamNumber = 0;
//EOF.DataBuffer.TotalSize = 0;
//EOF.DataBuffer.StartOffset = 0;
// Setup EOF ScatterPage ::
//
// The following fields were reset during the Class Instantiation ::
//
//EOF.ScatterPage.Page_p = NULL;
//EOF.ScatterPage.Size = 0;
//EOF.ScatterPage.BytesUsed = 0;
//EOF.ScatterPage.FlagsIn = 0;
//EOF.ScatterPage.FlagsOut = 0;
MME_ERROR Result = MME_SendCommand( MMEHandle, eof);
if( Result != MME_SUCCESS )
{
CODEC_ERROR("Unable to send eof (%08x).\n", Result );
return CodecError;
}
return CodecNoError;
}
CodecStatus_t Codec_MmeAudioSpdifin_c::DiscardQueuedDecodes()
{
CodecStatus_t Status;
Status = Codec_MmeAudio_c::DiscardQueuedDecodes();
if (CodecNoError != Status)
return Status;
Status = SendEofCommand();
if (CodecNoError != Status)
return Status;
return CodecNoError;
}
////////////////////////////////////////////////////////////////////////////
///
/// Status Information display
#define SPDIFIN_TEXT(x) #x
const char * SpdifinStreamTypeText[]=
{
SPDIFIN_TEXT(SPDIFIN_NULL_DATA_BURST),
SPDIFIN_TEXT(SPDIFIN_AC3),
SPDIFIN_TEXT(SPDIFIN_PAUSE_BURST),
SPDIFIN_TEXT(SPDIFIN_MP1L1),
SPDIFIN_TEXT(SPDIFIN_MP1L2L3),
SPDIFIN_TEXT(SPDIFIN_MP2MC),
SPDIFIN_TEXT(SPDIFIN_MP2AAC),
SPDIFIN_TEXT(SPDIFIN_MP2L1LSF),
SPDIFIN_TEXT(SPDIFIN_MP2L2LSF),
SPDIFIN_TEXT(SPDIFIN_MP2L3LSF),
SPDIFIN_TEXT(SPDIFIN_DTS1),
SPDIFIN_TEXT(SPDIFIN_DTS2),
SPDIFIN_TEXT(SPDIFIN_DTS3),
SPDIFIN_TEXT(SPDIFIN_ATRAC),
SPDIFIN_TEXT(SPDIFIN_ATRAC2_3),
SPDIFIN_TEXT(SPDIFIN_IEC60937_RESERVED),
SPDIFIN_TEXT(SPDIFIN_RESERVED_16),
SPDIFIN_TEXT(SPDIFIN_RESERVED_17),
SPDIFIN_TEXT(SPDIFIN_RESERVED_18),
SPDIFIN_TEXT(SPDIFIN_RESERVED_19),
SPDIFIN_TEXT(SPDIFIN_RESERVED_20),
SPDIFIN_TEXT(SPDIFIN_RESERVED_21),
SPDIFIN_TEXT(SPDIFIN_RESERVED_22),
SPDIFIN_TEXT(SPDIFIN_RESERVED_23),
SPDIFIN_TEXT(SPDIFIN_RESERVED_24),
SPDIFIN_TEXT(SPDIFIN_RESERVED_25),
SPDIFIN_TEXT(SPDIFIN_RESERVED_26),
SPDIFIN_TEXT(SPDIFIN_RESERVED_27),
SPDIFIN_TEXT(SPDIFIN_RESERVED_28),
SPDIFIN_TEXT(SPDIFIN_RESERVED_29),
SPDIFIN_TEXT(SPDIFIN_RESERVED_30),
SPDIFIN_TEXT(SPDIFIN_RESERVED_31),
SPDIFIN_TEXT(SPDIFIN_IEC60958_PCM),
SPDIFIN_TEXT(SPDIFIN_IEC60958_DTS14),
SPDIFIN_TEXT(SPDIFIN_IEC60958_DTS16),
SPDIFIN_TEXT(SPDIFIN_RESERVED)
};
const char * SpdifinStateText[]=
{
SPDIFIN_TEXT(SPDIFIN_STATE_RESET),
SPDIFIN_TEXT(SPDIFIN_STATE_PCM_BYPASS),
SPDIFIN_TEXT(SPDIFIN_STATE_COMPRESSED_BYPASS),
SPDIFIN_TEXT(SPDIFIN_STATE_UNDERFLOW),
SPDIFIN_TEXT(SPDIFIN_STATE_COMPRESSED_MUTE),
SPDIFIN_TEXT(SPDIFIN_STATE_INVALID)
};
static inline const char * reportStreamType(enum eMulticomSpdifinPC type)
{
return (type < SPDIFIN_RESERVED) ? SpdifinStreamTypeText[type] : SpdifinStreamTypeText[SPDIFIN_RESERVED];
}
static inline const char * reportState(enum eMulticomSpdifinState state)
{
return (state < SPDIFIN_STATE_INVALID) ? SpdifinStateText[state] : SpdifinStateText[SPDIFIN_STATE_INVALID];
}
////////////////////////////////////////////////////////////////////////////
///
/// Validate the ACC status structure and squawk loudly if problems are found.
///
/// Dispite the squawking this method unconditionally returns success. This is
/// because the firmware will already have concealed the decode problems by
/// performing a soft mute.
///
/// \return CodecSuccess
///
CodecStatus_t Codec_MmeAudioSpdifin_c::ValidateDecodeContext( CodecBaseDecodeContext_t *Context )
{
SpdifinAudioCodecDecodeContext_t * DecodeContext = (SpdifinAudioCodecDecodeContext_t *) Context;
MME_LxAudioDecoderFrameStatus_t & Status = DecodeContext->DecodeStatus;
ParsedAudioParameters_t * AudioParameters;
enum eMulticomSpdifinState NewState, OldState = SpdifStatus.State;
enum eMulticomSpdifinPC NewPC , OldPC = SpdifStatus.StreamType;
tMMESpdifinStatus *FrameStatus = (tMMESpdifinStatus *) &Status.FrameStatus[0];
NewState = (enum eMulticomSpdifinState) FrameStatus->CurrentState;
NewPC = (enum eMulticomSpdifinPC ) FrameStatus->PC;
bool StatusChange = (AudioDecoderStatus.SamplingFreq != Status.SamplingFreq) ||
(AudioDecoderStatus.DecAudioMode != Status.DecAudioMode);
// HACK: This should bloody well be in the super-class
AudioDecoderStatus = Status;
if ((OldState != NewState) || (OldPC != NewPC) || StatusChange)
{
SpdifStatus.State = NewState;
SpdifStatus.StreamType = NewPC;
report( severity_info, "Codec_MmeAudioSpdifin_c::ValidateDecodeContext() New State :: %s after %d samples\n", reportState(NewState) , SpdifStatus.PlayedSamples);
report( severity_info, "Codec_MmeAudioSpdifin_c::ValidateDecodeContext() New StreamType :: [%d] %s after %d samples\n", NewPC, reportStreamType(NewPC), SpdifStatus.PlayedSamples);
PlayerStatus_t PlayerStatus;
PlayerEventRecord_t Event;
void *EventUserData = NULL;
Event.Code = EventInputFormatChanged;
Event.Playback = Playback;
Event.Stream = Stream;
Event.PlaybackTime = TIME_NOT_APPLICABLE;
Event.UserData = EventUserData;
Event.Value[0].Pointer = this; // pointer to the component
PlayerStatus = Player->SignalEvent( &Event );
if( PlayerStatus != PlayerNoError )
{
report( severity_error, "Codec_MmeAudioSpdifin_c::ValidateDecodeContext - Failed to signal event.\n" );
return CodecError;
}
// END SYSFS
}
SpdifStatus.PlayedSamples += Status.NbOutSamples;
NumberOfSamplesProcessed += Status.NbOutSamples; // SYSFS
CODEC_DEBUG("Codec_MmeAudioSpdifin_c::ValidateDecodeContext() Transform Cmd returned \n");
if (ENABLE_CODEC_DEBUG)
{
//DumpCommand(bufferIndex);
}
if (Status.DecStatus)
{
CODEC_ERROR("SPDIFIN audio decode error (muted frame): %d\n", Status.DecStatus);
DecodeErrors++;
//DumpCommand(bufferIndex);
// don't report an error to the higher levels (because the frame is muted)
}
//
// Attach any codec derived metadata to the output buffer (or verify the
// frame analysis if the frame analyser already filled everything in for
// us).
//
AudioParameters = BufferState[DecodeContext->BaseContext.BufferIndex].ParsedAudioParameters;
// TODO: these values should be extracted from the codec's reply
if (AudioOutputSurface)
{
AudioParameters->Source.BitsPerSample = AudioOutputSurface->BitsPerSample;
AudioParameters->Source.ChannelCount = AudioOutputSurface->ChannelCount;
}
AudioParameters->Organisation = Status.AudioMode;
AudioParameters->SampleCount = Status.NbOutSamples;
enum eAccFsCode SamplingFreqCode = (enum eAccFsCode) Status.SamplingFreq;
if (SamplingFreqCode < ACC_FS_reserved)
{
AudioParameters->Source.SampleRateHz = Codec_MmeAudio_c::ConvertCodecSamplingFreq(SamplingFreqCode);
//AudioParameters->Source.SampleRateHz = 44100;
}
else
{
AudioParameters->Source.SampleRateHz = 0;
CODEC_ERROR("SPDIFIn audio decode bad sampling freq returned: 0x%x\n", SamplingFreqCode);
}
if (SpdifStatus.StreamType == SPDIFIN_AC3)
{
Codec_MmeAudioEAc3_c::FillStreamMetadata(AudioParameters, (MME_LxAudioDecoderFrameStatus_t*)&Status);
}
else if (((SpdifStatus.StreamType >= SPDIFIN_DTS1) && ((SpdifStatus.StreamType <= SPDIFIN_DTS3))) ||
(SpdifStatus.StreamType == SPDIFIN_IEC60958_DTS14) || (SpdifStatus.StreamType == SPDIFIN_IEC60958_DTS16))
{
Codec_MmeAudioDtshd_c::FillStreamMetadata(AudioParameters, (MME_LxAudioDecoderFrameStatus_t*)&Status);
}
else
{
// do nothing, the AudioParameters are zeroed by FrameParser_Audio_c::Input() which is
// appropriate (i.e. OriginalEncoding is AudioOriginalEncodingUnknown)
}
return CodecNoError;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
///
/// Terminate the SPDIFIN mme transformer
/// First Send an Empty BUFFER with EOF Tag so that in unlocks pending TRANSFORM in case it is waiting
/// for more buffers, then wait for all SentBuffers and DecodeTransforms to have returned
CodecStatus_t Codec_MmeAudioSpdifin_c::TerminateMMETransformer( void )
{
CodecStatus_t Status;
if( MMEInitialized )
{
Status = SendEofCommand();
if (CodecNoError != Status)
return Status;
// Call base class that waits enough time for all MME_TRANSFORMS to return
Status = Codec_MmeBase_c::TerminateMMETransformer();
return Status;
}
return CodecNoError;
}
// /////////////////////////////////////////////////////////////////////////
//
// Function to dump out the set stream
// parameters from an mme command.
//
CodecStatus_t Codec_MmeAudioSpdifin_c::DumpSetStreamParameters( void *Parameters )
{
CODEC_ERROR("Not implemented\n");
return CodecNoError;
}
// /////////////////////////////////////////////////////////////////////////
//
// Function to dump out the decode
// parameters from an mme command.
//
CodecStatus_t Codec_MmeAudioSpdifin_c::DumpDecodeParameters( void *Parameters )
{
CODEC_ERROR("Not implemented\n");
return CodecNoError;
}
CodecStatus_t Codec_MmeAudioSpdifin_c::CreateAttributeEvents (void)
{
PlayerStatus_t Status;
PlayerEventRecord_t Event;
void *EventUserData = NULL;
Event.Playback = Playback;
Event.Stream = Stream;
Event.PlaybackTime = TIME_NOT_APPLICABLE;
Event.UserData = EventUserData;
Event.Value[0].Pointer = this;
Status = Codec_MmeAudio_c::CreateAttributeEvents();
if (Status != PlayerNoError)
return Status;
Event.Code = EventInputFormatCreated;
Status = Player->SignalEvent( &Event );
if( Status != PlayerNoError )
{
CODEC_ERROR("Failed to signal event.\n");
return CodecError;
}
Event.Code = EventSupportedInputFormatCreated;
Status = Player->SignalEvent( &Event );
if( Status != PlayerNoError )
{
CODEC_ERROR("Failed to signal event.\n" );
return CodecError;
}
Event.Code = EventDecodeErrorsCreated;
Status = Player->SignalEvent( &Event );
if( Status != PlayerNoError )
{
CODEC_ERROR("Failed to signal event.\n" );
return CodecError;
}
Event.Code = EventNumberOfSamplesProcessedCreated;
Status = Player->SignalEvent( &Event );
if( Status != PlayerNoError )
{
CODEC_ERROR("Failed to signal event.\n" );
return CodecError;
}
return CodecNoError;
}
CodecStatus_t Codec_MmeAudioSpdifin_c::GetAttribute (const char *Attribute, PlayerAttributeDescriptor_t *Value)
{
//report( severity_error, "Codec_MmeAudioSpdifin_c::GetAttribute Enter\n");
if (0 == strcmp(Attribute, "input_format"))
{
Value->Id = SYSFS_ATTRIBUTE_ID_CONSTCHARPOINTER;
#define C(x) case SPDIFIN_ ## x: Value->u.ConstCharPointer = #x; return CodecNoError
switch (SpdifStatus.StreamType)
{
C(NULL_DATA_BURST);
C(AC3);
C(PAUSE_BURST);
C(MP1L1);
C(MP1L2L3);
C(MP2MC);
C(MP2AAC);
C(MP2L1LSF);
C(MP2L2LSF);
C(MP2L3LSF);
C(DTS1);
C(DTS2);
C(DTS3);
C(ATRAC);
C(ATRAC2_3);
case SPDIFIN_IEC60958:
Value->u.ConstCharPointer = "PCM";
return CodecNoError;
C(IEC60958_DTS14);
C(IEC60958_DTS16);
default:
CODEC_ERROR("This input_format does not exist.\n" );
return CodecError;
}
#undef C
}
else if (0 == strcmp(Attribute, "decode_errors"))
{
Value->Id = SYSFS_ATTRIBUTE_ID_INTEGER;
Value->u.Int = DecodeErrors;
return CodecNoError;
}
else if (0 == strcmp(Attribute, "supported_input_format"))
{
//report( severity_error, "%s %d\n", __FUNCTION__, __LINE__);
MME_LxAudioDecoderInfo_t &Capability = AudioDecoderTransformCapability;
Value->Id = SYSFS_ATTRIBUTE_ID_BOOL;
switch (SpdifStatus.StreamType)
{
case SPDIFIN_AC3:
Value->u.Bool = Capability.DecoderCapabilityExtFlags[0] & 0x8; // ACC_SPDIFIN_DD
return CodecNoError;
case SPDIFIN_DTS1:
case SPDIFIN_DTS2:
case SPDIFIN_DTS3:
case SPDIFIN_IEC60958_DTS14:
case SPDIFIN_IEC60958_DTS16:
Value->u.Bool = Capability.DecoderCapabilityExtFlags[0] & 0x10; // ACC_SPDIFIN_DTS
return CodecNoError;
case SPDIFIN_MP2AAC:
Value->u.Bool = Capability.DecoderCapabilityExtFlags[0] & 0x20; // ACC_SPDIFIN_MPG to be renamed ACC_SPDIFIN_AAC
case SPDIFIN_IEC60958:
case SPDIFIN_NULL_DATA_BURST:
case SPDIFIN_PAUSE_BURST:
Value->u.Bool = true;
return CodecNoError;
case SPDIFIN_MP1L1:
case SPDIFIN_MP1L2L3:
case SPDIFIN_MP2MC:
case SPDIFIN_MP2L1LSF:
case SPDIFIN_MP2L2LSF:
case SPDIFIN_MP2L3LSF:
case SPDIFIN_ATRAC:
case SPDIFIN_ATRAC2_3:
default:
Value->u.Bool = false;
return CodecNoError;
}
}
else if (0 == strcmp(Attribute, "number_of_samples_processed"))
{
Value->Id = SYSFS_ATTRIBUTE_ID_UNSIGNEDLONGLONGINT;
Value->u.UnsignedLongLongInt = NumberOfSamplesProcessed;
return CodecNoError;
}
else
{
CodecStatus_t Status;
Status = Codec_MmeAudio_c::GetAttribute (Attribute, Value);
if (Status != CodecNoError)
{
CODEC_ERROR("This attribute does not exist.\n" );
return CodecError;
}
}
return CodecNoError;
}
CodecStatus_t Codec_MmeAudioSpdifin_c::SetAttribute (const char *Attribute, PlayerAttributeDescriptor_t *Value)
{
if (0 == strcmp(Attribute, "decode_errors"))
{
DecodeErrors = Value->u.Int;
return CodecNoError;
}
else
{
CODEC_ERROR("This attribute cannot be set.\n" );
return CodecError;
}
return CodecNoError;
}
| project-magpie/tdt-driver | player2_131/player/codec/codec_mme_audio_spdifin.cpp | C++ | gpl-2.0 | 32,205 |
Ext.define('TrackApp.view.main.Main', {
extend: 'Ext.panel.Panel',
requires: [
'Ext.resizer.Splitter'
],
xtype: 'app-main',
controller: 'main',
viewModel: {
type: 'main'
},
title: 'Oslo-Bergen til fots',
header: {
titlePosition: 0,
defaults: {
xtype: 'button',
toggleGroup: 'menu'
},
items: [{
text: 'Bilder',
id: 'instagram'
},{
text: 'Høydeprofil',
id: 'profile'
},{
text: 'Posisjon',
id: 'positions'
},{
text: 'Facebook',
id: 'facebookUrl',
reference: 'facebookBtn'
},{
text: 'Instagram',
id: 'instagramUrl',
reference: 'instagramBtn'
}]
},
layout: {
type: 'vbox',
pack: 'start',
align: 'stretch'
},
items: [{
reference: 'map',
xtype: 'map',
flex: 3
}, {
reference: 'bottom',
xtype: 'panel',
flex: 2,
//split: true,
hidden: true,
layout: {
type: 'fit'
},
defaults: {
hidden: true
},
items: [{
reference: 'profile',
xtype: 'profile'
},{
reference: 'positions',
xtype: 'positions'
}]
}]
}); | turban/oslobergen | app/view/main/Main.js | JavaScript | gpl-2.0 | 1,049 |
package edu.asu.spring.quadriga.validator;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import edu.asu.spring.quadriga.web.workbench.backing.ModifyCollaborator;
import edu.asu.spring.quadriga.web.workbench.backing.ModifyCollaboratorForm;
/**
* This class validates the collaborator form used for deletion.
* @author kiran batna
*
*/
@Service
public class CollaboratorFormDeleteValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return clazz.isAssignableFrom(ModifyCollaboratorForm.class);
}
@Override
public void validate(Object target, Errors errors) {
ModifyCollaboratorForm collaboratorForm = (ModifyCollaboratorForm)target;
List<ModifyCollaborator> collaboratorList = collaboratorForm.getCollaborators();
String userName;
boolean isAllNull = true;
for(int i=0;i<collaboratorList.size();i++)
{
userName = collaboratorList.get(i).getUserName();
if(userName != null)
{
isAllNull = false;
}
}
if(isAllNull == true)
{
for(int i=0;i<collaboratorList.size();i++)
{
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "collaborators["+i+"].userName", "collaborator_delete_selection.required");
}
}
}
} | diging/quadriga | Quadriga/src/main/java/edu/asu/spring/quadriga/validator/CollaboratorFormDeleteValidator.java | Java | gpl-2.0 | 1,384 |
import contextvars
import gettext
import os
from telebot.asyncio_handler_backends import BaseMiddleware
try:
from babel.support import LazyProxy
babel_imported = True
except ImportError:
babel_imported = False
class I18N(BaseMiddleware):
"""
This middleware provides high-level tool for internationalization
It is based on gettext util.
"""
context_lang = contextvars.ContextVar('language', default=None)
def __init__(self, translations_path, domain_name: str):
super().__init__()
self.update_types = self.process_update_types()
self.path = translations_path
self.domain = domain_name
self.translations = self.find_translations()
@property
def available_translations(self):
return list(self.translations)
def gettext(self, text: str, lang: str = None):
"""
Singular translations
"""
if lang is None:
lang = self.context_lang.get()
if lang not in self.translations:
return text
translator = self.translations[lang]
return translator.gettext(text)
def ngettext(self, singular: str, plural: str, lang: str = None, n=1):
"""
Plural translations
"""
if lang is None:
lang = self.context_lang.get()
if lang not in self.translations:
if n == 1:
return singular
return plural
translator = self.translations[lang]
return translator.ngettext(singular, plural, n)
def lazy_gettext(self, text: str, lang: str = None):
if not babel_imported:
raise RuntimeError('babel module is not imported. Check that you installed it.')
return LazyProxy(self.gettext, text, lang, enable_cache=False)
def lazy_ngettext(self, singular: str, plural: str, lang: str = None, n=1):
if not babel_imported:
raise RuntimeError('babel module is not imported. Check that you installed it.')
return LazyProxy(self.ngettext, singular, plural, lang, n, enable_cache=False)
async def get_user_language(self, obj):
"""
You need to override this method and return user language
"""
raise NotImplementedError
def process_update_types(self) -> list:
"""
You need to override this method and return any update types which you want to be processed
"""
raise NotImplementedError
async def pre_process(self, message, data):
"""
context language variable will be set each time when update from 'process_update_types' comes
value is the result of 'get_user_language' method
"""
self.context_lang.set(await self.get_user_language(obj=message))
async def post_process(self, message, data, exception):
pass
def find_translations(self):
"""
Looks for translations with passed 'domain' in passed 'path'
"""
if not os.path.exists(self.path):
raise RuntimeError(f"Translations directory by path: {self.path!r} was not found")
result = {}
for name in os.listdir(self.path):
translations_path = os.path.join(self.path, name, 'LC_MESSAGES')
if not os.path.isdir(translations_path):
continue
po_file = os.path.join(translations_path, self.domain + '.po')
mo_file = po_file[:-2] + 'mo'
if os.path.isfile(po_file) and not os.path.isfile(mo_file):
raise FileNotFoundError(f"Translations for: {name!r} were not compiled!")
with open(mo_file, 'rb') as file:
result[name] = gettext.GNUTranslations(file)
return result
| eternnoir/pyTelegramBotAPI | examples/asynchronous_telebot/middleware/i18n_middleware_example/i18n_base_midddleware.py | Python | gpl-2.0 | 3,751 |
package edu.sc.seis.fissuresUtil.display;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JComponent;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
import edu.sc.seis.fissuresUtil.display.borders.TimeBorder;
import edu.sc.seis.fissuresUtil.display.borders.TitleBorder;
import edu.sc.seis.fissuresUtil.exceptionHandler.GlobalExceptionHandler;
public class SeismogramPDFBuilder {
public SeismogramPDFBuilder() {
this(true, 1, true);
}
public SeismogramPDFBuilder(boolean landscape,
int dispPerPage,
boolean separateDisplays) {
this(landscape, PAGE_SIZE, MARGIN, dispPerPage, separateDisplays);
}
public SeismogramPDFBuilder(boolean landscape,
Rectangle pageSize,
int margin,
int dispPerPage,
boolean separateDisplays) {
this(landscape,
pageSize,
margin,
margin,
margin,
margin,
dispPerPage,
separateDisplays);
}
public SeismogramPDFBuilder(boolean landscape,
Rectangle pageSize,
int topMargin,
int rightMargin,
int bottomMargin,
int leftMargin,
int dispPerPage,
boolean separateDisplays) {
setPageSize(landscape ? pageSize.rotate() : pageSize);
setMargins(topMargin, rightMargin, bottomMargin, leftMargin);
setDispPerPage(dispPerPage);
}
public void setPageSize(Rectangle pageSize) {
this.pageSize = pageSize;
}
public Rectangle getPageSize() {
return pageSize;
}
public void setMargins(int margin) {
setMargins(margin, margin, margin, margin);
}
public void setMargins(int topMargin,
int rightMargin,
int bottomMargin,
int leftMargin) {
setTopMargin(topMargin);
setRightMargin(rightMargin);
setBottomMargin(bottomMargin);
setLeftMargin(leftMargin);
}
public void setTopMargin(int topMargin) {
this.topMargin = topMargin;
recalculateVertMargins();
}
public int getTopMargin() {
return topMargin;
}
public void setRightMargin(int rightMargin) {
this.rightMargin = rightMargin;
recalculateHorizMargins();
}
public int getRightMargin() {
return rightMargin;
}
public void setBottomMargin(int bottomMargin) {
this.bottomMargin = bottomMargin;
recalculateVertMargins();
}
public int getBottomMargin() {
return bottomMargin;
}
public void setLeftMargin(int leftMargin) {
this.leftMargin = leftMargin;
recalculateHorizMargins();
}
public int getLeftMargin() {
return leftMargin;
}
public void setDispPerPage(int dispPerPage) {
this.dispPerPage = dispPerPage;
}
public int getDispPerPage() {
return dispPerPage;
}
public void setSeparateDisplays(boolean separateDisplays) {
this.separateDisplays = separateDisplays;
}
public boolean getSeparateDisplays() {
return separateDisplays;
}
public void setHeader(TitleBorder header) {
this.header = header;
}
public TitleBorder getHeader() {
return header;
}
public Dimension getPrintableSize() {
return new Dimension((int)(pageSize.getWidth() - leftMargin - rightMargin),
(int)(pageSize.getHeight() - topMargin - bottomMargin));
}
public void createPDF(JComponent disp, File file) throws IOException {
file.getCanonicalFile().getParentFile().mkdirs();
File temp = File.createTempFile(file.getName(),
null,
file.getParentFile());
createPDF(disp, new FileOutputStream(temp));
file.delete();
temp.renameTo(file);
}
public void createPDF(JComponent comp, OutputStream out) {
List displays = new ArrayList();
if(separateDisplays && comp instanceof VerticalSeismogramDisplay) {
displays.addAll(breakOutSeparateDisplays((VerticalSeismogramDisplay)comp));
} else {
displays.add(comp);
}
createPDF((JComponent[])displays.toArray(new JComponent[0]), out);
}
public void createPDF(JComponent[] comps, OutputStream out) {
Document document = new Document(pageSize);
try {
int headerHeight = 0;
if(header != null) {
header.setSize(header.getPreferredSize());
headerHeight = header.getHeight();
}
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
int pageW = (int)pageSize.getWidth();
int pageH = (int)pageSize.getHeight();
int pixelsPerDisplayH = (int)Math.floor((pageH - vertMargins - headerHeight)
/ (double)dispPerPage);
int pixelsPerDisplayW = (int)Math.floor(pageW - horizMargins);
PdfContentByte cb = writer.getDirectContent();
// layer for SeismogramDisplay
PdfTemplate tpTraces = cb.createTemplate(pageW, pageH);
Graphics2D g2Traces = tpTraces.createGraphics(pageW, pageH);
g2Traces.translate(rightMargin, topMargin);
if(header != null) {
header.setSize(new Dimension(pixelsPerDisplayW, headerHeight));
boolean bufferingStatus = header.isDoubleBuffered();
header.setDoubleBuffered(false);
header.paint(g2Traces);
header.setDoubleBuffered(bufferingStatus);
g2Traces.translate(0, headerHeight);
}
int seisOnCurPage = 0;
for(int i = 0; i < comps.length; i++) {
// loop over all traces
boolean bufferingStatus = comps[i].isDoubleBuffered();
comps[i].setDoubleBuffered(false);
if(comps[i] instanceof Graphics2DRenderer) {
((Graphics2DRenderer)comps[i]).renderToGraphics(g2Traces,
new Dimension(pixelsPerDisplayW,
pixelsPerDisplayH));
} else {
comps[i].paint(g2Traces);
}
comps[i].setDoubleBuffered(bufferingStatus);
if(++seisOnCurPage == dispPerPage) {
// page is full, finish page and create a new page.
cb.addTemplate(tpTraces, 0, 0);
g2Traces.dispose();
document.newPage();
tpTraces = cb.createTemplate(pageW, pageH);
g2Traces = tpTraces.createGraphics(pageW, pageH);
g2Traces.translate(rightMargin, topMargin);
// reset current count
seisOnCurPage = 0;
} else {
// step down the page
g2Traces.translate(0, pixelsPerDisplayH);
}
}
if(seisOnCurPage != 0) {
// finish writing to the Graphics2D
cb.addTemplate(tpTraces, 0, 0);
}
g2Traces.dispose();
} catch(DocumentException ex) {
GlobalExceptionHandler.handle("problem saving to pdf", ex);
}
// step 5: we close the document
document.close();
}
private List breakOutSeparateDisplays(VerticalSeismogramDisplay disp) {
List displays = ((VerticalSeismogramDisplay)disp).getDisplays();
Iterator it = displays.iterator();
while(it.hasNext()) {
BasicSeismogramDisplay cur = (BasicSeismogramDisplay)it.next();
cur.clear(BorderedDisplay.BOTTOM_CENTER);
if(!cur.isFilled(BorderedDisplay.TOP_CENTER)) {
cur.add(new TimeBorder(cur), BorderedDisplay.TOP_CENTER);
}
}
return displays;
}
private void recalculateHorizMargins() {
horizMargins = leftMargin + rightMargin;
}
private void recalculateVertMargins() {
vertMargins = topMargin + bottomMargin;
}
private int topMargin, rightMargin, bottomMargin, leftMargin;
private int horizMargins, vertMargins;
private Rectangle pageSize;
private int dispPerPage;
private boolean separateDisplays;
private TitleBorder header;
public static final Rectangle PAGE_SIZE = PageSize.LETTER;
public static final int MARGIN = 50;
}
| crotwell/fissuresUtil | src/main/java/edu/sc/seis/fissuresUtil/display/SeismogramPDFBuilder.java | Java | gpl-2.0 | 9,449 |
/***********************************************************************
MemStream.C
BOOM : Bioinformatics Object Oriented Modules
Copyright (C)2012 William H. Majoros (martiandna@gmail.com).
This is OPEN SOURCE SOFTWARE governed by the Gnu General Public
License (GPL) version 3, as described at www.opensource.org.
***********************************************************************/
#include <iostream>
#include "MemStream.H"
using namespace std;
BOOM::MemStream::MemStream(const char *p)
: p(p)
{
}
BOOM::String BOOM::MemStream::readLine()
{
const char *q=p;
while(true)
switch(*q)
{
case '\n':
case '\0':
goto end;
default:
++q;
}
end:
const char *oldP=p;
unsigned length=q-p;
p=q+1;
return BOOM::String(oldP,length);
}
bool BOOM::MemStream::eof()
{
return *p=='\0';
}
| bmajoros/BOOM | MemStream.C | C++ | gpl-2.0 | 848 |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# <pep8 compliant>
import bpy
from bpy.types import Header, Menu, Panel
from bpy.app.translations import pgettext_iface as iface_
from bpy.app.translations import contexts as i18n_contexts
def opengl_lamp_buttons(column, lamp):
split = column.row()
split.prop(lamp, "use", text="", icon='OUTLINER_OB_LAMP' if lamp.use else 'LAMP_DATA')
col = split.column()
col.active = lamp.use
row = col.row()
row.label(text="Diffuse:")
row.prop(lamp, "diffuse_color", text="")
row = col.row()
row.label(text="Specular:")
row.prop(lamp, "specular_color", text="")
col = split.column()
col.active = lamp.use
col.prop(lamp, "direction", text="")
class USERPREF_HT_header(Header):
bl_space_type = 'USER_PREFERENCES'
def draw(self, context):
layout = self.layout
layout.template_header()
userpref = context.user_preferences
layout.operator_context = 'EXEC_AREA'
layout.operator("wm.save_userpref")
layout.operator_context = 'INVOKE_DEFAULT'
if userpref.active_section == 'INPUT':
layout.operator("wm.keyconfig_import")
layout.operator("wm.keyconfig_export")
elif userpref.active_section == 'ADDONS':
layout.operator("wm.addon_install", icon='FILESEL')
layout.operator("wm.addon_refresh", icon='FILE_REFRESH')
layout.menu("USERPREF_MT_addons_online_resources")
elif userpref.active_section == 'THEMES':
layout.operator("ui.reset_default_theme")
layout.operator("wm.theme_install")
class USERPREF_PT_tabs(Panel):
bl_label = ""
bl_space_type = 'USER_PREFERENCES'
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
def draw(self, context):
layout = self.layout
userpref = context.user_preferences
layout.prop(userpref, "active_section", expand=True)
class USERPREF_MT_interaction_presets(Menu):
bl_label = "Presets"
preset_subdir = "interaction"
preset_operator = "script.execute_preset"
draw = Menu.draw_preset
class USERPREF_MT_appconfigs(Menu):
bl_label = "AppPresets"
preset_subdir = "keyconfig"
preset_operator = "wm.appconfig_activate"
def draw(self, context):
self.layout.operator("wm.appconfig_default", text="Blender (default)")
# now draw the presets
Menu.draw_preset(self, context)
class USERPREF_MT_splash(Menu):
bl_label = "Splash"
def draw(self, context):
layout = self.layout
split = layout.split()
row = split.row()
row.label("")
row = split.row()
row.label("Interaction:")
text = bpy.path.display_name(context.window_manager.keyconfigs.active.name)
if not text:
text = "Blender (default)"
row.menu("USERPREF_MT_appconfigs", text=text)
# only for addons
class USERPREF_MT_splash_footer(Menu):
bl_label = ""
def draw(self, context):
pass
class USERPREF_PT_interface(Panel):
bl_space_type = 'USER_PREFERENCES'
bl_label = "Interface"
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
@classmethod
def poll(cls, context):
userpref = context.user_preferences
return (userpref.active_section == 'INTERFACE')
def draw(self, context):
import sys
layout = self.layout
userpref = context.user_preferences
view = userpref.view
row = layout.row()
col = row.column()
col.label(text="Display:")
col.prop(view, "show_tooltips")
col.prop(view, "show_tooltips_python")
col.prop(view, "show_object_info", text="Object Info")
col.prop(view, "show_large_cursors")
col.prop(view, "show_view_name", text="View Name")
col.prop(view, "show_playback_fps", text="Playback FPS")
col.prop(view, "use_global_scene")
col.prop(view, "object_origin_size")
col.separator()
col.separator()
col.separator()
col.prop(view, "show_mini_axis", text="Display Mini Axis")
sub = col.column()
sub.active = view.show_mini_axis
sub.prop(view, "mini_axis_size", text="Size")
sub.prop(view, "mini_axis_brightness", text="Brightness")
col.separator()
if sys.platform[:3] == "win":
col.label("Warnings")
col.prop(view, "use_quit_dialog")
row.separator()
row.separator()
col = row.column()
col.label(text="View Manipulation:")
col.prop(view, "use_mouse_depth_cursor")
col.prop(view, "use_mouse_depth_navigate")
col.prop(view, "use_zoom_to_mouse")
col.prop(view, "use_rotate_around_active")
col.prop(view, "use_global_pivot")
col.prop(view, "use_camera_lock_parent")
col.separator()
col.prop(view, "use_auto_perspective")
col.prop(view, "smooth_view")
col.prop(view, "rotation_angle")
col.separator()
col.separator()
col.label(text="2D Viewports:")
col.prop(view, "view2d_grid_spacing_min", text="Minimum Grid Spacing")
col.prop(view, "timecode_style")
col.prop(view, "view_frame_type")
if (view.view_frame_type == 'SECONDS'):
col.prop(view, "view_frame_seconds")
elif (view.view_frame_type == 'KEYFRAMES'):
col.prop(view, "view_frame_keyframes")
row.separator()
row.separator()
col = row.column()
#Toolbox doesn't exist yet
#col.label(text="Toolbox:")
#col.prop(view, "show_column_layout")
#col.label(text="Open Toolbox Delay:")
#col.prop(view, "open_left_mouse_delay", text="Hold LMB")
#col.prop(view, "open_right_mouse_delay", text="Hold RMB")
col.prop(view, "show_manipulator")
sub = col.column()
sub.active = view.show_manipulator
sub.prop(view, "manipulator_size", text="Size")
sub.prop(view, "manipulator_handle_size", text="Handle Size")
sub.prop(view, "manipulator_hotspot", text="Hotspot")
col.separator()
col.separator()
col.separator()
col.label(text="Menus:")
col.prop(view, "use_mouse_over_open")
sub = col.column()
sub.active = view.use_mouse_over_open
sub.prop(view, "open_toplevel_delay", text="Top Level")
sub.prop(view, "open_sublevel_delay", text="Sub Level")
col.separator()
col.label(text="Pie Menus:")
sub = col.column(align=True)
sub.prop(view, "pie_animation_timeout")
sub.prop(view, "pie_initial_timeout")
sub.prop(view, "pie_menu_radius")
sub.prop(view, "pie_menu_threshold")
sub.prop(view, "pie_menu_confirm")
col.separator()
col.separator()
col.separator()
col.prop(view, "show_splash")
class USERPREF_PT_edit(Panel):
bl_space_type = 'USER_PREFERENCES'
bl_label = "Edit"
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
@classmethod
def poll(cls, context):
userpref = context.user_preferences
return (userpref.active_section == 'EDITING')
def draw(self, context):
layout = self.layout
userpref = context.user_preferences
edit = userpref.edit
row = layout.row()
col = row.column()
col.label(text="Link Materials To:")
col.prop(edit, "material_link", text="")
col.separator()
col.separator()
col.separator()
col.label(text="New Objects:")
col.prop(edit, "use_enter_edit_mode")
col.label(text="Align To:")
col.prop(edit, "object_align", text="")
col.separator()
col.separator()
col.separator()
col.label(text="Undo:")
col.prop(edit, "use_global_undo")
col.prop(edit, "undo_steps", text="Steps")
col.prop(edit, "undo_memory_limit", text="Memory Limit")
row.separator()
row.separator()
col = row.column()
col.label(text="Grease Pencil:")
col.prop(edit, "grease_pencil_eraser_radius", text="Eraser Radius")
col.separator()
col.prop(edit, "grease_pencil_manhattan_distance", text="Manhattan Distance")
col.prop(edit, "grease_pencil_euclidean_distance", text="Euclidean Distance")
col.separator()
col.prop(edit, "grease_pencil_default_color", text="Default Color")
col.separator()
col.prop(edit, "use_grease_pencil_simplify_stroke", text="Simplify Stroke")
col.separator()
col.separator()
col.separator()
col.separator()
col.label(text="Playback:")
col.prop(edit, "use_negative_frames")
col.separator()
col.separator()
col.separator()
col.label(text="Node Editor:")
col.prop(edit, "node_margin")
col.label(text="Animation Editors:")
col.prop(edit, "fcurve_unselected_alpha", text="F-Curve Visibility")
row.separator()
row.separator()
col = row.column()
col.label(text="Keyframing:")
col.prop(edit, "use_visual_keying")
col.prop(edit, "use_keyframe_insert_needed", text="Only Insert Needed")
col.separator()
col.prop(edit, "use_auto_keying", text="Auto Keyframing:")
col.prop(edit, "use_auto_keying_warning")
sub = col.column()
#~ sub.active = edit.use_keyframe_insert_auto # incorrect, time-line can enable
sub.prop(edit, "use_keyframe_insert_available", text="Only Insert Available")
col.separator()
col.label(text="New F-Curve Defaults:")
col.prop(edit, "keyframe_new_interpolation_type", text="Interpolation")
col.prop(edit, "keyframe_new_handle_type", text="Handles")
col.prop(edit, "use_insertkey_xyz_to_rgb", text="XYZ to RGB")
col.separator()
col.separator()
col.separator()
col.label(text="Transform:")
col.prop(edit, "use_drag_immediately")
row.separator()
row.separator()
col = row.column()
col.prop(edit, "sculpt_paint_overlay_color", text="Sculpt Overlay Color")
col.separator()
col.separator()
col.separator()
col.label(text="Duplicate Data:")
col.prop(edit, "use_duplicate_mesh", text="Mesh")
col.prop(edit, "use_duplicate_surface", text="Surface")
col.prop(edit, "use_duplicate_curve", text="Curve")
col.prop(edit, "use_duplicate_text", text="Text")
col.prop(edit, "use_duplicate_metaball", text="Metaball")
col.prop(edit, "use_duplicate_armature", text="Armature")
col.prop(edit, "use_duplicate_lamp", text="Lamp")
col.prop(edit, "use_duplicate_material", text="Material")
col.prop(edit, "use_duplicate_texture", text="Texture")
#col.prop(edit, "use_duplicate_fcurve", text="F-Curve")
col.prop(edit, "use_duplicate_action", text="Action")
col.prop(edit, "use_duplicate_particle", text="Particle")
class USERPREF_PT_system(Panel):
bl_space_type = 'USER_PREFERENCES'
bl_label = "System"
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
@classmethod
def poll(cls, context):
userpref = context.user_preferences
return (userpref.active_section == 'SYSTEM')
def draw(self, context):
import sys
layout = self.layout
userpref = context.user_preferences
system = userpref.system
split = layout.split()
# 1. Column
column = split.column()
colsplit = column.split(percentage=0.85)
col = colsplit.column()
col.label(text="General:")
col.prop(system, "dpi")
col.label("Virtual Pixel Mode:")
col.prop(system, "virtual_pixel_mode", text="")
col.separator()
col.prop(system, "frame_server_port")
col.prop(system, "scrollback", text="Console Scrollback")
col.separator()
col.label(text="Sound:")
col.row().prop(system, "audio_device", expand=False)
sub = col.column()
sub.active = system.audio_device != 'NONE' and system.audio_device != 'Null'
#sub.prop(system, "use_preview_images")
sub.prop(system, "audio_channels", text="Channels")
sub.prop(system, "audio_mixing_buffer", text="Mixing Buffer")
sub.prop(system, "audio_sample_rate", text="Sample Rate")
sub.prop(system, "audio_sample_format", text="Sample Format")
col.separator()
col.label(text="Screencast:")
col.prop(system, "screencast_fps")
col.prop(system, "screencast_wait_time")
col.separator()
if userpref.addons.find('cycles') != -1:
userpref.addons['cycles'].preferences.draw_impl(col, context)
if hasattr(system, "opensubdiv_compute_type"):
col.label(text="OpenSubdiv compute:")
col.row().prop(system, "opensubdiv_compute_type", text="")
# 2. Column
column = split.column()
colsplit = column.split(percentage=0.85)
col = colsplit.column()
col.label(text="OpenGL:")
col.prop(system, "gl_clip_alpha", slider=True)
col.prop(system, "use_mipmaps")
col.prop(system, "use_gpu_mipmap")
col.prop(system, "use_16bit_textures")
col.separator()
col.label(text="Selection")
col.prop(system, "select_method", text="")
col.separator()
col.label(text="Anisotropic Filtering")
col.prop(system, "anisotropic_filter", text="")
col.separator()
col.label(text="Window Draw Method:")
col.prop(system, "window_draw_method", text="")
col.prop(system, "multi_sample", text="")
if sys.platform == "linux" and system.multi_sample != 'NONE':
col.label(text="Might fail for Mesh editing selection!")
col.separator()
col.prop(system, "use_region_overlap")
col.separator()
col.label(text="Text Draw Options:")
col.prop(system, "use_text_antialiasing")
col.separator()
col.label(text="Textures:")
col.prop(system, "gl_texture_limit", text="Limit Size")
col.prop(system, "texture_time_out", text="Time Out")
col.prop(system, "texture_collection_rate", text="Collection Rate")
col.separator()
col.label(text="Images Draw Method:")
col.prop(system, "image_draw_method", text="")
col.separator()
col.label(text="Sequencer/Clip Editor:")
# currently disabled in the code
# col.prop(system, "prefetch_frames")
col.prop(system, "memory_cache_limit")
# 3. Column
column = split.column()
column.label(text="Solid OpenGL lights:")
split = column.split(percentage=0.1)
split.label()
split.label(text="Colors:")
split.label(text="Direction:")
lamp = system.solid_lights[0]
opengl_lamp_buttons(column, lamp)
lamp = system.solid_lights[1]
opengl_lamp_buttons(column, lamp)
lamp = system.solid_lights[2]
opengl_lamp_buttons(column, lamp)
column.separator()
column.label(text="Color Picker Type:")
column.row().prop(system, "color_picker_type", text="")
column.separator()
column.prop(system, "use_weight_color_range", text="Custom Weight Paint Range")
sub = column.column()
sub.active = system.use_weight_color_range
sub.template_color_ramp(system, "weight_color_range", expand=True)
column.separator()
column.prop(system, "font_path_ui")
column.prop(system, "font_path_ui_mono")
if bpy.app.build_options.international:
column.prop(system, "use_international_fonts")
if system.use_international_fonts:
column.prop(system, "language")
row = column.row()
row.label(text="Translate:", text_ctxt=i18n_contexts.id_windowmanager)
row = column.row(align=True)
row.prop(system, "use_translate_interface", text="Interface", toggle=True)
row.prop(system, "use_translate_tooltips", text="Tooltips", toggle=True)
row.prop(system, "use_translate_new_dataname", text="New Data", toggle=True)
class USERPREF_MT_interface_theme_presets(Menu):
bl_label = "Presets"
preset_subdir = "interface_theme"
preset_operator = "script.execute_preset"
preset_type = 'XML'
preset_xml_map = (
("user_preferences.themes[0]", "Theme"),
("user_preferences.ui_styles[0]", "ThemeStyle"),
)
draw = Menu.draw_preset
class USERPREF_PT_theme(Panel):
bl_space_type = 'USER_PREFERENCES'
bl_label = "Themes"
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
# not essential, hard-coded UI delimiters for the theme layout
ui_delimiters = {
'VIEW_3D': {
"text_grease_pencil",
"text_keyframe",
"speaker",
"freestyle_face_mark",
"split_normal",
"bone_solid",
"paint_curve_pivot",
},
'GRAPH_EDITOR': {
"handle_vertex_select",
},
'IMAGE_EDITOR': {
"paint_curve_pivot",
},
'NODE_EDITOR': {
"layout_node",
},
'CLIP_EDITOR': {
"handle_vertex_select",
}
}
@staticmethod
def _theme_generic(split, themedata, theme_area):
col = split.column()
def theme_generic_recurse(data):
col.label(data.rna_type.name)
row = col.row()
subsplit = row.split(percentage=0.95)
padding1 = subsplit.split(percentage=0.15)
padding1.column()
subsplit = row.split(percentage=0.85)
padding2 = subsplit.split(percentage=0.15)
padding2.column()
colsub_pair = padding1.column(), padding2.column()
props_type = {}
for i, prop in enumerate(data.rna_type.properties):
if prop.identifier == "rna_type":
continue
props_type.setdefault((prop.type, prop.subtype), []).append(prop)
th_delimiters = USERPREF_PT_theme.ui_delimiters.get(theme_area)
for props_type, props_ls in sorted(props_type.items()):
if props_type[0] == 'POINTER':
for i, prop in enumerate(props_ls):
theme_generic_recurse(getattr(data, prop.identifier))
else:
if th_delimiters is None:
# simple, no delimiters
for i, prop in enumerate(props_ls):
colsub_pair[i % 2].row().prop(data, prop.identifier)
else:
# add hard coded delimiters
i = 0
for prop in props_ls:
colsub = colsub_pair[i]
colsub.row().prop(data, prop.identifier)
i = (i + 1) % 2
if prop.identifier in th_delimiters:
if i:
colsub = colsub_pair[1]
colsub.row().label("")
colsub_pair[0].row().label("")
colsub_pair[1].row().label("")
i = 0
theme_generic_recurse(themedata)
@staticmethod
def _theme_widget_style(layout, widget_style):
row = layout.row()
subsplit = row.split(percentage=0.95)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(widget_style, "outline")
colsub.row().prop(widget_style, "item", slider=True)
colsub.row().prop(widget_style, "inner", slider=True)
colsub.row().prop(widget_style, "inner_sel", slider=True)
subsplit = row.split(percentage=0.85)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(widget_style, "text")
colsub.row().prop(widget_style, "text_sel")
colsub.prop(widget_style, "show_shaded")
subsub = colsub.column(align=True)
subsub.active = widget_style.show_shaded
subsub.prop(widget_style, "shadetop")
subsub.prop(widget_style, "shadedown")
layout.separator()
@staticmethod
def _ui_font_style(layout, font_style):
split = layout.split()
col = split.column()
col.label(text="Kerning Style:")
col.row().prop(font_style, "font_kerning_style", expand=True)
col.prop(font_style, "points")
col = split.column()
col.label(text="Shadow Offset:")
col.prop(font_style, "shadow_offset_x", text="X")
col.prop(font_style, "shadow_offset_y", text="Y")
col = split.column()
col.prop(font_style, "shadow")
col.prop(font_style, "shadow_alpha")
col.prop(font_style, "shadow_value")
layout.separator()
@classmethod
def poll(cls, context):
userpref = context.user_preferences
return (userpref.active_section == 'THEMES')
def draw(self, context):
layout = self.layout
theme = context.user_preferences.themes[0]
split_themes = layout.split(percentage=0.2)
sub = split_themes.column()
sub.label(text="Presets:")
subrow = sub.row(align=True)
subrow.menu("USERPREF_MT_interface_theme_presets", text=USERPREF_MT_interface_theme_presets.bl_label)
subrow.operator("wm.interface_theme_preset_add", text="", icon='ZOOMIN')
subrow.operator("wm.interface_theme_preset_add", text="", icon='ZOOMOUT').remove_active = True
sub.separator()
sub.prop(theme, "theme_area", expand=True)
split = layout.split(percentage=0.4)
layout.separator()
layout.separator()
split = split_themes.split()
if theme.theme_area == 'USER_INTERFACE':
col = split.column()
ui = theme.user_interface
col.label(text="Regular:")
self._theme_widget_style(col, ui.wcol_regular)
col.label(text="Tool:")
self._theme_widget_style(col, ui.wcol_tool)
col.label(text="Radio Buttons:")
self._theme_widget_style(col, ui.wcol_radio)
col.label(text="Text:")
self._theme_widget_style(col, ui.wcol_text)
col.label(text="Option:")
self._theme_widget_style(col, ui.wcol_option)
col.label(text="Toggle:")
self._theme_widget_style(col, ui.wcol_toggle)
col.label(text="Number Field:")
self._theme_widget_style(col, ui.wcol_num)
col.label(text="Value Slider:")
self._theme_widget_style(col, ui.wcol_numslider)
col.label(text="Box:")
self._theme_widget_style(col, ui.wcol_box)
col.label(text="Menu:")
self._theme_widget_style(col, ui.wcol_menu)
col.label(text="Pie Menu:")
self._theme_widget_style(col, ui.wcol_pie_menu)
col.label(text="Pulldown:")
self._theme_widget_style(col, ui.wcol_pulldown)
col.label(text="Menu Back:")
self._theme_widget_style(col, ui.wcol_menu_back)
col.label(text="Tooltip:")
self._theme_widget_style(col, ui.wcol_tooltip)
col.label(text="Menu Item:")
self._theme_widget_style(col, ui.wcol_menu_item)
col.label(text="Scroll Bar:")
self._theme_widget_style(col, ui.wcol_scroll)
col.label(text="Progress Bar:")
self._theme_widget_style(col, ui.wcol_progress)
col.label(text="List Item:")
self._theme_widget_style(col, ui.wcol_list_item)
ui_state = theme.user_interface.wcol_state
col.label(text="State:")
row = col.row()
subsplit = row.split(percentage=0.95)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui_state, "inner_anim")
colsub.row().prop(ui_state, "inner_anim_sel")
colsub.row().prop(ui_state, "inner_driven")
colsub.row().prop(ui_state, "inner_driven_sel")
subsplit = row.split(percentage=0.85)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui_state, "inner_key")
colsub.row().prop(ui_state, "inner_key_sel")
colsub.row().prop(ui_state, "blend")
col.separator()
col.separator()
col.label("Styles:")
row = col.row()
subsplit = row.split(percentage=0.95)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui, "menu_shadow_fac")
subsplit = row.split(percentage=0.85)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui, "menu_shadow_width")
row = col.row()
subsplit = row.split(percentage=0.95)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui, "icon_alpha")
subsplit = row.split(percentage=0.85)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui, "widget_emboss")
col.separator()
col.separator()
col.label("Axis Colors:")
row = col.row()
subsplit = row.split(percentage=0.95)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui, "axis_x")
colsub.row().prop(ui, "axis_y")
colsub.row().prop(ui, "axis_z")
subsplit = row.split(percentage=0.85)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
layout.separator()
layout.separator()
elif theme.theme_area == 'BONE_COLOR_SETS':
col = split.column()
for i, ui in enumerate(theme.bone_color_sets):
col.label(text=iface_("Color Set %d:") % (i + 1), translate=False) # i starts from 0
row = col.row()
subsplit = row.split(percentage=0.95)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui, "normal")
colsub.row().prop(ui, "select")
colsub.row().prop(ui, "active")
subsplit = row.split(percentage=0.85)
padding = subsplit.split(percentage=0.15)
colsub = padding.column()
colsub = padding.column()
colsub.row().prop(ui, "show_colored_constraints")
elif theme.theme_area == 'STYLE':
col = split.column()
style = context.user_preferences.ui_styles[0]
col.label(text="Panel Title:")
self._ui_font_style(col, style.panel_title)
col.separator()
col.label(text="Widget:")
self._ui_font_style(col, style.widget)
col.separator()
col.label(text="Widget Label:")
self._ui_font_style(col, style.widget_label)
else:
self._theme_generic(split, getattr(theme, theme.theme_area.lower()), theme.theme_area)
class USERPREF_PT_file(Panel):
bl_space_type = 'USER_PREFERENCES'
bl_label = "Files"
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
@classmethod
def poll(cls, context):
userpref = context.user_preferences
return (userpref.active_section == 'FILES')
def draw(self, context):
layout = self.layout
userpref = context.user_preferences
paths = userpref.filepaths
system = userpref.system
split = layout.split(percentage=0.7)
col = split.column()
col.label(text="File Paths:")
colsplit = col.split(percentage=0.95)
col1 = colsplit.split(percentage=0.3)
sub = col1.column()
sub.label(text="Fonts:")
sub.label(text="Textures:")
sub.label(text="Render Output:")
sub.label(text="Scripts:")
sub.label(text="Sounds:")
sub.label(text="Temp:")
sub.label(text="Render Cache:")
sub.label(text="I18n Branches:")
sub.label(text="Image Editor:")
sub.label(text="Animation Player:")
sub = col1.column()
sub.prop(paths, "font_directory", text="")
sub.prop(paths, "texture_directory", text="")
sub.prop(paths, "render_output_directory", text="")
sub.prop(paths, "script_directory", text="")
sub.prop(paths, "sound_directory", text="")
sub.prop(paths, "temporary_directory", text="")
sub.prop(paths, "render_cache_directory", text="")
sub.prop(paths, "i18n_branches_directory", text="")
sub.prop(paths, "image_editor", text="")
subsplit = sub.split(percentage=0.3)
subsplit.prop(paths, "animation_player_preset", text="")
subsplit.prop(paths, "animation_player", text="")
col.separator()
col.separator()
colsplit = col.split(percentage=0.95)
sub = colsplit.column()
row = sub.split(percentage=0.3)
row.label(text="Auto Execution:")
row.prop(system, "use_scripts_auto_execute")
if system.use_scripts_auto_execute:
box = sub.box()
row = box.row()
row.label(text="Excluded Paths:")
row.operator("wm.userpref_autoexec_path_add", text="", icon='ZOOMIN', emboss=False)
for i, path_cmp in enumerate(userpref.autoexec_paths):
row = box.row()
row.prop(path_cmp, "path", text="")
row.prop(path_cmp, "use_glob", text="", icon='FILTER')
row.operator("wm.userpref_autoexec_path_remove", text="", icon='X', emboss=False).index = i
col = split.column()
col.label(text="Save & Load:")
col.prop(paths, "use_relative_paths")
col.prop(paths, "use_file_compression")
col.prop(paths, "use_load_ui")
col.prop(paths, "use_filter_files")
col.prop(paths, "show_hidden_files_datablocks")
col.prop(paths, "hide_recent_locations")
col.prop(paths, "hide_system_bookmarks")
col.prop(paths, "show_thumbnails")
col.separator()
col.prop(paths, "save_version")
col.prop(paths, "recent_files")
col.prop(paths, "use_save_preview_images")
col.separator()
col.label(text="Auto Save:")
col.prop(paths, "use_keep_session")
col.prop(paths, "use_auto_save_temporary_files")
sub = col.column()
sub.active = paths.use_auto_save_temporary_files
sub.prop(paths, "auto_save_time", text="Timer (mins)")
col.separator()
col.label(text="Text Editor:")
col.prop(system, "use_tabs_as_spaces")
colsplit = col.split(percentage=0.95)
col1 = colsplit.split(percentage=0.3)
sub = col1.column()
sub.label(text="Author:")
sub = col1.column()
sub.prop(system, "author", text="")
class USERPREF_MT_ndof_settings(Menu):
# accessed from the window key-bindings in C (only)
bl_label = "3D Mouse Settings"
def draw(self, context):
layout = self.layout
input_prefs = context.user_preferences.inputs
is_view3d = context.space_data.type == 'VIEW_3D'
layout.prop(input_prefs, "ndof_sensitivity")
layout.prop(input_prefs, "ndof_orbit_sensitivity")
layout.prop(input_prefs, "ndof_deadzone")
if is_view3d:
layout.separator()
layout.prop(input_prefs, "ndof_show_guide")
layout.separator()
layout.label(text="Orbit style")
layout.row().prop(input_prefs, "ndof_view_navigate_method", text="")
layout.row().prop(input_prefs, "ndof_view_rotate_method", text="")
layout.separator()
layout.label(text="Orbit options")
layout.prop(input_prefs, "ndof_rotx_invert_axis")
layout.prop(input_prefs, "ndof_roty_invert_axis")
layout.prop(input_prefs, "ndof_rotz_invert_axis")
# view2d use pan/zoom
layout.separator()
layout.label(text="Pan options")
layout.prop(input_prefs, "ndof_panx_invert_axis")
layout.prop(input_prefs, "ndof_pany_invert_axis")
layout.prop(input_prefs, "ndof_panz_invert_axis")
layout.prop(input_prefs, "ndof_pan_yz_swap_axis")
layout.label(text="Zoom options")
layout.prop(input_prefs, "ndof_zoom_invert")
if is_view3d:
layout.separator()
layout.label(text="Fly/Walk options")
layout.prop(input_prefs, "ndof_fly_helicopter", icon='NDOF_FLY')
layout.prop(input_prefs, "ndof_lock_horizon", icon='NDOF_DOM')
class USERPREF_MT_keyconfigs(Menu):
bl_label = "KeyPresets"
preset_subdir = "keyconfig"
preset_operator = "wm.keyconfig_activate"
def draw(self, context):
props = self.layout.operator("wm.context_set_value", text="Blender (default)")
props.data_path = "window_manager.keyconfigs.active"
props.value = "context.window_manager.keyconfigs.default"
# now draw the presets
Menu.draw_preset(self, context)
class USERPREF_PT_input(Panel):
bl_space_type = 'USER_PREFERENCES'
bl_label = "Input"
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
@classmethod
def poll(cls, context):
userpref = context.user_preferences
return (userpref.active_section == 'INPUT')
@staticmethod
def draw_input_prefs(inputs, layout):
import sys
# General settings
row = layout.row()
col = row.column()
sub = col.column()
sub.label(text="Presets:")
subrow = sub.row(align=True)
subrow.menu("USERPREF_MT_interaction_presets", text=bpy.types.USERPREF_MT_interaction_presets.bl_label)
subrow.operator("wm.interaction_preset_add", text="", icon='ZOOMIN')
subrow.operator("wm.interaction_preset_add", text="", icon='ZOOMOUT').remove_active = True
sub.separator()
sub.label(text="Mouse:")
sub1 = sub.column()
sub1.active = (inputs.select_mouse == 'RIGHT')
sub1.prop(inputs, "use_mouse_emulate_3_button")
sub.prop(inputs, "use_mouse_continuous")
sub.prop(inputs, "drag_threshold")
sub.prop(inputs, "tweak_threshold")
sub.label(text="Select With:")
sub.row().prop(inputs, "select_mouse", expand=True)
sub = col.column()
sub.label(text="Double Click:")
sub.prop(inputs, "mouse_double_click_time", text="Speed")
sub.separator()
sub.prop(inputs, "use_emulate_numpad")
sub.separator()
sub.label(text="Orbit Style:")
sub.row().prop(inputs, "view_rotate_method", expand=True)
sub.separator()
sub.label(text="Zoom Style:")
sub.row().prop(inputs, "view_zoom_method", text="")
if inputs.view_zoom_method in {'DOLLY', 'CONTINUE'}:
sub.row().prop(inputs, "view_zoom_axis", expand=True)
sub.prop(inputs, "invert_mouse_zoom", text="Invert Mouse Zoom Direction")
#sub.prop(inputs, "use_mouse_mmb_paste")
#col.separator()
sub = col.column()
sub.prop(inputs, "invert_zoom_wheel", text="Invert Wheel Zoom Direction")
#sub.prop(view, "wheel_scroll_lines", text="Scroll Lines")
if sys.platform == "darwin":
sub = col.column()
sub.prop(inputs, "use_trackpad_natural", text="Natural Trackpad Direction")
col.separator()
sub = col.column()
sub.label(text="View Navigation:")
sub.row().prop(inputs, "navigation_mode", expand=True)
if inputs.navigation_mode == 'WALK':
walk = inputs.walk_navigation
sub.prop(walk, "use_mouse_reverse")
sub.prop(walk, "mouse_speed")
sub.prop(walk, "teleport_time")
sub = col.column(align=True)
sub.prop(walk, "walk_speed")
sub.prop(walk, "walk_speed_factor")
sub.separator()
sub.prop(walk, "use_gravity")
sub = col.column(align=True)
sub.active = walk.use_gravity
sub.prop(walk, "view_height")
sub.prop(walk, "jump_height")
if inputs.use_ndof:
col.separator()
col.label(text="NDOF Device:")
sub = col.column(align=True)
sub.prop(inputs, "ndof_sensitivity", text="NDOF Sensitivity")
sub.prop(inputs, "ndof_orbit_sensitivity", text="NDOF Orbit Sensitivity")
sub.prop(inputs, "ndof_deadzone", text="NDOF Deadzone")
sub = col.column(align=True)
sub.row().prop(inputs, "ndof_view_navigate_method", expand=True)
sub.row().prop(inputs, "ndof_view_rotate_method", expand=True)
row.separator()
def draw(self, context):
from rna_keymap_ui import draw_keymaps
layout = self.layout
#import time
#start = time.time()
userpref = context.user_preferences
inputs = userpref.inputs
split = layout.split(percentage=0.25)
# Input settings
self.draw_input_prefs(inputs, split)
# Keymap Settings
draw_keymaps(context, split)
#print("runtime", time.time() - start)
class USERPREF_MT_addons_online_resources(Menu):
bl_label = "Online Resources"
# menu to open web-pages with addons development guides
def draw(self, context):
layout = self.layout
layout.operator(
"wm.url_open", text="Add-ons Catalog", icon='URL',
).url = "http://wiki.blender.org/index.php/Extensions:2.6/Py/Scripts"
layout.separator()
layout.operator(
"wm.url_open", text="How to share your add-on", icon='URL',
).url = "http://wiki.blender.org/index.php/Dev:Py/Sharing"
layout.operator(
"wm.url_open", text="Add-on Guidelines", icon='URL',
).url = "http://wiki.blender.org/index.php/Dev:2.5/Py/Scripts/Guidelines/Addons"
layout.operator(
"wm.url_open", text="API Concepts", icon='URL',
).url = bpy.types.WM_OT_doc_view._prefix + "/info_quickstart.html"
layout.operator("wm.url_open", text="Add-on Tutorial", icon='URL',
).url = "http://www.blender.org/api/blender_python_api_current/info_tutorial_addon.html"
class USERPREF_PT_addons(Panel):
bl_space_type = 'USER_PREFERENCES'
bl_label = "Add-ons"
bl_region_type = 'WINDOW'
bl_options = {'HIDE_HEADER'}
_support_icon_mapping = {
'OFFICIAL': 'FILE_BLEND',
'COMMUNITY': 'POSE_DATA',
'TESTING': 'MOD_EXPLODE',
}
@classmethod
def poll(cls, context):
userpref = context.user_preferences
return (userpref.active_section == 'ADDONS')
@staticmethod
def is_user_addon(mod, user_addon_paths):
import os
if not user_addon_paths:
for path in (bpy.utils.script_path_user(),
bpy.utils.script_path_pref()):
if path is not None:
user_addon_paths.append(os.path.join(path, "addons"))
for path in user_addon_paths:
if bpy.path.is_subdir(mod.__file__, path):
return True
return False
@staticmethod
def draw_error(layout, message):
lines = message.split("\n")
box = layout.box()
sub = box.row()
sub.label(lines[0])
sub.label(icon='ERROR')
for l in lines[1:]:
box.label(l)
def draw(self, context):
import os
import addon_utils
layout = self.layout
userpref = context.user_preferences
used_ext = {ext.module for ext in userpref.addons}
userpref_addons_folder = os.path.join(userpref.filepaths.script_directory, "addons")
scripts_addons_folder = bpy.utils.user_resource('SCRIPTS', "addons")
# collect the categories that can be filtered on
addons = [(mod, addon_utils.module_bl_info(mod)) for mod in addon_utils.modules(refresh=False)]
split = layout.split(percentage=0.2)
col = split.column()
col.prop(context.window_manager, "addon_search", text="", icon='VIEWZOOM')
col.label(text="Supported Level")
col.prop(context.window_manager, "addon_support", expand=True)
col.label(text="Categories")
col.prop(context.window_manager, "addon_filter", expand=True)
col = split.column()
# set in addon_utils.modules_refresh()
if addon_utils.error_duplicates:
self.draw_error(col,
"Multiple addons using the same name found!\n"
"likely a problem with the script search path.\n"
"(see console for details)",
)
if addon_utils.error_encoding:
self.draw_error(col,
"One or more addons do not have UTF-8 encoding\n"
"(see console for details)",
)
filter = context.window_manager.addon_filter
search = context.window_manager.addon_search.lower()
support = context.window_manager.addon_support
# initialized on demand
user_addon_paths = []
for mod, info in addons:
module_name = mod.__name__
is_enabled = module_name in used_ext
if info["support"] not in support:
continue
# check if addon should be visible with current filters
if ((filter == "All") or
(filter == info["category"]) or
(filter == "Enabled" and is_enabled) or
(filter == "Disabled" and not is_enabled) or
(filter == "User" and (mod.__file__.startswith((scripts_addons_folder, userpref_addons_folder))))
):
if search and search not in info["name"].lower():
if info["author"]:
if search not in info["author"].lower():
continue
else:
continue
# Addon UI Code
col_box = col.column()
box = col_box.box()
colsub = box.column()
row = colsub.row(align=True)
row.operator(
"wm.addon_expand",
icon='TRIA_DOWN' if info["show_expanded"] else 'TRIA_RIGHT',
emboss=False,
).module = module_name
row.operator(
"wm.addon_disable" if is_enabled else "wm.addon_enable",
icon='CHECKBOX_HLT' if is_enabled else 'CHECKBOX_DEHLT', text="",
emboss=False,
).module = module_name
sub = row.row()
sub.active = is_enabled
sub.label(text='%s: %s' % (info["category"], info["name"]))
if info["warning"]:
sub.label(icon='ERROR')
# icon showing support level.
sub.label(icon=self._support_icon_mapping.get(info["support"], 'QUESTION'))
# Expanded UI (only if additional info is available)
if info["show_expanded"]:
if info["description"]:
split = colsub.row().split(percentage=0.15)
split.label(text="Description:")
split.label(text=info["description"])
if info["location"]:
split = colsub.row().split(percentage=0.15)
split.label(text="Location:")
split.label(text=info["location"])
if mod:
split = colsub.row().split(percentage=0.15)
split.label(text="File:")
split.label(text=mod.__file__, translate=False)
if info["author"]:
split = colsub.row().split(percentage=0.15)
split.label(text="Author:")
split.label(text=info["author"], translate=False)
if info["version"]:
split = colsub.row().split(percentage=0.15)
split.label(text="Version:")
split.label(text='.'.join(str(x) for x in info["version"]), translate=False)
if info["warning"]:
split = colsub.row().split(percentage=0.15)
split.label(text="Warning:")
split.label(text=' ' + info["warning"], icon='ERROR')
user_addon = USERPREF_PT_addons.is_user_addon(mod, user_addon_paths)
tot_row = bool(info["wiki_url"]) + bool(user_addon)
if tot_row:
split = colsub.row().split(percentage=0.15)
split.label(text="Internet:")
if info["wiki_url"]:
split.operator("wm.url_open", text="Documentation", icon='HELP').url = info["wiki_url"]
split.operator("wm.url_open", text="Report a Bug", icon='URL').url = info.get(
"tracker_url",
"https://developer.blender.org/maniphest/task/edit/form/2")
if user_addon:
split.operator("wm.addon_remove", text="Remove", icon='CANCEL').module = mod.__name__
for i in range(4 - tot_row):
split.separator()
# Show addon user preferences
if is_enabled:
addon_preferences = userpref.addons[module_name].preferences
if addon_preferences is not None:
draw = getattr(addon_preferences, "draw", None)
if draw is not None:
addon_preferences_class = type(addon_preferences)
box_prefs = col_box.box()
box_prefs.label("Preferences:")
addon_preferences_class.layout = box_prefs
try:
draw(context)
except:
import traceback
traceback.print_exc()
box_prefs.label(text="Error (see console)", icon='ERROR')
del addon_preferences_class.layout
# Append missing scripts
# First collect scripts that are used but have no script file.
module_names = {mod.__name__ for mod, info in addons}
missing_modules = {ext for ext in used_ext if ext not in module_names}
if missing_modules and filter in {"All", "Enabled"}:
col.column().separator()
col.column().label(text="Missing script files")
module_names = {mod.__name__ for mod, info in addons}
for module_name in sorted(missing_modules):
is_enabled = module_name in used_ext
# Addon UI Code
box = col.column().box()
colsub = box.column()
row = colsub.row(align=True)
row.label(text="", icon='ERROR')
if is_enabled:
row.operator("wm.addon_disable", icon='CHECKBOX_HLT', text="", emboss=False).module = module_name
row.label(text=module_name, translate=False)
if __name__ == "__main__": # only for live edit.
bpy.utils.register_module(__name__)
| AndrewPeelMV/Blender2.78c | 2.78/scripts/startup/bl_ui/space_userpref.py | Python | gpl-2.0 | 50,089 |
<?php
/**
* The header for our theme.
*
* Displays all of the <head> section and everything up till <div id="content">
*
* @package wallerhall
*/
?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php wp_title( '|', true, 'right' ); ?></title>
<link href='http://fonts.googleapis.com/css?family=Forum|Cinzel' rel='stylesheet' type='text/css'>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="page" class="hfeed site">
<a class="skip-link screen-reader-text" href="#content"><?php _e( 'Skip to content', 'stock' ); ?></a>
<header id="masthead" class="site-header" role="banner">
<div class="site-branding">
<h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
<h2 class="site-description"><?php bloginfo( 'description' ); ?></h2>
</div>
<nav id="site-navigation" class="main-navigation" role="navigation">
<button class="menu-toggle"><?php _e( 'Menu', 'stock' ); ?></button>
<?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?>
</nav><!-- #site-navigation -->
</header><!-- #masthead -->
<div id="content" class="site-content">
| samuelbjohnson/wallerhall | wp-content/themes/wallerhall/header.php | PHP | gpl-2.0 | 1,399 |
#include "AddOptionsDialog.h"
#include <wx/tokenzr.h>
#include "ColoursAndFontsManager.h"
#include <wx/sstream.h>
#include <wx/txtstrm.h>
AddOptionsDialog::AddOptionsDialog(wxWindow* parent, const wxString& value)
: AddOptionsDialogBase(parent)
{
LexerConf::Ptr_t lexer = ColoursAndFontsManager::Get().GetLexer("text");
lexer->Apply(m_stc);
wxArrayString lines = ::wxStringTokenize(value, ";");
for(const wxString& line : lines) {
m_stc->AppendText(line + "\n");
}
}
AddOptionsDialog::~AddOptionsDialog() {}
wxString AddOptionsDialog::GetValue() const
{
wxStringInputStream input(m_stc->GetText());
wxTextInputStream text(input);
wxString value;
while(!input.Eof()) {
// Read the next line
value += text.ReadLine();
value += ";";
}
return value.BeforeLast(';');
}
| AJenbo/codelite | LiteEditor/AddOptionsDialog.cpp | C++ | gpl-2.0 | 849 |
<?php
/**
* Edit Site Themes Administration Screen
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/** Load WordPress Administration Bootstrap */
require_once(dirname(__FILE__) . '/admin.php');
if (!is_multisite())
wp_die(__('Multisite support is not enabled.'));
if (!current_user_can('manage_sites'))
wp_die(__('You do not have sufficient permissions to manage themes for this site.'));
get_current_screen()->add_help_tab(array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('The menu is for editing information specific to individual sites, particularly if the admin area of a site is unavailable.') . '</p>' .
'<p>' . __('<strong>Info</strong> - The domain and path are rarely edited as this can cause the site to not work properly. The Registered date and Last Updated date are displayed. Network admins can mark a site as archived, spam, deleted and mature, to remove from public listings or disable.') . '</p>' .
'<p>' . __('<strong>Users</strong> - This displays the users associated with this site. You can also change their role, reset their password, or remove them from the site. Removing the user from the site does not remove the user from the network.') . '</p>' .
'<p>' . sprintf(__('<strong>Themes</strong> - This area shows themes that are not already enabled across the network. Enabling a theme in this menu makes it accessible to this site. It does not activate the theme, but allows it to show in the site’s Appearance menu. To enable a theme for the entire network, see the <a href="%s">Network Themes</a> screen.'), network_admin_url('themes.php')) . '</p>' .
'<p>' . __('<strong>Settings</strong> - This page shows a list of all settings associated with this site. Some are created by WordPress and others are created by plugins you activate. Note that some fields are grayed out and say Serialized Data. You cannot modify these values due to the way the setting is stored in the database.') . '</p>'
));
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Network_Admin_Sites_Screen" target="_blank">Documentation on Site Management</a>') . '</p>' .
'<p>' . __('<a href="http://wordpress.org/support/forum/multisite/" target="_blank">Support Forums</a>') . '</p>'
);
$wp_list_table = _get_list_table('WP_MS_Themes_List_Table');
$action = $wp_list_table->current_action();
$s = isset($_REQUEST['s']) ? $_REQUEST['s'] : '';
// Clean up request URI from temporary args for screen options/paging uri's to work as expected.
$temp_args = array('enabled', 'disabled', 'error');
$_SERVER['REQUEST_URI'] = remove_query_arg($temp_args, $_SERVER['REQUEST_URI']);
$referer = remove_query_arg($temp_args, wp_get_referer());
$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
if (!$id)
wp_die(__('Invalid site ID.'));
$wp_list_table->prepare_items();
$details = get_blog_details($id);
if (!can_edit_network($details->site_id))
wp_die(__('You do not have permission to access this page.'));
$is_main_site = is_main_site($id);
if ($action) {
switch_to_blog($id);
$allowed_themes = get_option('allowedthemes');
switch ($action) {
case 'enable':
check_admin_referer('enable-theme_' . $_GET['theme']);
$theme = $_GET['theme'];
$action = 'enabled';
$n = 1;
if (!$allowed_themes)
$allowed_themes = array($theme => true);
else
$allowed_themes[$theme] = true;
break;
case 'disable':
check_admin_referer('disable-theme_' . $_GET['theme']);
$theme = $_GET['theme'];
$action = 'disabled';
$n = 1;
if (!$allowed_themes)
$allowed_themes = array();
else
unset($allowed_themes[$theme]);
break;
case 'enable-selected':
check_admin_referer('bulk-themes');
if (isset($_POST['checked'])) {
$themes = (array)$_POST['checked'];
$action = 'enabled';
$n = count($themes);
foreach ((array)$themes as $theme)
$allowed_themes[$theme] = true;
} else {
$action = 'error';
$n = 'none';
}
break;
case 'disable-selected':
check_admin_referer('bulk-themes');
if (isset($_POST['checked'])) {
$themes = (array)$_POST['checked'];
$action = 'disabled';
$n = count($themes);
foreach ((array)$themes as $theme)
unset($allowed_themes[$theme]);
} else {
$action = 'error';
$n = 'none';
}
break;
}
update_option('allowedthemes', $allowed_themes);
restore_current_blog();
wp_safe_redirect(add_query_arg(array('id' => $id, $action => $n), $referer));
exit;
}
if (isset($_GET['action']) && 'update-site' == $_GET['action']) {
wp_safe_redirect($referer);
exit();
}
add_thickbox();
add_screen_option('per_page', array('label' => _x('Themes', 'themes per page (screen options)')));
$site_url_no_http = preg_replace('#^http(s)?://#', '', get_blogaddress_by_id($id));
$title_site_url_linked = sprintf(__('Edit Site: <a href="%1$s">%2$s</a>'), get_blogaddress_by_id($id), $site_url_no_http);
$title = sprintf(__('Edit Site: %s'), $site_url_no_http);
$parent_file = 'sites.php';
$submenu_file = 'sites.php';
require(ABSPATH . 'wp-admin/admin-header.php'); ?>
<div class="wrap">
<h2 id="edit-site"><?php echo $title_site_url_linked ?></h2>
<h3 class="nav-tab-wrapper">
<?php
$tabs = array(
'site-info' => array('label' => __('Info'), 'url' => 'site-info.php'),
'site-users' => array('label' => __('Users'), 'url' => 'site-users.php'),
'site-themes' => array('label' => __('Themes'), 'url' => 'site-themes.php'),
'site-settings' => array('label' => __('Settings'), 'url' => 'site-settings.php'),
);
foreach ($tabs as $tab_id => $tab) {
$class = ($tab['url'] == $pagenow) ? ' nav-tab-active' : '';
echo '<a href="' . $tab['url'] . '?id=' . $id . '" class="nav-tab' . $class . '">' . esc_html($tab['label']) . '</a>';
}
?>
</h3><?php
if (isset($_GET['enabled'])) {
$_GET['enabled'] = absint($_GET['enabled']);
echo '<div id="message" class="updated"><p>' . sprintf(_n('Theme enabled.', '%s themes enabled.', $_GET['enabled']), number_format_i18n($_GET['enabled'])) . '</p></div>';
} elseif (isset($_GET['disabled'])) {
$_GET['disabled'] = absint($_GET['disabled']);
echo '<div id="message" class="updated"><p>' . sprintf(_n('Theme disabled.', '%s themes disabled.', $_GET['disabled']), number_format_i18n($_GET['disabled'])) . '</p></div>';
} elseif (isset($_GET['error']) && 'none' == $_GET['error']) {
echo '<div id="message" class="error"><p>' . __('No theme selected.') . '</p></div>';
} ?>
<p><?php _e('Network enabled themes are not shown on this screen.') ?></p>
<form method="get" action="">
<?php $wp_list_table->search_box(__('Search Installed Themes'), 'theme'); ?>
<input type="hidden" name="id" value="<?php echo esc_attr($id) ?>"/>
</form>
<?php $wp_list_table->views(); ?>
<form method="post" action="site-themes.php?action=update-site">
<input type="hidden" name="id" value="<?php echo esc_attr($id) ?>"/>
<?php $wp_list_table->display(); ?>
</form>
</div>
<?php include(ABSPATH . 'wp-admin/admin-footer.php'); ?>
| sean-yb/ybTheme-test | wp-admin/network/site-themes.php | PHP | gpl-2.0 | 7,862 |
/*____________________________________________________________________________
ExifPro Image Viewer
Copyright (C) 2000-2015 Michael Kowalski
____________________________________________________________________________*/
// CopyProgressDlg.cpp : implementation file
//
#include "stdafx.h"
#include "resource.h"
#include "CopyProgressDlg.h"
// CopyProgressDlg dialog
CopyProgressDlg::CopyProgressDlg(CWnd* parent /*=NULL*/)
: CDialog(CopyProgressDlg::IDD, parent)
{
}
CopyProgressDlg::~CopyProgressDlg()
{
}
void CopyProgressDlg::DoDataExchange(CDataExchange* DX)
{
CDialog::DoDataExchange(DX);
DDX_Control(DX, IDC_ANIMATION, animation_);
}
BEGIN_MESSAGE_MAP(CopyProgressDlg, CDialog)
END_MESSAGE_MAP()
// CopyProgressDlg message handlers
BOOL CopyProgressDlg::OnInitDialog()
{
CDialog::OnInitDialog();
animation_.Open(IDR_COPY_ANIM);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
| mikekov/ExifPro | src/CopyProgressDlg.cpp | C++ | gpl-2.0 | 1,034 |
/*
* This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "Common.h"
#include "NetworkManager.h"
#include "NetworkThread.h"
#include "Socket.h"
#include "Log.h"
#include <boost/bind.hpp>
NetworkManager::NetworkManager():
m_NetThreadsCount(1),
m_isRunning(false)
{
}
NetworkManager::~NetworkManager()
{
StopNetwork();
m_acceptor.reset();
m_NetThreads.reset();
}
bool NetworkManager::StartNetworkIO( boost::uint16_t port, const char* address )
{
if( m_NetThreadsCount <= 0 )
{
sLog.outError("Number of network threads is incorrect = %i", m_NetThreadsCount );
return false;
}
m_NetThreadsCount += 1;
m_NetThreads.reset( new NetworkThread[ m_NetThreadsCount ] );
try
{
protocol::Endpoint listen_addr( protocol::IPAddress::from_string( address ), port );
m_acceptor.reset( new protocol::Acceptor( get_acceptor_thread().service() , listen_addr ) );
}
catch( boost::system::error_code& )
{
sLog.outError("Failed to open acceptor, check if the port is free");
return false;
}
m_isRunning = true;
accept_next_connection();
for (size_t i = 0; i < m_NetThreadsCount; ++i)
m_NetThreads[i].Start();
return true;
}
bool NetworkManager::StartNetwork( boost::uint16_t port, std::string& address)
{
m_addr = address;
m_port = port;
return StartNetworkIO(port, address.c_str());
}
void NetworkManager::StopNetwork()
{
if( m_isRunning )
{
m_isRunning = false;
Stop();
Wait();
}
}
void NetworkManager::Wait()
{
if( m_NetThreads )
{
for (size_t i = 0; i < m_NetThreadsCount; ++i)
m_NetThreads[i].Wait();
}
}
void NetworkManager::Stop()
{
if( m_acceptor.get() )
m_acceptor->cancel();
if( m_NetThreads )
{
for (size_t i = 0; i < m_NetThreadsCount; ++i)
m_NetThreads[i].Stop();
}
}
bool NetworkManager::OnSocketOpen( const SocketPtr& sock )
{
NetworkThread& thrd = sock->owner();
thrd.AddSocket( sock );
return true;
}
void NetworkManager::OnSocketClose( const SocketPtr& sock )
{
NetworkThread& thrd = sock->owner();
thrd.RemoveSocket( sock );
}
void NetworkManager::accept_next_connection()
{
NetworkThread& worker = get_network_thread_for_new_connection();
SocketPtr connection = CreateSocket( worker );
m_acceptor->async_accept( connection->socket(),
boost::bind( &NetworkManager::OnNewConnection, this, connection,
boost::asio::placeholders::error) );
}
void NetworkManager::OnNewConnection( SocketPtr connection,
const boost::system::error_code& error )
{
if( error )
{
sLog.outError("Error accepting new client connection!");
return;
}
if( !connection->open() )
{
sLog.outError("Unable to start new client connection!");
connection->CloseSocket();
return;
}
accept_next_connection();
}
NetworkThread& NetworkManager::get_acceptor_thread()
{
return m_NetThreads[0];
}
NetworkThread& NetworkManager::get_network_thread_for_new_connection()
{
//we skip the Acceptor Thread
size_t min = 1;
MANGOS_ASSERT(m_NetThreadsCount > 1);
for (size_t i = 1; i < m_NetThreadsCount; ++i)
{
if (m_NetThreads[i].Connections() < m_NetThreads[min].Connections())
min = i;
}
return m_NetThreads[min];
}
| Lillecarl/RustEmu-Stable | src/shared/Network/NetworkManager.cpp | C++ | gpl-2.0 | 4,295 |
<?php
namespace TYPO3\CMS\Beuser\Controller;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Backend\Template\Components\ButtonBar;
use TYPO3\CMS\Backend\Tree\View\PageTreeView;
use TYPO3\CMS\Backend\Utility\BackendUtility;
use TYPO3\CMS\Backend\View\BackendTemplateView;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Mvc\Controller\ActionController;
use TYPO3\CMS\Extbase\Mvc\View\ViewInterface;
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
/**
* Backend module page permissions
*/
class PermissionController extends ActionController
{
/**
* @var string prefix for session
*/
const SESSION_PREFIX = 'tx_Beuser_';
/**
* @var int the current page id
*/
protected $id;
/**
* @var int
*/
protected $returnId;
/**
* @var int
*/
protected $depth;
/**
* @var int
*/
protected $lastEdited;
/**
* Number of levels to enable recursive settings for
*
* @var int
*/
protected $getLevels = 10;
/**
* @var array
*/
protected $pageInfo = [];
/**
* Backend Template Container
*
* @var string
*/
protected $defaultViewObjectName = BackendTemplateView::class;
/**
* BackendTemplateContainer
*
* @var BackendTemplateView
*/
protected $view;
/**
* Initialize action
*/
protected function initializeAction()
{
// determine id parameter
$this->id = (int)GeneralUtility::_GP('id');
if ($this->request->hasArgument('id')) {
$this->id = (int)$this->request->getArgument('id');
}
// determine depth parameter
$this->depth = ((int)GeneralUtility::_GP('depth') > 0)
? (int) GeneralUtility::_GP('depth')
: $this->getBackendUser()->getSessionData(self::SESSION_PREFIX . 'depth');
if ($this->request->hasArgument('depth')) {
$this->depth = (int)$this->request->getArgument('depth');
}
$this->getBackendUser()->setAndSaveSessionData(self::SESSION_PREFIX . 'depth', $this->depth);
$this->lastEdited = GeneralUtility::_GP('lastEdited');
$this->returnId = GeneralUtility::_GP('returnId');
$this->pageInfo = BackendUtility::readPageAccess($this->id, ' 1=1');
}
/**
* Initializes view
*
* @param ViewInterface $view The view to be initialized
*/
protected function initializeView(ViewInterface $view)
{
parent::initializeView($view);
$view->assign(
'previewUrl',
BackendUtility::viewOnClick(
(int)$this->pageInfo['uid'],
'',
BackendUtility::BEgetRootLine((int)$this->pageInfo['uid'])
)
);
// the view of the update action has a different view class
if ($view instanceof BackendTemplateView) {
$view->getModuleTemplate()->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Beuser/Permissions');
$view->getModuleTemplate()->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/Tooltip');
$view->getModuleTemplate()->addJavaScriptCode(
'jumpToUrl',
'
function jumpToUrl(URL) {
window.location.href = URL;
return false;
}
'
);
$this->registerDocHeaderButtons();
$this->view->getModuleTemplate()->setFlashMessageQueue($this->controllerContext->getFlashMessageQueue());
}
}
/**
* Registers the Icons into the docheader
*
* @throws \InvalidArgumentException
*/
protected function registerDocHeaderButtons()
{
/** @var ButtonBar $buttonBar */
$buttonBar = $this->view->getModuleTemplate()->getDocHeaderComponent()->getButtonBar();
$currentRequest = $this->request;
$moduleName = $currentRequest->getPluginName();
$getVars = $this->request->getArguments();
$lang = $this->getLanguageService();
$extensionName = $currentRequest->getControllerExtensionName();
if (empty($getVars)) {
$modulePrefix = strtolower('tx_' . $extensionName . '_' . $moduleName);
$getVars = ['id', 'M', $modulePrefix];
}
if ($currentRequest->getControllerActionName() === 'edit') {
// CLOSE button:
$closeUrl = $this->uriBuilder->reset()->setArguments([
'action' => 'index',
'id' => $this->id
])->buildBackendUri();
$closeButton = $buttonBar->makeLinkButton()
->setHref($closeUrl)
->setTitle($lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.closeDoc'))
->setIcon($this->view->getModuleTemplate()->getIconFactory()->getIcon(
'actions-close',
Icon::SIZE_SMALL
));
$buttonBar->addButton($closeButton);
// SAVE button:
$saveButton = $buttonBar->makeInputButton()
->setTitle($lang->sL('LLL:EXT:lang/Resources/Private/Language/locallang_core.xlf:rm.saveCloseDoc'))
->setName('tx_beuser_system_beusertxpermission[submit]')
->setValue('Save')
->setForm('PermissionControllerEdit')
->setIcon($this->view->getModuleTemplate()->getIconFactory()->getIcon(
'actions-document-save',
Icon::SIZE_SMALL
))
->setShowLabelText(true);
$buttonBar->addButton($saveButton);
}
// SHORTCUT botton:
$shortcutButton = $buttonBar->makeShortcutButton()
->setModuleName($moduleName)
->setGetVariables($getVars);
$buttonBar->addButton($shortcutButton);
}
/**
* Index action
*/
public function indexAction()
{
if (!$this->id) {
$this->pageInfo = ['title' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'], 'uid' => 0, 'pid' => 0];
}
if ($this->getBackendUser()->workspace != 0) {
// Adding section with the permission setting matrix:
$this->addFlashMessage(
LocalizationUtility::translate('LLL:EXT:beuser/Resources/Private/Language/locallang_mod_permission.xlf:WorkspaceWarningText', 'beuser'),
LocalizationUtility::translate('LLL:EXT:beuser/Resources/Private/Language/locallang_mod_permission.xlf:WorkspaceWarning', 'beuser'),
FlashMessage::WARNING
);
}
// depth options
$depthOptions = [];
$url = $this->uriBuilder->reset()->setArguments([
'action' => 'index',
'depth' => '__DEPTH__',
'id' => $this->id
])->buildBackendUri();
foreach ([1, 2, 3, 4, 10] as $depthLevel) {
$levelLabel = $depthLevel === 1 ? 'level' : 'levels';
$depthOptions[$depthLevel] = $depthLevel . ' ' . LocalizationUtility::translate('LLL:EXT:beuser/Resources/Private/Language/locallang_mod_permission.xlf:' . $levelLabel, 'beuser');
}
$this->view->assign('depthBaseUrl', $url);
$this->view->assign('depth', $this->depth);
$this->view->assign('depthOptions', $depthOptions);
$beUserArray = BackendUtility::getUserNames();
$this->view->assign('beUsers', $beUserArray);
$beGroupArray = BackendUtility::getGroupNames();
$this->view->assign('beGroups', $beGroupArray);
/** @var $tree PageTreeView */
$tree = GeneralUtility::makeInstance(PageTreeView::class);
$tree->init();
$tree->addField('perms_user', true);
$tree->addField('perms_group', true);
$tree->addField('perms_everybody', true);
$tree->addField('perms_userid', true);
$tree->addField('perms_groupid', true);
$tree->addField('hidden');
$tree->addField('fe_group');
$tree->addField('starttime');
$tree->addField('endtime');
$tree->addField('editlock');
// Create the tree from $this->id
if ($this->id) {
$tree->tree[] = ['row' => $this->pageInfo, 'HTML' => $tree->getIcon($this->id)];
} else {
$tree->tree[] = ['row' => $this->pageInfo, 'HTML' => $tree->getRootIcon($this->pageInfo)];
}
$tree->getTree($this->id, $this->depth);
$this->view->assign('viewTree', $tree->tree);
// CSH for permissions setting
$this->view->assign('cshItem', BackendUtility::cshItem('xMOD_csh_corebe', 'perm_module', null, '<span class="btn btn-default btn-sm">|</span>'));
}
/**
* Edit action
*/
public function editAction()
{
$this->view->assign('id', $this->id);
$this->view->assign('depth', $this->depth);
if (!$this->id) {
$this->pageInfo = ['title' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'], 'uid' => 0, 'pid' => 0];
}
if ($this->getBackendUser()->workspace != 0) {
// Adding FlashMessage with the permission setting matrix:
$this->addFlashMessage(
LocalizationUtility::translate('LLL:EXT:beuser/Resources/Private/Language/locallang_mod_permission.xlf:WorkspaceWarningText', 'beuser'),
LocalizationUtility::translate('LLL:EXT:beuser/Resources/Private/Language/locallang_mod_permission.xlf:WorkspaceWarning', 'beuser'),
FlashMessage::WARNING
);
}
// Get usernames and groupnames
$beGroupArray = BackendUtility::getListGroupNames('title,uid');
$beUserArray = BackendUtility::getUserNames();
// Owner selector
$beUserDataArray = [0 => LocalizationUtility::translate('LLL:EXT:beuser/Resources/Private/Language/locallang_mod_permission.xlf:selectNone', 'beuser')];
foreach ($beUserArray as $uid => &$row) {
$beUserDataArray[$uid] = $row['username'];
}
$beUserDataArray[-1] = LocalizationUtility::translate('LLL:EXT:beuser/Resources/Private/Language/locallang_mod_permission.xlf:selectUnchanged', 'beuser');
$this->view->assign('currentBeUser', $this->pageInfo['perms_userid']);
$this->view->assign('beUserData', $beUserDataArray);
// Group selector
$beGroupDataArray = [0 => LocalizationUtility::translate('LLL:EXT:beuser/Resources/Private/Language/locallang_mod_permission.xlf:selectNone', 'beuser')];
foreach ($beGroupArray as $uid => $row) {
$beGroupDataArray[$uid] = $row['title'];
}
$beGroupDataArray[-1] = LocalizationUtility::translate('LLL:EXT:beuser/Resources/Private/Language/locallang_mod_permission.xlf:selectUnchanged', 'beuser');
$this->view->assign('currentBeGroup', $this->pageInfo['perms_groupid']);
$this->view->assign('beGroupData', $beGroupDataArray);
$this->view->assign('pageInfo', $this->pageInfo);
$this->view->assign('returnId', $this->returnId);
$this->view->assign('recursiveSelectOptions', $this->getRecursiveSelectOptions());
}
/**
* Update action
*
* @param array $data
* @param array $mirror
*/
protected function updateAction(array $data, array $mirror)
{
if (!empty($data['pages'])) {
foreach ($data['pages'] as $pageUid => $properties) {
// if the owner and group field shouldn't be touched, unset the option
if ((int)$properties['perms_userid'] === -1) {
unset($properties['perms_userid']);
}
if ((int)$properties['perms_groupid'] === -1) {
unset($properties['perms_groupid']);
}
$connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('pages');
$connection->update(
'pages',
$properties,
['uid' => (int)$pageUid]
);
if (!empty($mirror['pages'][$pageUid])) {
$mirrorPages = GeneralUtility::trimExplode(',', $mirror['pages'][$pageUid]);
foreach ($mirrorPages as $mirrorPageUid) {
$connection->update(
'pages',
$properties,
['uid' => (int)$mirrorPageUid]
);
}
}
}
}
$this->redirect('index', null, null, ['id' => $this->returnId, 'depth' => $this->depth]);
}
/**
* @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
*/
protected function getBackendUser()
{
return $GLOBALS['BE_USER'];
}
/**
* Finding tree and offer setting of values recursively.
*
* @return array
*/
protected function getRecursiveSelectOptions()
{
// Initialize tree object:
$tree = GeneralUtility::makeInstance(PageTreeView::class);
$tree->init();
$tree->addField('perms_userid', true);
$tree->makeHTML = 0;
$tree->setRecs = 1;
// Make tree:
$tree->getTree($this->id, $this->getLevels, '');
$options = [];
$options[''] = '';
// If there are a hierarchy of page ids, then...
if ($this->getBackendUser()->user['uid'] && !empty($tree->orig_ids_hierarchy)) {
// Init:
$labelRecursive = LocalizationUtility::translate('LLL:EXT:beuser/Resources/Private/Language/locallang_mod_permission.xlf:recursive', 'beuser');
$labelLevel = LocalizationUtility::translate('LLL:EXT:beuser/Resources/Private/Language/locallang_mod_permission.xlf:level', 'beuser');
$labelLevels = LocalizationUtility::translate('LLL:EXT:beuser/Resources/Private/Language/locallang_mod_permission.xlf:levels', 'beuser');
$labelPageAffected = LocalizationUtility::translate('LLL:EXT:beuser/Resources/Private/Language/locallang_mod_permission.xlf:page_affected', 'beuser');
$labelPagesAffected = LocalizationUtility::translate('LLL:EXT:beuser/Resources/Private/Language/locallang_mod_permission.xlf:pages_affected', 'beuser');
$theIdListArr = [];
// Traverse the number of levels we want to allow recursive
// setting of permissions for:
for ($a = $this->getLevels; $a > 0; $a--) {
if (is_array($tree->orig_ids_hierarchy[$a])) {
foreach ($tree->orig_ids_hierarchy[$a] as $theId) {
$theIdListArr[] = $theId;
}
$lKey = $this->getLevels - $a + 1;
$pagesCount = count($theIdListArr);
$options[implode(',', $theIdListArr)] = $labelRecursive . ' ' . $lKey . ' ' . ($lKey === 1 ? $labelLevel : $labelLevels) .
' (' . $pagesCount . ' ' . ($pagesCount === 1 ? $labelPageAffected : $labelPagesAffected) . ')';
}
}
}
return $options;
}
/**
* Returns LanguageService
*
* @return \TYPO3\CMS\Lang\LanguageService
*/
protected function getLanguageService()
{
return $GLOBALS['LANG'];
}
}
| ksjogo/TYPO3.CMS | typo3/sysext/beuser/Classes/Controller/PermissionController.php | PHP | gpl-2.0 | 15,936 |
<?php
/**
* Skin loader function & helpers
*
* @package Total
* @subpackage Skins
* @author Alexander Clarke
* @copyright Copyright (c) 2014, Symple Workz LLC
* @link http://www.wpexplorer.com
* @since Total 1.5.4
*/
/**
* Skins Loader Class
*
* @since Total 1.6.3
*/
if ( ! class_exists( 'WPEX_Skin_Loader' ) ) {
class WPEX_Skin_Loader {
/**
* Returns the current skin name
*
* @since 1.6.3
* @var $current_skin
* @access private
* @return string
*/
private $current_skin = 'base';
/**
* Start things up
*
* @since 1.6.3
*/
function __construct() {
// Get the current skin
$current_skin = $this->current_skin();
// Load skin if needed
if ( $current_skin && 'base' != $current_skin ) {
$this->load_skin( $current_skin );
}
// Include skins admin panel functions
require_once( WPEX_SKIN_DIR . 'admin/skins-admin.php' );
}
/**
* Array of available skins
*
* @since 1.6.3
*/
public function skins_array() {
$skins = array(
'base' => array (
'core' => true,
'name' => __( 'Base', 'wpex' ),
'screenshot' => WPEX_SKIN_DIR_URI .'classes/base/screenshot.jpg',
),
'agent' => array(
'core' => true,
'name' => __( 'Agent', 'wpex' ),
'class' => WPEX_SKIN_DIR .'classes/agent/agent-skin.php',
'screenshot' => WPEX_SKIN_DIR_URI .'classes/agent/screenshot.jpg',
),
'neat' => array(
'core' => true,
'name' => __( 'Neat', 'wpex' ),
'class' => WPEX_SKIN_DIR .'classes/neat/neat-skin.php',
'screenshot' => WPEX_SKIN_DIR_URI .'classes/neat/screenshot.jpg',
),
'flat' => array(
'core' => true,
'name' => __( 'Flat', 'wpex' ),
'class' => WPEX_SKIN_DIR .'classes/flat/flat-skin.php',
'screenshot' => WPEX_SKIN_DIR_URI .'classes/flat/screenshot.jpg',
),
'gaps' => array(
'core' => true,
'name' => __( 'Gaps', 'wpex' ),
'class' => WPEX_SKIN_DIR .'classes/gaps/gaps-skin.php',
'screenshot' => WPEX_SKIN_DIR_URI .'classes/gaps/screenshot.jpg',
),
'minimal-graphical' => array(
'core' => true,
'name' => __( 'Minimal Graphical', 'wpex' ),
'class' => WPEX_SKIN_DIR .'classes/minimal-graphical/minimal-graphical-skin.php',
'screenshot' => WPEX_SKIN_DIR_URI .'classes/minimal-graphical/screenshot.jpg',
),
);
// Add filter so you can create more skins via child themes or plugins
$skins = apply_filters( 'wpex_skins', $skins );
// Return skins
return $skins;
}
/**
* Returns the current skin
*
* @since 1.6.3
*/
public function current_skin() {
// Get skin from theme mod
$skin = get_theme_mod( 'theme_skin', 'base' );
// Sanitize
if ( ! $skin ) {
$skin = 'base';
}
// Return current skin
return $skin;
}
/**
* Returns the correct class file for the current skin
*
* @since 1.6.3
*/
public function current_skin_file( $active_skin ) {
// Nothing needed for the base skin or an empty skin
if ( 'base' == $active_skin || ! $active_skin ) {
return;
}
// Get currect skin class to load later
$skins = $this->skins_array();
$active_skin_array = wp_array_slice_assoc( $skins, array( $active_skin ) );
if ( is_array( $active_skin_array ) ) {
$is_core = ! empty( $active_skin_array[$active_skin]['core'] ) ? true : false;
$class_file = ! empty( $active_skin_array[$active_skin]['class'] ) ? $active_skin_array[$active_skin]['class'] : false;
}
// Return class file if one exists
if ( $is_core && $class_file ) {
return $class_file;
}
}
/**
* Load the active skin
*
* @since 1.6.3
*/
public function load_skin( $current_skin ) {
// Get skin file
$file = $this->current_skin_file( $current_skin );
// Load the file if it exists
if ( $file ) {
require_once( $file );
}
}
}
}
new WPEX_Skin_Loader();
/**
* Helper function that returns skins array
*
* @since Total 1.6.3
*/
if ( ! function_exists( 'wpex_skins' ) ) {
function wpex_skins() {
$class = new WPEX_Skin_Loader();
return $class->skins_array();
}
}
/**
* Helper function that returns active skin name
*
* @since Total 1.6.3
*/
if ( ! function_exists( 'wpex_active_skin' ) ) {
function wpex_active_skin() {
$class = new WPEX_Skin_Loader();
return $class->current_skin();
}
} | naoyawada/Concurrent | wp-content/themes/Total/skins/skins.php | PHP | gpl-2.0 | 5,852 |
using System;
using Server;
using Server.Targeting;
using Server.Mobiles;
using Server.Network;
using Server.Items;
using Server.Gumps;
using System.Collections;
using System.Collections.Generic;
using Server.ContextMenus;
using Server.SkillHandlers;
namespace Server.Gumps
{
public class ImbuingGumpC : Gump
{
private const int LabelHue = 0x480;
private const int LabelColor = 0x7FFF; //Localized
private const int FontColor = 0xFFFFFF; //string
private const int ValueColor = 0xCCCCFF;
public const int MaxProps = 5;
private int m_Mod, m_Value;
private Item m_Item;
private int m_GemAmount = 0, m_PrimResAmount = 0, m_SpecResAmount = 0;
private int m_TotalItemWeight;
private int m_TotalProps;
private int m_PropWeight;
private int m_MaxWeight;
private ImbuingDefinition m_Definition;
public ImbuingGumpC(Mobile from, Item item, int mod, int value) : base(520, 340)
{
PlayerMobile m = from as PlayerMobile;
from.CloseGump(typeof(ImbuingGump));
from.CloseGump(typeof(ImbuingGumpB));
from.CloseGump(typeof(RunicReforgingGump));
// SoulForge Check
if (!Imbuing.CheckSoulForge(from, 1))
return;
ImbuingContext context = Imbuing.GetContext(m);
// = Check Type of Ingredients Needed
if (!Imbuing.Table.ContainsKey(mod))
return;
m_Definition = Imbuing.Table[mod];
if (value == -1)
value = m_Definition.IncAmount;
m_Item = item;
m_Mod = mod;
m_Value = value;
int maxInt = Imbuing.GetMaxIntensity(item, m_Definition);
int inc = m_Definition.IncAmount;
int weight = m_Definition.Weight;
if (m_Item is BaseJewel && m_Mod == 12)
maxInt /= 2;
if (m_Value < inc) m_Value = inc;
if (m_Value > maxInt) m_Value = maxInt;
if (m_Value <= 0)
m_Value = 1;
double currentIntensity = Math.Floor((m_Value / (double)maxInt) * 100);
//Set context
context.LastImbued = item;
context.Imbue_Mod = mod;
context.Imbue_ModVal = weight;
context.ImbMenu_ModInc = inc;
context.Imbue_ModInt = value;
// - Current Mod Weight
m_TotalItemWeight = Imbuing.GetTotalWeight(m_Item, m_Mod);
m_TotalProps = Imbuing.GetTotalMods(m_Item, m_Mod);
if (maxInt <= 1)
currentIntensity= 100;
m_PropWeight = (int)Math.Floor(((double)weight / (double)maxInt) * m_Value);
// - Maximum allowed Property Weight & Item Mod Count
m_MaxWeight = Imbuing.GetMaxWeight(m_Item);
// = Times Item has been Imbued
int timesImbued = 0;
if (m_Item is BaseWeapon)
timesImbued = ((BaseWeapon)m_Item).TimesImbued;
if (m_Item is BaseArmor)
timesImbued = ((BaseArmor)m_Item).TimesImbued;
if (m_Item is BaseJewel)
timesImbued = ((BaseJewel)m_Item).TimesImbued;
if (m_Item is BaseHat)
timesImbued = ((BaseHat)m_Item).TimesImbued;
// = Check Ingredients needed at the current Intensity
m_GemAmount = Imbuing.GetGemAmount(m_Item, m_Mod, m_Value);
m_PrimResAmount = Imbuing.GetPrimaryAmount(m_Item, m_Mod, m_Value);
m_SpecResAmount = Imbuing.GetSpecialAmount(m_Item, m_Mod, m_Value);
// ------------------------------ Gump Menu -------------------------------------------------------------
AddPage(0);
AddBackground(0, 0, 520, 440, 5054);
AddImageTiled(10, 10, 500, 420, 2624);
AddImageTiled(10, 30, 500, 10, 5058);
AddImageTiled(250, 40, 10, 290, 5058);
AddImageTiled(10, 180, 500, 10, 5058);
AddImageTiled(10, 330, 500, 10, 5058);
AddImageTiled(10, 400, 500, 10, 5058);
AddAlphaRegion(10, 10, 500, 420);
AddHtmlLocalized(10, 12, 520, 20, 1079717, LabelColor, false, false); //<CENTER>IMBUING CONFIRMATION</CENTER>
AddHtmlLocalized(50, 50, 200, 20, 1114269, LabelColor, false, false); //PROPERTY INFORMATION
AddHtmlLocalized(25, 80, 80, 20, 1114270, LabelColor, false, false); //Property:
AddHtmlLocalized(95, 80, 150, 20, m_Definition.AttributeName, LabelColor, false, false);
AddHtmlLocalized(25, 100, 80, 20, 1114271, LabelColor, false, false); // Replaces:
int replace = WhatReplacesWhat(m_Mod, m_Item);
if (replace > 0)
{
AddHtmlLocalized(95, 100, 150, 20, replace, LabelColor, false, false);
}
// - Weight Modifier
AddHtmlLocalized(25, 120, 80, 20, 1114272, 0xFFFFFF, false, false); //Weight:
AddLabel(95, 120, 1153, String.Format("{0}x", ((double)m_Definition.Weight / 100.0).ToString("0.0")));
AddHtmlLocalized(25, 140, 80, 20, 1114273, LabelColor, false, false); //Intensity:
AddLabel(95, 140, 1153, String.Format("{0}%", currentIntensity));
// - Materials needed
AddHtmlLocalized(10, 200, 245, 20, 1044055, LabelColor, false, false); //<CENTER>MATERIALS</CENTER>
AddHtmlLocalized(40, 230, 180, 20, m_Definition.PrimaryName, LabelColor, false, false);
AddLabel(210, 230, 1153, m_PrimResAmount.ToString());
AddHtmlLocalized(40, 255, 180, 20, m_Definition.GemName, LabelColor, false, false);
AddLabel(210, 255, 1153, m_GemAmount.ToString());
if (m_SpecResAmount > 0)
{
AddHtmlLocalized(40, 280, 180, 17, m_Definition.SpecialName, LabelColor, false, false);
AddLabel(210, 280, 1153, m_SpecResAmount.ToString());
}
// - Mod Description
AddHtmlLocalized(280, 55, 200, 110, m_Definition.Description, LabelColor, false, false);
AddHtmlLocalized(350, 200, 150, 20, 1113650, LabelColor, false, false); //RESULTS
AddHtmlLocalized(280, 220, 150, 20, 1113645, LabelColor, false, false); //Properties:
AddLabel(430, 220, m_TotalProps + 1 >= 5 ? 54 : 64, String.Format("{0}/5", m_TotalProps + 1));
int projWeight = m_TotalItemWeight + m_PropWeight;
AddHtmlLocalized(280, 240, 150, 20, 1113646, LabelColor, false, false); //Total Property Weight:
AddLabel(430, 240, projWeight >= m_MaxWeight ? 54 : 64, String.Format("{0}/{1}", projWeight, m_MaxWeight));
AddHtmlLocalized(280, 260, 150, 20, 1113647, LabelColor, false, false); //Times Imbued:
AddLabel(430, 260, timesImbued >= 20 ? 54 : 64, String.Format("{0}/20", timesImbued));
// ===== CALCULATE DIFFICULTY =====
double dif;
double suc = Imbuing.GetSuccessChance(from, item, m_TotalItemWeight, m_PropWeight, out dif);
int color = 64;
AddHtmlLocalized(300, 300, 150, 20, 1044057, 0xFFFFFF, false, false); // Success Chance:
if (suc > 100) suc = 100;
if (suc < 0) suc = 0;
if (suc < 75.0)
{
if (suc >= 50.0)
{
color = 54;
}
else
{
color = 46;
}
}
AddLabel(420, 300, color, String.Format("{0}%", suc.ToString("0.0")));
// - Attribute Level
if (maxInt > 1)
{
// - Set Intesity to Minimum
if (m_Value <= 0)
m_Value = 1;
// = New Value:
AddHtmlLocalized(235, 350, 100, 17, 1062300, LabelColor, false, false); // New Value:
if (m_Mod == 41) // - Mage Weapon Value ( i.e [Mage Weapon -25] )
AddHtml(240, 368, 40, 20, String.Format("<CENTER><BASEFONT COLOR=#CCCCFF> -{0}</CENTER>", 30 - m_Value), false, false);
else if (maxInt <= 8 || m_Mod == 21 || m_Mod == 17) // - Show Property Value as just Number ( i.e [Mana Regen 2] )
AddHtml(240, 368, 40, 20, String.Format("<CENTER><BASEFONT COLOR=#CCCCFF> {0}</CENTER>", m_Value), false, false);
else // - Show Property Value as % ( i.e [Hit Fireball 25%] )
AddHtml(240, 368, 40, 20, String.Format("<CENTER><BASEFONT COLOR=#CCCCFF> {0}%</CENTER>", m_Value), false, false);
// == Buttons ==
AddButton(180, 370, 5230, 5230, 10053, GumpButtonType.Reply, 0); // To Minimum Value
AddButton(200, 370, 5230, 5230, 10052, GumpButtonType.Reply, 0); // Dec Value by %
AddButton(220, 370, 5230, 5230, 10051, GumpButtonType.Reply, 0); // dec value by 1
AddButton(320, 370, 5230, 5230, 10056, GumpButtonType.Reply, 0); //To Maximum Value
AddButton(300, 370, 5230, 5230, 10055, GumpButtonType.Reply, 0); // Inc Value by %
AddButton(280, 370, 5230, 5230, 10054, GumpButtonType.Reply, 0); // inc Value by 1
AddLabel(322, 368, 0, ">");
AddLabel(326, 368, 0, ">");
AddLabel(330, 368, 0, ">");
AddLabel(304, 368, 0, ">");
AddLabel(308, 368, 0, ">");
AddLabel(286, 368, 0, ">");
AddLabel(226, 368, 0, "<");
AddLabel(203, 368, 0, "<");
AddLabel(207, 368, 0, "<");
AddLabel(181, 368, 0, "<");
AddLabel(185, 368, 0, "<");
AddLabel(189, 368, 0, "<");
}
AddButton(15, 410, 4005, 4007, 10099, GumpButtonType.Reply, 0);
AddHtmlLocalized(50, 410, 100, 18, 1114268, LabelColor, false, false); //Back
AddButton(390, 410, 4005, 4007, 10100, GumpButtonType.Reply, 0);
AddHtmlLocalized(425, 410, 120, 18, 1114267, LabelColor, false, false); //Imbue Item
}
public override void OnResponse(NetState state, RelayInfo info)
{
Mobile from = state.Mobile;
PlayerMobile pm = from as PlayerMobile;
ImbuingContext context = Imbuing.GetContext(pm);
int buttonNum = 0;
if (info.ButtonID > 0 && info.ButtonID < 10000)
buttonNum = 0;
else if (info.ButtonID > 20004)
buttonNum = 30000;
else
buttonNum = info.ButtonID;
switch (buttonNum)
{
case 0:
{
//Close
break;
}
case 10051: // = Decrease Mod Value [<]
{
if (context.Imbue_ModInt > m_Definition.IncAmount)
context.Imbue_ModInt -= m_Definition.IncAmount;
from.SendGump(new ImbuingGumpC(from, m_Item, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10052:// = Decrease Mod Value [<<]
{
if ((m_Mod == 42 || m_Mod == 24) && context.Imbue_ModInt > 20)
context.Imbue_ModInt -= 20;
if ((m_Mod == 13 || m_Mod == 20 || m_Mod == 21) && context.Imbue_ModInt > 10)
context.Imbue_ModInt -= 10;
else if (context.Imbue_ModInt > 5)
context.Imbue_ModInt -= 5;
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10053:// = Minimum Mod Value [<<<]
{
context.Imbue_ModInt = 1;
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10054: // = Increase Mod Value [>]
{
int max = Imbuing.GetMaxIntensity(m_Item, m_Definition);
if(m_Mod == 12 && context.LastImbued is BaseJewel)
max /= 2;
if (context.Imbue_ModInt + m_Definition.IncAmount <= max)
context.Imbue_ModInt += m_Definition.IncAmount;
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10055: // = Increase Mod Value [>>]
{
int max = Imbuing.GetMaxIntensity(m_Item, m_Definition);
if (m_Mod == 12 && context.LastImbued is BaseJewel)
max /= 2;
if (m_Mod == 42 || m_Mod == 24)
{
if (context.Imbue_ModInt + 20 <= max)
context.Imbue_ModInt += 20;
else
context.Imbue_ModInt = max;
}
if (m_Mod == 13 || m_Mod == 20 || m_Mod == 21)
{
if (context.Imbue_ModInt + 10 <= max)
context.Imbue_ModInt += 10;
else
context.Imbue_ModInt = max;
}
else if (context.Imbue_ModInt + 5 <= max)
context.Imbue_ModInt += 5;
else
context.Imbue_ModInt = Imbuing.GetMaxIntensity(m_Item, m_Definition);
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10056: // = Maximum Mod Value [>>>]
{
int max = Imbuing.GetMaxIntensity(m_Item, m_Definition);
if (m_Mod == 12 && context.LastImbued is BaseJewel)
max /= 2;
context.Imbue_ModInt = max;
from.SendGump(new ImbuingGumpC(from, context.LastImbued, context.Imbue_Mod, context.Imbue_ModInt));
break;
}
case 10099: // - Back
{
from.SendGump(new ImbuingGumpB(from, context.LastImbued));
break;
}
case 10100: // = Imbue the Item
{
context.Imbue_IWmax = m_MaxWeight;
if (Imbuing.OnBeforeImbue(from, m_Item, m_Mod, m_Value, m_TotalProps, MaxProps, m_TotalItemWeight, m_MaxWeight))
{
Imbuing.ImbueItem(from, m_Item, m_Mod, m_Value);
SendGumpDelayed(from);
}
break;
}
}
}
public void SendGumpDelayed(Mobile from)
{
Timer.DelayCall(TimeSpan.FromSeconds(1.5), new TimerStateCallback(SendGump_Callback), from);
}
public void SendGump_Callback(object o)
{
Mobile from = o as Mobile;
if (from != null)
from.SendGump(new ImbuingGump(from));
}
// =========== Check if Choosen Attribute Replaces Another =================
public static int WhatReplacesWhat(int mod, Item item)
{
if (Imbuing.GetValueForMod(item, mod) > 0)
{
return Imbuing.GetAttributeName(mod);
}
if (item is BaseWeapon)
{
BaseWeapon i = item as BaseWeapon;
// Slayers replace Slayers
if (mod >= 101 && mod <= 127)
{
if (i.Slayer != SlayerName.None)
return GetNameForAttribute(i.Slayer);
if (i.Slayer2 != SlayerName.None)
return GetNameForAttribute(i.Slayer2);
}
// OnHitEffect replace OnHitEffect
if (mod >= 35 && mod <= 39)
{
if (i.WeaponAttributes.HitMagicArrow > 0)
return GetNameForAttribute(AosWeaponAttribute.HitMagicArrow);
else if (i.WeaponAttributes.HitHarm > 0)
return GetNameForAttribute(AosWeaponAttribute.HitHarm);
else if (i.WeaponAttributes.HitFireball > 0)
return GetNameForAttribute(AosWeaponAttribute.HitFireball);
else if (i.WeaponAttributes.HitLightning > 0)
return GetNameForAttribute(AosWeaponAttribute.HitLightning);
else if (i.WeaponAttributes.HitDispel > 0)
return GetNameForAttribute(AosWeaponAttribute.HitDispel);
}
// OnHitArea replace OnHitArea
if (mod >= 30 && mod <= 34)
{
if (i.WeaponAttributes.HitPhysicalArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitPhysicalArea);
else if (i.WeaponAttributes.HitColdArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitFireArea);
else if (i.WeaponAttributes.HitFireArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitColdArea);
else if (i.WeaponAttributes.HitPoisonArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitPoisonArea);
else if (i.WeaponAttributes.HitEnergyArea > 0)
return GetNameForAttribute(AosWeaponAttribute.HitEnergyArea);
}
}
if (item is BaseJewel)
{
BaseJewel i = item as BaseJewel;
// SkillGroup1 replace SkillGroup1
if (mod >= 151 && mod <= 155)
{
if (i.SkillBonuses.GetBonus(0) > 0)
{
foreach (SkillName sk in Imbuing.PossibleSkills)
{
if(i.SkillBonuses.GetSkill(0) == sk)
return GetNameForAttribute(sk);
}
}
}
// SkillGroup2 replace SkillGroup2
if (mod >= 156 && mod <= 160)
{
if (i.SkillBonuses.GetBonus(1) > 0)
{
foreach (SkillName sk in Imbuing.PossibleSkills)
{
if (i.SkillBonuses.GetSkill(1) == sk)
return GetNameForAttribute(sk);
}
}
}
// SkillGroup3 replace SkillGroup3
if (mod >= 161 && mod <= 166)
{
if (i.SkillBonuses.GetBonus(2) > 0)
{
foreach (SkillName sk in Imbuing.PossibleSkills)
{
if (i.SkillBonuses.GetSkill(2) == sk)
return GetNameForAttribute(sk);
}
}
}
// SkillGroup4 replace SkillGroup4
if (mod >= 167 && mod <= 172)
{
if (i.SkillBonuses.GetBonus(3) > 0)
{
foreach (SkillName sk in Imbuing.PossibleSkills)
{
if (i.SkillBonuses.GetSkill(3) == sk)
return GetNameForAttribute(sk);
}
}
}
// SkillGroup5 replace SkillGroup5
if (mod >= 173 && mod <= 178)
{
if (i.SkillBonuses.GetBonus(4) > 0)
{
foreach (SkillName sk in Imbuing.PossibleSkills)
{
if (i.SkillBonuses.GetSkill(4) == sk)
return GetNameForAttribute(sk);
}
}
}
}
return -1;
}
public static int GetNameForAttribute(object attribute)
{
if(attribute is AosArmorAttribute && (AosArmorAttribute)attribute == AosArmorAttribute.LowerStatReq)
attribute = AosWeaponAttribute.LowerStatReq;
if (attribute is AosArmorAttribute && (AosArmorAttribute)attribute == AosArmorAttribute.DurabilityBonus)
attribute = AosWeaponAttribute.DurabilityBonus;
foreach (ImbuingDefinition def in Imbuing.Table.Values)
{
if (attribute is SlayerName && def.Attribute is SlayerName && (SlayerName)attribute == (SlayerName)def.Attribute)
return def.AttributeName;
if (attribute is AosAttribute && def.Attribute is AosAttribute && (AosAttribute)attribute == (AosAttribute)def.Attribute)
return def.AttributeName;
if (attribute is AosWeaponAttribute && def.Attribute is AosWeaponAttribute && (AosWeaponAttribute)attribute == (AosWeaponAttribute)def.Attribute)
return def.AttributeName;
if (attribute is SkillName && def.Attribute is SkillName && (SkillName)attribute == (SkillName)def.Attribute)
return def.AttributeName;
if (def.Attribute == attribute)
return def.AttributeName;
}
return -1;
}
}
} | ppardalj/ServUO | Scripts/Skills/Imbuing/Gumps/ImbuingC.cs | C# | gpl-2.0 | 22,477 |
"use strict"
var util = require('util')
var MessageEvent = require('./messageevent')
var Config = require('./config')
/**
* Coordinate the connection of a new chat client to the server.
* Different chat clients send the information differently, so far this chat server supports: TinTin++, mudjs, MudMaster, MudMaster 2k6, ZChat
*/
class Handshake {
/**
* Handshake constructor
* Constructs a new handshake object to process new connections to the chatserver
* @param {Socket} socket nodejs net socket object
* @param {Function} callback the callback that will be processed once the handshake has completed
* @todo Get the chatserver's name from some sort of preferences file
* @todo Get the chatserver's version from some sort of preferences file
*/
constructor(socket, callback) {
this.socket = socket
this.cb = callback
socket.on('data', data => {
var str = data.toString()
var nameAndIp = []
// check if our handshake data contains the expected :
if (str.indexOf(':') > -1) {
// set the connection's protocol information
this.setProtocol(str)
// send the chat name of the server to the client
this.setName('chatserver')
// send the version of the chatserver to the client
this.setVersion(`chatserver v${Config.version}`)
// setup the version response listener to get the client's version
this.socket.on('data', data => this.getVersion(data))
}
})
}
/**
* Set the protocol of the handshake
* @param {String} protocolStr colon and new line delimitered string of the handshake data
*/
setProtocol(protocolStr) {
// split the protocol string by the :
var result = protocolStr.split(':', 2)
// check the first part of the result to get the protocol
if (result[0] == 'CHAT') {
// MudMaster protocol
this.protocol = 'mudmaster'
} else if (result[0] == 'ZCHAT') {
// ZChat protocol
this.protocol = 'zchat'
} else {
// Unknown protocol
this.protocol = 'unknown'
}
// get the name and ip from the second part of the result
this.name = result[1].split('\n')[0]
this.ip = this.socket.remoteAddress
this.port = this.socket.remotePort
}
/**
* Send the chat servers name to the client
* @param {String} name the name of the chat server
*/
setName(name) {
this.socket.write(util.format('YES:%s\n', name))
}
/**
* Send the chat servers version to the client
* @param {String} version the version of the chatserver
*/
setVersion(version) {
// create the version as hex
var hexVersion = ""
for (var i = 0; i < version.length; i++) {
hexVersion += ''+version.charCodeAt(i).toString(16)
}
// send the version
MessageEvent.version(version).toSocket(this.socket).send()
}
/**
* Get the chat client's version
* @param {String} data the data received over the socket
*/
getVersion(data) {
if (data[0].toString(16) == MessageEvent.Type.VERSION) {
this.version = data.toString().substring(1, data.length - 2)
}
// remove all the listeners for 'data' on the socket as we don't want getVersion called over and over
this.socket.removeAllListeners('data')
// callback with self
this.cb(this)
}
}
module.exports = Handshake
| logikaljay/mudchat | core/handshake.js | JavaScript | gpl-2.0 | 3,704 |
SELECT Dimensions, sum(Trans) as Trans, sum(Trans_Percent) as Trans_Percent
FROM (
SELECT
buyers_race as Dimensions,
count(*) as Trans,
round((count(*) / (SELECT count(*) FROM (SELECT transaction_type,
CASE transaction_type
WHEN 'D' THEN 2 * count(*)
ELSE count(*)
END AS Sales
FROM c2s_checklist_master
WHERE paid_unpaid = 'P'
AND EXTRACT(YEAR FROM transaction_date) = 2016) T2 )) * 100), 1) as Trans_Percent
FROM c2s_checklist_master
WHERE paid_unpaid = 'P' AND transaction_type = 'B' AND EXTRACT(YEAR FROM transaction_date) = 2016
GROUP BY buyers_race
) T
GROUP BY Dimensions ORDER BY Dimensions
| iAssureIT/c2s | x.php | PHP | gpl-2.0 | 1,042 |
'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import UIDropdownComponent from './component';
let uiDropdown = function (element) {
ReactDOM.render(
React.createElement(
UIDropdownComponent,
{'message': element.getAttribute('data-message')}
),
element
);
};
export default uiDropdown; | roman901/Overheard | frontend/js/ui/dropdown/index.js | JavaScript | gpl-2.0 | 371 |
<?php
require realpath(__DIR__ . '/../vendor/autoload.php');
use Application\Structures;
use Application\Models;
date_default_timezone_set("US/Arizona");
?>
| Etrahkad/GameOfWar | tests/bootstrap.php | PHP | gpl-2.0 | 160 |
/* This file is part of the KDE project
Copyright (C) 2003 Lucijan Busch <lucijan@kde.org>
Copyright (C) 2003-2011 Jarosław Staniek <staniek@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "kexipartinfo_p.h"
#include "KexiMainWindowIface.h"
#include <kexidb/global.h>
#include <KActionCollection>
using namespace KexiPart;
Info::Private::Private(const KService::Ptr& aPtr)
: ptr(aPtr)
, instanceCaption(aPtr->name())
, groupName(aPtr->genericName())
// , mimeType(aPtr->property("X-Kexi-TypeMime").toString())
, itemIcon(aPtr->property("X-Kexi-ItemIcon", QVariant::String).toString())
, objectName(aPtr->property("X-Kexi-TypeName", QVariant::String).toString())
// , projectPartID( aPtr->property("X-Kexi-TypeId").toInt() )
, partClass(aPtr->property("X-Kexi-Class", QVariant::String).toString())
, broken(false)
, idStoredInPartDatabase(false)
{
bool dataView = true;
getBooleanProperty(aPtr, "X-Kexi-SupportsDataView", &dataView);
if (dataView) {
supportedViewModes |= Kexi::DataViewMode;
}
bool designView = true;
getBooleanProperty(aPtr, "X-Kexi-SupportsDesignView", &designView);
if (designView) {
supportedViewModes |= Kexi::DesignViewMode;
}
bool textView = false;
getBooleanProperty(aPtr, "X-Kexi-SupportsTextView", &textView);
if (textView) {
supportedViewModes |= Kexi::TextViewMode;
}
dataView = true;
getBooleanProperty(aPtr, "X-Kexi-SupportsDataViewInUserMode", &dataView);
if (dataView) {
supportedUserViewModes |= Kexi::DataViewMode;
}
designView = false;
getBooleanProperty(aPtr, "X-Kexi-SupportsDesignViewInUserMode", &designView);
if (designView) {
supportedUserViewModes |= Kexi::DesignViewMode;
}
textView = false;
getBooleanProperty(aPtr, "X-Kexi-SupportsTextViewInUserMode", &textView);
if (textView) {
supportedUserViewModes |= Kexi::TextViewMode;
}
isVisibleInNavigator = true;
getBooleanProperty(aPtr, "X-Kexi-NoObject", &isVisibleInNavigator);
isPropertyEditorAlwaysVisibleInDesignMode = true;
getBooleanProperty(aPtr, "X-Kexi-PropertyEditorAlwaysVisibleInDesignMode",
&isPropertyEditorAlwaysVisibleInDesignMode);
#if 0
if (projectPartID == 0) {
if (isVisibleInNavigator) {
kWarning() << "Could not found project part ID! (name: '" << objectName
<< "'). Possible problem with installation of the .desktop files for Kexi plugins";
isVisibleInNavigator = false;
}
projectPartID = -1;
}
#endif
}
Info::Private::Private()
#if 0 //moved as internal to KexiProject
: projectPartID(-1) //OK?
#endif
: broken(false)
, isVisibleInNavigator(false)
, idStoredInPartDatabase(false)
, isPropertyEditorAlwaysVisibleInDesignMode(false)
{
}
//------------------------------
KexiNewObjectAction::KexiNewObjectAction(Info* info, QObject *parent)
: KAction(KIcon(info->createItemIcon()), info->instanceCaption() + "...", parent)
, m_info(info)
{
setObjectName(KexiPart::nameForCreateAction(*m_info));
// default tooltip and what's this
setToolTip(i18n("Create new object of type \"%1\"",
m_info->instanceCaption().toLower()));
setWhatsThis(i18n("Creates new object of type \"%1\"",
m_info->instanceCaption().toLower()));
connect(this, SIGNAL(triggered()), this, SLOT(slotTriggered()));
connect(this, SIGNAL(newObjectRequested(KexiPart::Info*)),
&Kexi::partManager(), SIGNAL(newObjectRequested(KexiPart::Info*)));
}
void KexiNewObjectAction::slotTriggered()
{
emit newObjectRequested(m_info);
}
//------------------------------
Info::Info(KService::Ptr ptr)
: d(new Private(ptr))
{
if (KexiMainWindowIface::global()) {
KexiNewObjectAction *act = new KexiNewObjectAction(
this,
KexiMainWindowIface::global()->actionCollection());
if (KexiMainWindowIface::global()->actionCollection()) {
KexiMainWindowIface::global()->actionCollection()->addAction(act->objectName(), act);
}
}
}
Info::Info(const QString& partClass, const QString& itemIcon,
const QString& objectName)
: d(new Private)
{
d->partClass = partClass;
d->itemIcon = itemIcon;
d->objectName = objectName;
}
Info::~Info()
{
delete d;
}
QString Info::groupName() const
{
return d->groupName;
}
QString Info::instanceCaption() const
{
return d->instanceCaption;
}
QString Info::partClass() const
{
return d->partClass;
}
QString Info::itemIcon() const
{
return d->itemIcon;
}
QString Info::createItemIcon() const
{
return d->itemIcon + "_newobj";
}
QString Info::objectName() const
{
return d->objectName;
}
Kexi::ViewModes Info::supportedViewModes() const
{
return d->supportedViewModes;
}
Kexi::ViewModes Info::supportedUserViewModes() const
{
return d->supportedUserViewModes;
}
KService::Ptr Info::ptr() const
{
return d->ptr;
}
bool Info::isBroken() const
{
return d->broken;
}
bool Info::isVisibleInNavigator() const
{
return d->isVisibleInNavigator;
}
#if 0 //moved as internal to KexiProject
int Info::projectPartID() const
{
return d->projectPartID;
}
void Info::setProjectPartID(int id)
{
d->projectPartID = id;
}
#endif
void Info::setBroken(bool broken, const QString& errorMessage)
{
d->broken = broken; d->errorMessage = errorMessage;
}
QString Info::errorMessage() const
{
return d->errorMessage;
}
void Info::setIdStoredInPartDatabase(bool set)
{
d->idStoredInPartDatabase = set;
}
bool Info::isIdStoredInPartDatabase() const
{
return d->idStoredInPartDatabase;
}
bool Info::isDataExportSupported() const
{
QVariant val = d->ptr ? d->ptr->property("X-Kexi-SupportsDataExport") : QVariant();
return val.isValid() ? val.toBool() : false;
}
bool Info::isPrintingSupported() const
{
QVariant val = d->ptr ? d->ptr->property("X-Kexi-SupportsPrinting") : QVariant();
return val.isValid() ? val.toBool() : false;
}
bool Info::isExecuteSupported() const
{
QVariant val = d->ptr ? d->ptr->property("X-Kexi-SupportsExecution") : QVariant();
return val.isValid() ? val.toBool() : false;
}
bool Info::isPropertyEditorAlwaysVisibleInDesignMode() const
{
return d->isPropertyEditorAlwaysVisibleInDesignMode;
}
//--------------
QString KexiPart::nameForCreateAction(const Info& info)
{
return info.objectName() + "part_create";
}
#include "kexipartinfo_p.moc"
| wyuka/calligra | kexi/core/kexipartinfo.cpp | C++ | gpl-2.0 | 7,461 |
#include "cacic_software.h"
cacic_software::cacic_software()
{
}
void cacic_software::iniciaColeta()
{
#ifdef Q_OS_WIN
this->coletaSoftware = coletaWin();
#elif defined(Q_OS_LINUX)
this->coletaSoftware = coletaLinux();
#endif
}
#if defined(Q_OS_WIN)
/***************************************************************
* Realiza a coleta de softwares do Windows por meio do regedit.
***************************************************************/
using namespace voidrealms::win32;
QJsonObject cacic_software::coletaWin()
{
QJsonObject softwaresJson;
QStringList regedit;
//No windows, ele armazena os dados em 2 locais diferentes se for x64. Um para programas x86 e outro pra x64.
regedit.append("SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\");
regedit.append("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\");
foreach(QString registry, regedit){
VRegistry reg;
reg.OpenKey(HKEY_LOCAL_MACHINE, registry);
QStringList keys = reg.enum_Keys();
qDebug() << _exceptions;
foreach(QString key, keys){
if(!_exceptions.contains(key) ||
(_exceptions.contains(key) && !_exceptions[key].isEmpty())){
QVariantMap software;
VRegistry subReg;
subReg.OpenKey(HKEY_LOCAL_MACHINE, registry + key);
if (!subReg.get_REG_SZ("DisplayName").isEmpty())
software["description"] = subReg.get_REG_SZ("DisplayName");
if (!subReg.get_REG_SZ("Publisher").isEmpty())
software["publisher"] = subReg.get_REG_SZ("Publisher");
if (!subReg.get_REG_SZ("InstallLocation").isEmpty())
software["installLocation"] = subReg.get_REG_SZ("InstallLocation");
if (!subReg.get_REG_SZ("InstallDate").isEmpty())
software["installDate"] = subReg.get_REG_SZ("InstallDate");
if (!subReg.get_REG_SZ("URLInfoAbout").isEmpty())
software["url"] = subReg.get_REG_SZ("URLInfoAbout");
if (!subReg.get_REG_EXPAND_SZ("UninstallString").isEmpty())
software["uninstallString"] = subReg.get_REG_EXPAND_SZ("UninstallString");
if (!subReg.get_REG_EXPAND_SZ("QuietUninstallString").isEmpty())
software["quietUninstallString"] = subReg.get_REG_EXPAND_SZ("QuietUninstallString");
if (!subReg.get_REG_SZ("DisplayVersion").isEmpty())
software["version"] = subReg.get_REG_SZ("DisplayVersion");
software["name"] = key;
if(_exceptions.contains(key)){
foreach(QString value, _exceptions[key]){
qDebug() << value;
software.remove(value);
}
}
softwaresJson[key] = QJsonObject::fromVariantMap(software);
}
}
}
return softwaresJson;
}
#elif defined(Q_OS_LINUX)
QJsonObject cacic_software::coletaLinux()
{
OperatingSystem operatingSystem;
if( operatingSystem.getIdOs() == OperatingSystem::LINUX_ARCH ) {
return coletaArch();
} else /*if ( operatingSystem.getIdOs() == OperatingSystem::LINUX_DEBIAN ||
operatingSystem.getIdOs() == OperatingSystem::LINUX_UBUNTU )*/ {
return coletaDebian();
}
return QJsonObject();
}
QJsonObject cacic_software::coletaArch()
{
ConsoleObject console;
QJsonObject softwaresJson;
QStringList packages = console("pacman -Qe").split("\n");
foreach(QString package, packages) {
QString packageName = package.split(" ")[0];
if (!(packageName.isEmpty() || packageName.isNull()) &&
(!_exceptions.contains(packageName)
|| !(_exceptions.contains(packageName)
&& _exceptions[packageName].isEmpty()))){
QJsonObject packageJson;
QStringList packageInfo = console(QString("pacman -Qi ").append(packageName)).split("\n");
packageJson["name"] = QJsonValue::fromVariant(QString(packageName));
foreach(QString line, packageInfo) {
if(line.contains("Version") &&
!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("version")))
packageJson["version"] = line.split(":")[1].mid(1);
if(line.contains("Description") &&
!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("description")))
packageJson["description"] = line.split(":")[1].mid(1);
if(line.contains("URL")) {
QStringList url = line.split(":");
QString urlString;
for(int i = 1 ; i < url.size() ; ++i){
urlString.append(url[i]);
if(i == 1 ) urlString.append(":");
}
if(!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("url")))
packageJson["url"] = urlString.mid(1);
if (!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("publisher")))
packageJson["publisher"] = urlString.mid(1);
}
// installSize não existe na coleta do Windows.
// if(line.contains("Installed size"))
// packageJson["installSize"] = line.split(":")[1].mid(1);
if(line.contains("Install Date") &&
!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("installDate")))
packageJson["installDate"] = line.split(":")[1].mid(1);
}
if (!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("installLocation"))) {
QString location = console(QString("whereis ").append(packageName)).split("\n").at(0);
if(!location.split(":").at(1).isEmpty()) {
location = location.split(":").at(1).mid(1);
packageJson["installLocation"] = location;
}
}
softwaresJson[packageName] = packageJson;
}
}
return softwaresJson;
}
QJsonObject cacic_software::coletaDebian()
{
ConsoleObject console;
QJsonObject softwaresJson;
QStringList packages = console("dpkg --get-selections | grep -v '\^lib\\|\^fonts'").split("\n");
foreach(QString package, packages) {
QString packageName = package.split("\t")[0];
if (!(packageName.isEmpty() || packageName.isNull()) &&
(!_exceptions.contains(packageName)
|| !(_exceptions.contains(packageName)
&& _exceptions[packageName].isEmpty()))){
QJsonObject packageJson;
QStringList packageInfo = console(QString("apt-cache show ").append(packageName)).split("\n");
packageJson["name"] = QJsonValue::fromVariant(QString(packageName));
foreach(QString line, packageInfo) {
if(line.contains("Version:") &&
!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("version")))
packageJson["version"] = line.split(":")[1].mid(1);
if(line.contains("Description-en:") &&
!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("description"))){
packageJson["description"] = line.split(":")[1].mid(1);
}
if(line.contains("Homepage:")) {
QStringList url = line.split(":");
QString urlString;
for(int i = 1 ; i < url.size() ; ++i){
urlString.append(url[i]);
if(i == 1 ) urlString.append(":");
}
if (!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("url")))
packageJson["url"] = urlString.mid(1);
if (!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("publisher")))
packageJson["publisher"] = urlString.mid(1);
}
// installSize não existe na coleta do Windows.
// if(line.contains("Installed-Size:"))
// packageJson["installSize"] = line.split(":")[1].mid(1);
}
if (!packageName.isEmpty() &&
!(_exceptions.contains(packageName)
&& _exceptions[packageName].contains("installLocation"))){
QString treatedPackageName = packageName;
if(treatedPackageName.contains("amd64") || treatedPackageName.contains("i386"))
treatedPackageName = treatedPackageName.split(":").at(0);
QString location = console(QString("whereis ").append(treatedPackageName)).split("\n").at(0);
if(!location.split(":").at(1).isEmpty()) {
location = location.split(":").at(1).mid(1);
packageJson["installLocation"] = location;
}
}
softwaresJson[packageName] = packageJson;
}
// int counterPackages = softwaresJson.size();
}
return softwaresJson;
}
#endif
QHash<QString, QStringList> cacic_software::exceptions() const
{
return _exceptions;
}
void cacic_software::setExceptionClasses(const QHash<QString, QStringList> &exceptions)
{
_exceptions = exceptions;
}
QJsonObject cacic_software::toJsonObject()
{
return coletaSoftware;
}
| lightbase/cacic-agente | src/cacic_software.cpp | C++ | gpl-2.0 | 10,006 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("QualificationB")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("QualificationB")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("19a1a09d-9a9e-4968-ac5d-8e2cc7a445fc")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| marcoschoma/programmingchallenges | CodeJam2017/QualificationB/Properties/AssemblyInfo.cs | C# | gpl-2.0 | 1,399 |
<?php
/**
* File containing the RelationList FieldType Value class
*
* @copyright Copyright (C) 1999-2013 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
* @version //autogentag//
*/
namespace eZ\Publish\Core\FieldType\RelationList;
use eZ\Publish\Core\FieldType\Value as BaseValue;
/**
* Value for RelationList field type
*/
class Value extends BaseValue
{
/**
* Related content id's
*
* @var mixed[]
*/
public $destinationContentIds;
/**
* Construct a new Value object and initialize it $text
*
* @param mixed[] $destinationContentIds
*/
public function __construct( array $destinationContentIds = array() )
{
$this->destinationContentIds = $destinationContentIds;
}
/**
* @see \eZ\Publish\Core\FieldType\Value
*/
public function __toString()
{
return implode( ',', $this->destinationContentIds );
}
}
| gbentley/ezpublish-kernel | eZ/Publish/Core/FieldType/RelationList/Value.php | PHP | gpl-2.0 | 992 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Workout.Models
{
public partial class WorkoutUserControl : System.Web.UI.UserControl
{
public Workout.Models.Context WorkoutContext
{
get
{
Workout.Models.Context context = (this.Page as WorkoutPage).WorkoutContext;
if(context == null)
{
throw new ApplicationException("Unable to retrieve parent page's WorkoutContext from user control.");
}
return context;
}
}
}
} | mattkgross/WorkoutLogger | Workout/Models/WorkoutUserControl.cs | C# | gpl-2.0 | 638 |
/**
* \file GuiSpellchecker.cpp
* This file is part of LyX, the document processor.
* Licence details can be found in the file COPYING.
*
* \author John Levon
* \author Edwin Leuven
* \author Abdelrazak Younes
*
* Full author contact details are available in file CREDITS.
*/
#include <config.h>
#include "GuiSpellchecker.h"
#include "GuiApplication.h"
#include "qt_helpers.h"
#include "ui_SpellcheckerUi.h"
#include "Buffer.h"
#include "BufferParams.h"
#include "BufferView.h"
#include "buffer_funcs.h"
#include "Cursor.h"
#include "Text.h"
#include "CutAndPaste.h"
#include "FuncRequest.h"
#include "Language.h"
#include "LyX.h"
#include "LyXRC.h"
#include "lyxfind.h"
#include "Paragraph.h"
#include "WordLangTuple.h"
#include "support/debug.h"
#include "support/docstring.h"
#include "support/docstring_list.h"
#include "support/ExceptionMessage.h"
#include "support/gettext.h"
#include "support/lstrings.h"
#include "support/textutils.h"
#include <QKeyEvent>
#include <QListWidgetItem>
#include <QMessageBox>
#include "SpellChecker.h"
#include "frontends/alert.h"
using namespace std;
using namespace lyx::support;
namespace lyx {
namespace frontend {
struct SpellcheckerWidget::Private
{
Private(SpellcheckerWidget * parent, DockView * dv)
: p(parent), dv_(dv), incheck_(false), wrap_around_(false) {}
/// update from controller
void updateSuggestions(docstring_list & words);
/// move to next position after current word
void forward();
/// check text until next misspelled/unknown word
void check();
///
bool continueFromBeginning();
///
void setLanguage(Language const * lang);
/// test and set guard flag
bool inCheck() {
if (incheck_)
return true;
incheck_ = true;
return false;
}
void canCheck() { incheck_ = false; }
/// check for wrap around of current position
bool isWrapAround(DocIterator cursor) const;
///
Ui::SpellcheckerUi ui;
///
SpellcheckerWidget * p;
///
GuiView * gv_;
///
DockView * dv_;
/// current word being checked and lang code
WordLangTuple word_;
///
DocIterator start_;
///
bool incheck_;
///
bool wrap_around_;
};
SpellcheckerWidget::SpellcheckerWidget(GuiView * gv, DockView * dv, QWidget * parent)
: QTabWidget(parent), d(new Private(this, dv))
{
d->ui.setupUi(this);
d->gv_ = gv;
connect(d->ui.suggestionsLW, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
this, SLOT(on_replacePB_clicked()));
// language
QAbstractItemModel * language_model = guiApp->languageModel();
// FIXME: it would be nice if sorting was enabled/disabled via a checkbox.
language_model->sort(0);
d->ui.languageCO->setModel(language_model);
d->ui.languageCO->setModelColumn(1);
d->ui.wordED->setReadOnly(true);
d->ui.suggestionsLW->installEventFilter(this);
}
SpellcheckerWidget::~SpellcheckerWidget()
{
delete d;
}
bool SpellcheckerWidget::eventFilter(QObject *obj, QEvent *event)
{
if (obj == d->ui.suggestionsLW && event->type() == QEvent::KeyPress) {
QKeyEvent *e = static_cast<QKeyEvent *> (event);
if (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return) {
if (d->ui.suggestionsLW->currentItem()) {
on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
on_replacePB_clicked();
}
return true;
} else if (e->key() == Qt::Key_Right) {
if (d->ui.suggestionsLW->currentItem())
on_suggestionsLW_itemClicked(d->ui.suggestionsLW->currentItem());
return true;
}
}
// standard event processing
return QWidget::eventFilter(obj, event);
}
void SpellcheckerWidget::on_suggestionsLW_itemClicked(QListWidgetItem * item)
{
if (d->ui.replaceCO->count() != 0)
d->ui.replaceCO->setItemText(0, item->text());
else
d->ui.replaceCO->addItem(item->text());
d->ui.replaceCO->setCurrentIndex(0);
}
void SpellcheckerWidget::on_replaceCO_highlighted(const QString & str)
{
QListWidget * lw = d->ui.suggestionsLW;
if (lw->currentItem() && lw->currentItem()->text() == str)
return;
for (int i = 0; i != lw->count(); ++i) {
if (lw->item(i)->text() == str) {
lw->setCurrentRow(i);
break;
}
}
}
void SpellcheckerWidget::updateView()
{
BufferView * bv = d->gv_->documentBufferView();
setEnabled(bv != 0);
if (bv && hasFocus() && d->start_.empty()) {
d->start_ = bv->cursor();
d->check();
}
}
bool SpellcheckerWidget::Private::continueFromBeginning()
{
QMessageBox::StandardButton const answer = QMessageBox::question(p,
qt_("Spell Checker"),
qt_("We reached the end of the document, would you like to "
"continue from the beginning?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
if (answer == QMessageBox::No) {
dv_->hide();
return false;
}
dispatch(FuncRequest(LFUN_BUFFER_BEGIN));
wrap_around_ = true;
return true;
}
bool SpellcheckerWidget::Private::isWrapAround(DocIterator cursor) const
{
return wrap_around_ && start_.buffer() == cursor.buffer() && start_ < cursor;
}
void SpellcheckerWidget::Private::forward()
{
BufferView * bv = gv_->documentBufferView();
DocIterator from = bv->cursor();
dispatch(FuncRequest(LFUN_ESCAPE));
dispatch(FuncRequest(LFUN_CHAR_FORWARD));
if (bv->cursor().depth() <= 1 && bv->cursor().atLastPos()) {
continueFromBeginning();
return;
}
if (from == bv->cursor()) {
//FIXME we must be at the end of a cell
dispatch(FuncRequest(LFUN_CHAR_FORWARD));
}
if (isWrapAround(bv->cursor())) {
dv_->hide();
}
}
void SpellcheckerWidget::on_languageCO_activated(int index)
{
string const lang =
fromqstr(d->ui.languageCO->itemData(index).toString());
if (!d->word_.lang() || d->word_.lang()->lang() == lang)
// nothing changed
return;
dispatch(FuncRequest(LFUN_LANGUAGE, lang));
d->check();
}
bool SpellcheckerWidget::initialiseParams(std::string const &)
{
BufferView * bv = d->gv_->documentBufferView();
if (bv == 0)
return false;
std::set<Language const *> languages =
bv->buffer().masterBuffer()->getLanguages();
if (!languages.empty())
d->setLanguage(*languages.begin());
d->start_ = DocIterator();
d->wrap_around_ = false;
d->incheck_ = false;
return true;
}
void SpellcheckerWidget::on_ignoreAllPB_clicked()
{
/// ignore all occurrences of word
if (d->inCheck())
return;
LYXERR(Debug::GUI, "Spellchecker: ignore all button");
if (d->word_.lang() && !d->word_.word().empty())
theSpellChecker()->accept(d->word_);
d->forward();
d->check();
d->canCheck();
}
void SpellcheckerWidget::on_addPB_clicked()
{
/// insert word in personal dictionary
if (d->inCheck())
return;
LYXERR(Debug::GUI, "Spellchecker: add word button");
theSpellChecker()->insert(d->word_);
d->forward();
d->check();
d->canCheck();
}
void SpellcheckerWidget::on_ignorePB_clicked()
{
/// ignore this occurrence of word
if (d->inCheck())
return;
LYXERR(Debug::GUI, "Spellchecker: ignore button");
d->forward();
d->check();
d->canCheck();
}
void SpellcheckerWidget::on_findNextPB_clicked()
{
if (d->inCheck())
return;
docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
docstring const datastring = find2string(textfield,
true, true, true);
LYXERR(Debug::GUI, "Spellchecker: find next (" << textfield << ")");
dispatch(FuncRequest(LFUN_WORD_FIND, datastring));
d->canCheck();
}
void SpellcheckerWidget::on_replacePB_clicked()
{
if (d->inCheck())
return;
docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
docstring const datastring = replace2string(replacement, textfield,
true, true, false, false);
LYXERR(Debug::GUI, "Replace (" << replacement << ")");
dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
d->forward();
d->check();
d->canCheck();
}
void SpellcheckerWidget::on_replaceAllPB_clicked()
{
if (d->inCheck())
return;
docstring const textfield = qstring_to_ucs4(d->ui.wordED->text());
docstring const replacement = qstring_to_ucs4(d->ui.replaceCO->currentText());
docstring const datastring = replace2string(replacement, textfield,
true, true, true, true);
LYXERR(Debug::GUI, "Replace all (" << replacement << ")");
dispatch(FuncRequest(LFUN_WORD_REPLACE, datastring));
d->forward();
d->check(); // continue spellchecking
d->canCheck();
}
void SpellcheckerWidget::Private::updateSuggestions(docstring_list & words)
{
QString const suggestion = toqstr(word_.word());
ui.wordED->setText(suggestion);
QListWidget * lw = ui.suggestionsLW;
lw->clear();
if (words.empty()) {
p->on_suggestionsLW_itemClicked(new QListWidgetItem(suggestion));
return;
}
for (size_t i = 0; i != words.size(); ++i)
lw->addItem(toqstr(words[i]));
p->on_suggestionsLW_itemClicked(lw->item(0));
lw->setCurrentRow(0);
}
void SpellcheckerWidget::Private::setLanguage(Language const * lang)
{
int const pos = ui.languageCO->findData(toqstr(lang->lang()));
if (pos != -1)
ui.languageCO->setCurrentIndex(pos);
}
void SpellcheckerWidget::Private::check()
{
BufferView * bv = gv_->documentBufferView();
if (!bv || bv->buffer().text().empty())
return;
DocIterator from = bv->cursor();
DocIterator to;
WordLangTuple word_lang;
docstring_list suggestions;
LYXERR(Debug::GUI, "Spellchecker: start check at " << from);
int progress;
try {
progress = bv->buffer().spellCheck(from, to, word_lang, suggestions);
} catch (ExceptionMessage const & message) {
if (message.type_ == WarningException) {
Alert::warning(message.title_, message.details_);
return;
}
throw message;
}
// end of document
if (from == doc_iterator_end(&bv->buffer())) {
if (wrap_around_ || start_ == doc_iterator_begin(&bv->buffer())) {
dv_->hide();
return;
}
if (continueFromBeginning())
check();
return;
}
if (isWrapAround(from)) {
dv_->hide();
return;
}
word_ = word_lang;
// set suggestions
updateSuggestions(suggestions);
// set language
setLanguage(word_lang.lang());
// FIXME LFUN
// If we used a LFUN, dispatch would do all of this for us
int const size = to.pos() - from.pos();
bv->putSelectionAt(from, size, false);
bv->processUpdateFlags(Update::Force | Update::FitCursor);
}
GuiSpellchecker::GuiSpellchecker(GuiView & parent,
Qt::DockWidgetArea area, Qt::WindowFlags flags)
: DockView(parent, "spellchecker", qt_("Spellchecker"),
area, flags)
{
widget_ = new SpellcheckerWidget(&parent, this);
setWidget(widget_);
setFocusProxy(widget_);
}
GuiSpellchecker::~GuiSpellchecker()
{
setFocusProxy(0);
delete widget_;
}
void GuiSpellchecker::updateView()
{
widget_->updateView();
}
Dialog * createGuiSpellchecker(GuiView & lv)
{
GuiSpellchecker * gui = new GuiSpellchecker(lv, Qt::RightDockWidgetArea);
#ifdef Q_WS_MACX
gui->setFloating(true);
#endif
return gui;
}
} // namespace frontend
} // namespace lyx
#include "moc_GuiSpellchecker.cpp"
| rpavlik/lyx-lucid-backport | src/frontends/qt4/GuiSpellchecker.cpp | C++ | gpl-2.0 | 10,750 |
/**
* @copyright 2009-2019 Vanilla Forums Inc.
* @license GPL-2.0-only
*/
import { styleFactory } from "@library/styles/styleUtils";
import { useThemeCache } from "@library/styles/themeCache";
import { flexHelper } from "@library/styles/styleHelpers";
import { px } from "csx";
export const embedErrorClasses = useThemeCache(() => {
const style = styleFactory("embedError");
const renderErrorRoot = style("renderErrorRoot", {
display: "block",
textAlign: "left",
});
const renderErrorIconLink = style("renderErrorIconLink", {
paddingLeft: px(4),
verticalAlign: "middle",
});
return { renderErrorRoot, renderErrorIconLink };
});
| vanilla/vanilla | library/src/scripts/embeddedContent/components/embedErrorStyles.ts | TypeScript | gpl-2.0 | 691 |
<?php
/*
Template Name: Startups Page
*/
?>
<?php get_header('page'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<!--<div id="newsletter-btn"></div>-->
<div class="post pageTemplet startap-pageTemplet" id="post-<?php the_ID(); ?>">
<!--<h2><php the_title();?></h2>-->
<?php //include (TEMPLATEPATH . '/inc/meta.php' ); ?>
<div class="entry">
<?php include(locate_template('areasTemplates/startups.php'));?>
<?php //wp_link_pages(array('before' => 'Pages: ', 'next_or_number' => 'number')); ?>
</div>
<?php //edit_post_link('Edit this entry.', '<p>', '</p>'); ?>
</div>
<?php // comments_template(); ?>
<?php endwhile; endif; ?>
<?php //get_sidebar(); ?>
<?php get_footer('page'); ?> | DavidSalzer/Mindcet-startups-site | wp-content/themes/mindcet-Theme/startupsPage.php | PHP | gpl-2.0 | 786 |
/*
* Copyright (c) 2014. Licensed under GPL-2. See license.txt in project folder.
*/
package de._0x29.xkpasswd;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by christian on 1/26/14.
*/
public class PasswordFactory {
private int mAmount = 4;
private int mMaxWordLength = 8;
private int mMinWordLength = 5;
private String mDelimiter = " ";
private int mDigitsBefore = 0;
private int mDigitsAfter = 0;
public PasswordFactory setNumberOfWords(int amount) {
mAmount = amount;
return this;
}
public PasswordFactory setMinimumWordLength(int min) {
mMinWordLength = min;
return this;
}
public PasswordFactory setMaximumWordLength(int max) {
mMaxWordLength = max;
return this;
}
public PasswordFactory setWordDelimiter(String delimiter) {
mDelimiter = delimiter;
return this;
}
public PasswordFactory setDigitsBeforePassphrase(int digitsBefore) {
mDigitsBefore = digitsBefore;
return this;
}
public PasswordFactory setDigitsAfterPassphrase(int digitsAfter) {
mDigitsAfter = digitsAfter;
return this;
}
public String create() {
ArrayList<String> availableWords = new ArrayList<String>();
SecureRandom secureRandom = new SecureRandom();
StringBuffer buffer = new StringBuffer();
try {
Dictionary dictionary = new Dictionary();
HashMap<Integer, ArrayList<String>> words = dictionary.getWords();
for (Integer wordLength : words.keySet()) {
if (wordLength <= mMaxWordLength && wordLength >= mMinWordLength) {
availableWords.addAll(words.get(wordLength));
}
}
for (int i = 0; i < mAmount; i++) {
int randomIndex = secureRandom.nextInt(availableWords.size());
String s = availableWords.get(randomIndex);
buffer.append(s);
availableWords.remove(randomIndex);
if ((i + 1) < mAmount) {
buffer.append(mDelimiter);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return buffer.toString();
}
}
| methical/xkpasswd-lib | src/main/java/de/_0x29/xkpasswd/PasswordFactory.java | Java | gpl-2.0 | 2,376 |
package e.scm;
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.regex.*;
import e.util.*;
public class Patch {
private ArrayList<String> lines;
private ArrayList<String> errors;
private LineMapper lineMapper;
public static final class HunkRange {
/**
* Matches the "@@ -111,41 +113,41 @@" lines at the start of a hunk.
* We allow anything after the trailing "@@" because that gap is used for annotations, both by our annotate-patch.rb script and by "diff -p".
* GNU Diff's "print_unidiff_number_range" has a special case when outputting a,b where if a and b are equal, only a is output.
*/
private static final Pattern AT_AT_PATTERN = Pattern.compile("^@@ -(\\d+)(,\\d+)? \\+(\\d+)(,\\d+)? @@(.*)$");
private boolean matches;
// "from" is the first comma-separated pair. "to" is the second comma-separated pair.
// "begin" is the first number in each pair. "end" is the second number in each pair.
private int fromBegin;
private int fromEnd;
private int toBegin;
private int toEnd;
public HunkRange(String atAtLine) {
Matcher matcher = AT_AT_PATTERN.matcher(atAtLine);
matches = matcher.matches();
if (matches) {
fromBegin = parseInt(matcher.group(1), 0);
fromEnd = parseInt(matcher.group(2), fromBegin);
toBegin = parseInt(matcher.group(3), 0);
toEnd = parseInt(matcher.group(4), toBegin);
}
}
private int parseInt(String value, int fallback) {
if (value == null) {
return fallback;
}
if (value.startsWith(",")) {
value = value.substring(1);
}
int result = Integer.parseInt(value);
return result;
}
public boolean matches() {
return matches;
}
public int fromBegin() {
return fromBegin;
}
public int toBegin() {
return toBegin;
}
}
private interface PatchLineParser {
public void parseHunkHeader(int fromBegin, int toBegin);
public void parseFromLine(String sourceLine);
public void parseToLine(String sourceLine);
public void parseContextLine(String sourceLine);
}
private void parsePatch(boolean isPatchReversed, PatchLineParser patchLineParser) {
String fromPrefix = isPatchReversed ? "+" : "-";
String toPrefix = isPatchReversed ? "-" : "+";
for (int lineNumberWithinPatch = 0; lineNumberWithinPatch < lines.size(); ++lineNumberWithinPatch) {
String patchLine = lines.get(lineNumberWithinPatch);
if (patchLine.startsWith("@@")) {
HunkRange hunkRange = new HunkRange(patchLine);
if (isPatchReversed) {
patchLineParser.parseHunkHeader(hunkRange.toBegin(), hunkRange.fromBegin());
} else {
patchLineParser.parseHunkHeader(hunkRange.fromBegin(), hunkRange.toBegin());
}
} else if (patchLine.length() > 0) {
String sourceLine = patchLine.substring(1);
if (patchLine.startsWith(fromPrefix)) {
patchLineParser.parseFromLine(sourceLine);
} else if (patchLine.startsWith(toPrefix)) {
patchLineParser.parseToLine(sourceLine);
} else if (patchLine.startsWith(" ")) {
patchLineParser.parseContextLine(sourceLine);
} else if (patchLine.startsWith("=====") || patchLine.startsWith("Index: ") || patchLine.startsWith("RCS file: ") || patchLine.startsWith("retrieving revision ") || patchLine.startsWith("diff ") || patchLine.startsWith("new mode ") || patchLine.startsWith("old mode ") || patchLine.startsWith("index ") || patchLine.startsWith("\\ No newline at end of file")) {
// Ignore lines like this for the minute:
// bk:
// ===== makerules/vars-not-previously-included.make 1.33 vs 1.104 =====
// Index: src/e/scm/RevisionWindow.java
// svn:
// ===================================================================
// cvs:
// RCS file: /home/repositories/cvsroot/edit/src/e/edit/InsertNewlineAction.java,v
// retrieving revision 1.7
// diff -u -r1.7 -r1.9
} else {
// throw new RuntimeException("Malformed patch line \"" + patchLine + "\"");
}
}
}
}
public Patch(RevisionControlSystem backEnd, String filePath, Revision olderRevision, Revision newerRevision, boolean isPatchReversed, boolean ignoreWhiteSpace) {
Path directory = backEnd.getRoot();
String[] command = backEnd.getDifferencesCommand(olderRevision, newerRevision, filePath, ignoreWhiteSpace);
this.lines = new ArrayList<String>();
this.errors = new ArrayList<String>();
ProcessUtilities.backQuote(directory, command, lines, errors);
// CVS returns the number of differences as the status or some such idiocy.
if (errors.size() > 0) {
lines.addAll(errors);
}
initLineMapper(isPatchReversed);
}
private void initLineMapper(boolean isPatchReversed) {
lineMapper = new LineMapper();
parsePatch(isPatchReversed, new PatchLineParser() {
private int fromLine = 0;
private int toLine = 0;
public void parseHunkHeader(int fromBegin, int toBegin) {
fromLine = fromBegin;
toLine = toBegin;
}
public void parseFromLine(String sourceLine) {
++fromLine;
}
public void parseToLine(String sourceLine) {
++toLine;
}
public void parseContextLine(String sourceLine) {
lineMapper.addMapping(fromLine, toLine);
// Context lines count for both revisions.
++fromLine;
++toLine;
}
});
}
public int translateLineNumberInFromRevision(int fromLineNumber) {
return lineMapper.translate(fromLineNumber);
}
public ArrayList<String> getPatchLines() {
ArrayList<String> result = new ArrayList<>();
result.addAll(lines);
return result;
}
}
| software-jessies-org/scm | src/e/scm/Patch.java | Java | gpl-2.0 | 6,750 |
<?php
/**
* @version $Id: helper.php 8379 2007-08-10 23:20:01Z eddieajau $
* @package Joomla
* @copyright Copyright (C) 2005 - 2007 Open Source Matters. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
* Camp26.com
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
// Include the syndicate functions only once
require_once( dirname(__FILE__).DS.'helper.php' );
$document =& JFactory::getDocument();
$map['id'] = $params->get('id',0);
$map['plugin'] = $params->get('plugin',0);
$map['type'] = $params->get('typedisplay', 'js');
$map['width'] = $params->get('width',1000);
$map['height'] = $params->get('height',500);
$map['version'] = $params->get('version',8);
$map['background'] = $params->get('background','#000000');
$map['path'] = $params->get('path','components/com_yos_ammap/ammap');
$map['data_file'] = $params->get('data_file','ammap_data.xml');
$map['settings_file'] = $params->get('settings_file','ammap_settings.xml');
$map['preloader_color'] = $params->get('preloader_color','#999999');
$map['loading_data'] = $params->get('loading_data','Loading data');
$map['loading_settings'] = $params->get('loading_settings','Loading settings');
if (!$map['id']) {
$document->addScript($map['path'].'/swfobject.js');
} else {
$document->addScript('components/com_yos_ammap/ammap/swfobject.js');
}
JHTML::_('behavior.mootools');
switch ($map['type']){
case 'js':
$script = modAmmapHelper::getMap_swfobject($map);
break;
case 'fl':
default:
$script = modAmmapHelper::getMap_flash($map);
break;
}
require(JModuleHelper::getLayoutPath('mod_yos_ammap'));
?> | lycoben/veneflights | modules/mod_yos_ammap/mod_yos_ammap.php | PHP | gpl-2.0 | 2,016 |
package model.xmlparser.xmlview.mainmenudata;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import java.util.List;
@Root(name = "data")
public class MainMenuData {
@ElementList(inline = true, name = "Submenu")
List<Submenu> submenus;
public List<Submenu> getSubmenus() {
return submenus;
}
public void setSubmenus(List<Submenu> submenus) {
this.submenus = submenus;
}
}
| indiyskiy/WorldOnline | src/model/xmlparser/xmlview/mainmenudata/MainMenuData.java | Java | gpl-2.0 | 450 |
package com.sandlex.run2gather.runkeeper.model.types;
import com.google.gson.annotations.SerializedName;
/**
* author: Alexey Peskov
*/
public enum ActivityType {
RUNNING("Running"),
CYCLING("Cycling"),
MOUNTAIN_BIKING("Mountain Biking"),
WALKING("Walking"),
HIKING("Hiking"),
DOWNHILL_SKIING("Downhill Skiing"),
CROSS_COUNTRY_SKIING("Cross-Country Skiing"),
SNOWBOARDING("Snowboarding"),
SKATING("Skating"),
SWIMMING("Swimming"),
WHEELCHAIR("Wheelchair"),
ROWING("Rowing"),
ELLIPTICAL("Elliptical"),
OTHER("Other");
@SerializedName("type")
private final String code;
ActivityType(String code) {
this.code = code;
}
@Override
public String toString() {
return code;
}
public static ActivityType fromValue(String code) {
for (ActivityType type : ActivityType.values()) {
if (type.code.equals(code)) {
return type;
}
}
throw new IllegalArgumentException("Invalid ActivityType code: " + code);
}
}
| sandlex/run2gather | src/main/java/com/sandlex/run2gather/runkeeper/model/types/ActivityType.java | Java | gpl-2.0 | 1,076 |
package ojvm.loading.instructions;
import ojvm.data.JavaException;
import ojvm.operations.InstructionVisitor;
import ojvm.util.RuntimeConstants;
/**
* The encapsulation of a lreturn instruction.
* @author Amr Sabry
* @version jdk-1.1
*/
public class Ins_lreturn extends Instruction {
public Ins_lreturn (InstructionInputStream classFile) {
super(RuntimeConstants.opc_lreturn);
}
public void accept (InstructionVisitor iv) throws JavaException {
iv.visit_lreturn (this);
}
public String toString () {
return opcodeName;
}
}
| adum/bitbath | hackjvm/src/ojvm/loading/instructions/Ins_lreturn.java | Java | gpl-2.0 | 585 |
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
/*
* @(#)SharedInputStream.java 1.5 07/05/04
*/
package javax.mail.internet;
import java.io.*;
/**
* An InputStream that is backed by data that can be shared by multiple
* readers may implement this interface. This allows users of such an
* InputStream to determine the current position in the InputStream, and
* to create new InputStreams representing a subset of the data in the
* original InputStream. The new InputStream will access the same
* underlying data as the original, without copying the data. <p>
*
* Note that implementations of this interface must ensure that the
* <code>close</code> method does not close any underlying stream
* that might be shared by multiple instances of <code>SharedInputStream</code>
* until all shared instances have been closed.
*
* @version 1.5, 07/05/04
* @author Bill Shannon
* @since JavaMail 1.2
*/
public interface SharedInputStream {
/**
* Return the current position in the InputStream, as an
* offset from the beginning of the InputStream.
*
* @return the current position
*/
public long getPosition();
/**
* Return a new InputStream representing a subset of the data
* from this InputStream, starting at <code>start</code> (inclusive)
* up to <code>end</code> (exclusive). <code>start</code> must be
* non-negative. If <code>end</code> is -1, the new stream ends
* at the same place as this stream. The returned InputStream
* will also implement the SharedInputStream interface.
*
* @param start the starting position
* @param end the ending position + 1
* @return the new stream
*/
public InputStream newStream(long start, long end);
}
| liyue80/GmailAssistant20 | src/javax/mail/internet/SharedInputStream.java | Java | gpl-2.0 | 3,737 |
<?php
if ( !defined ( 'DIR_CORE' ) ) {
header ( 'Location: static_pages/' );
}
class ExtensionDefaultRealex extends Extension {
protected $registry;
protected $r_data;
public function __construct() {
$this->registry = Registry::getInstance();
}
//Hook to extension edit in the admin
public function onControllerPagesExtensionExtensions_UpdateData() {
$that = $this->baseObject;
$current_ext_id = $that->request->get['extension'];
if ( IS_ADMIN && $current_ext_id == 'default_realex' && $this->baseObject_method == 'edit' ) {
$html = '<a class="btn btn-white tooltips" target="_blank" href="http://www.realexpayments.com/partner-referral?id=abantecart" title="Visit Realex">
<i class="fa fa-external-link fa-lg"></i>
</a>';
$that->view->addHookVar('extension_toolbar_buttons', $html);
}
}
//Hook to enable payment details tab in admin
public function onControllerPagesSaleOrdertabs_UpdateData() {
/**
* @var $that ControllerPagesSaleOrderTabs
*/
$that = $this->baseObject;
$order_id = $that->data['order_id'];
//are we logged in and in admin?
if ( IS_ADMIN && $that->user->isLogged() ) {
//check if tab is not yet enabled.
if ( in_array('payment_details', $that->data['groups'])) {
return null;
}
//check if we this order is used realex payment
$this->_load_releax_order_data($order_id, $that);
if ( !$this->r_data ) {
return;
}
$that->data['groups'][] = 'payment_details';
$that->data['link_payment_details'] = $that->html->getSecureURL('sale/order/payment_details', '&order_id=' . $order_id.'&extension=default_realex');
//reload main view data with updated tab
$that->view->batchAssign( $that->data );
//other approch to hook to tab variable. In this case more work required to handle new tab
//$that->view->addHookVar('extension_tabs', '[tab HTML]');
}
}
//Hook to payment detilas page to show information
public function onControllerPagesSaleOrder_UpdateData() {
$that = $this->baseObject;
$order_id = $that->request->get['order_id'];
//are we logged to admin and correct method called?
if ( IS_ADMIN && $that->user->isLogged() && $this->baseObject_method == 'payment_details' ) {
//build HTML to show
$that->loadLanguage('default_realex/default_realex');
if ( !$this->r_data ) {
//no realex data yet. load it.
$this->_load_releax_order_data($order_id, $that);
}
if(!$this->r_data){
return null;
}
$view = new AView($this->registry, 0);
$view->assign('order_id', $order_id);
$view->assign('void_url', $that->html->getSecureURL('r/extension/default_realex/void'));
$view->assign('capture_url', $that->html->getSecureURL('r/extension/default_realex/capture'));
$view->assign('rebate_url', $that->html->getSecureURL('r/extension/default_realex/rebate'));
$view->assign('realex_order', $this->r_data);
$view->batchAssign($that->language->getASet('default_realex/default_realex'));
$this->baseObject->view->addHookVar('extension_payment_details', $view->fetch('pages/sale/payment_details.tpl'));
}
}
/**
* @param int $order_id
* @param AController $that
*/
private function _load_releax_order_data($order_id, $that) {
//data already loaded, return
if ( $this->r_data ) {
return null;
}
//load realex data
$that->loadModel('extension/default_realex');
$this->r_data = $that->model_extension_default_realex->getRealexOrder($order_id);
if (!empty($this->r_data)) {
$this->r_data['total_captured'] = $that->model_extension_default_realex->getTotalCaptured($this->r_data['realex_order_id']);
$this->r_data['total_formatted'] = $that->currency->format($this->r_data['total'], $this->r_data['currency_code'], 1);
$this->r_data['total_captured_formatted'] = $that->currency->format($this->r_data['total_captured'], $this->r_data['currency_code'], 1);
}
}
} | dssailo/stockpileshop | public_html/extensions/default_realex/core/default_realex.php | PHP | gpl-2.0 | 4,018 |
/**
* @file Types.hpp
* @author Adam Wolniakowski
* @date 2015-07-14
*/
#pragma once
#include <rwlibs/task/GraspTask.hpp>
namespace gripperz {
namespace grasps {
//! A type for grasp set
typedef rwlibs::task::GraspTask::Ptr Grasps;
//! Copies grasp set
Grasps copyGrasps(const Grasps tasks, bool onlySuccesses = false);
} /* grasps */
} /* gripperz */
| dagothar/gripperz | src/grasps/Types.hpp | C++ | gpl-2.0 | 402 |
class NumMatrix {
public:
NumMatrix(vector<vector<int>> &matrix) {
// error handle
if (matrix.size() == 0 || matrix[0].size() == 0) {
_m = 0;
_n = 0;
return;
}
_m = matrix.size();
_n = matrix[0].size();
_sum = vector<vector<long long>>(_m + 1, vector<long long>(_n + 1, 0));
for (int i = 0; i < _m; i++) {
for (int j = 0; j < _n; j++) {
_sum[i + 1][j + 1] =
_sum[i][j + 1] + _sum[i + 1][j] - _sum[i][j] + matrix[i][j];
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
if (row2 < row1 || col2 < col1) {
return 0;
}
if (row2 >= _m || col2 >= _n || row2 < 0 || col2 < 0) {
return 0;
}
if (row1 >= _m || col1 >= _n || row1 < 0 || col1 < 0) {
return 0;
}
if (_m == 0 || _n == 0) {
return 0;
}
//注意 边界条件
return _sum[row2 + 1][col2 + 1] - _sum[row2 + 1][col1] -
_sum[row1][col2 + 1] + _sum[row1][col1];
}
private:
vector<vector<long long>> _sum;
int _m;
int _n;
};
// Your NumMatrix object will be instantiated and called as such:
// NumMatrix numMatrix(matrix);
// numMatrix.sumRegion(0, 1, 2, 3);
// numMatrix.sumRegion(1, 2, 3, 4);
| gyang/Algo | leetcode/Range Sum Query 2D - Immutable/main.cpp | C++ | gpl-2.0 | 1,232 |
using System;
using BTZ.App.Infrastructure;
using System.Threading;
using BTZ.App.Data;
using BTZ.Common;
using Android.Util;
using Newtonsoft.Json;
namespace BTZ.App.Communication
{
/// <summary>
/// Jonas Ahlf 16.04.2015 15:33:36
/// </summary>
public class LoginMessageProcessor : ILoginMessageProcessor
{
#region WebUri
const string BaseUri = "http://192.168.1.3:56534/btz";
const string LoginUri = "/login/";
const string RegUri = "/reg/";
#endregion
readonly RemoteConnection _remoteConnection;
readonly IPrivateRepository _privateRepo;
public LoginMessageProcessor (IPrivateRepository _privateRepo)
{
this._remoteConnection = new RemoteConnection ();
this._privateRepo = _privateRepo;
}
#region ILoginMessageProcessor implementation
public event EventHandler OnLoginResult;
public event EventHandler OnRegisterResult;
public void UserLogin ()
{
new Thread (() => {
LocalUser user = _privateRepo.GetLocalUser();
LoginData data = new LoginData()
{
Username = user.Name,
Password = user.Password
};
var result = _remoteConnection.Request(new BaseDto(){JsonObject = JsonConvert.SerializeObject(data), Type = DtoType.Login});
BoolArgs args;
if(result == null)
{
args = new BoolArgs(){Success = false};
FireLoginEvent(args);
return;
}
var response = ParseLoginResponse(result);
if(response == null)
{
args = new BoolArgs(){Success = false};
FireLoginEvent(args);
return;
}
if(response.Success)
{
user.Token = response.Token;
_privateRepo.UpdateLocalUser(user);
}
args = new BoolArgs(){Success = response.Success};
FireLoginEvent(args);
}).Start ();
}
public void RegisterUser ()
{
LocalUser user = _privateRepo.GetLocalUser();
LoginData data = new LoginData()
{
Username = user.Name,
Password = user.Password
};
var result = _remoteConnection.Request(new BaseDto(){JsonObject = JsonConvert.SerializeObject(data), Type = DtoType.Register});
BoolArgs args;
if(result == null)
{
args = new BoolArgs(){Success = false};
FireRegEvent(args);
return;
}
var response = ParseLoginResponse(result);
if(response == null)
{
args = new BoolArgs(){Success = false};
FireRegEvent(args);
return;
}
if (response.Success) {
user.Token = response.Token;
_privateRepo.UpdateLocalUser (user);
} else {
_privateRepo.DeleteLocalUser ();
}
args = new BoolArgs(){Success = response.Success};
FireRegEvent(args);
}
#endregion
void FireLoginEvent(BoolArgs args)
{
if (OnLoginResult != null) {
OnLoginResult (this, args);
}
}
void FireRegEvent(BoolArgs args)
{
if (OnRegisterResult != null) {
OnRegisterResult (this, args);
}
}
LoginResponse ParseLoginResponse(string value)
{
try {
return JsonConvert.DeserializeObject<LoginResponse>(value);
} catch (Exception ex) {
return null;
}
}
string SerializeObject(object obj)
{
return JsonConvert.SerializeObject (obj);
}
}
}
| BollerTuneZ/App.Android | BTZ.App.Communication/MessageProcessor/LoginMessageProcessor.cs | C# | gpl-2.0 | 3,273 |
<?php
/**
* Created by PhpStorm.
* User: nkostop
* Date: 25/05/16
* Time: 20:32
*/
namespace Drupal\drupalcamp\Form;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
class proposal extends FormBase {
public function getFormId() {
return 'proposal_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['speakerName'] = [
'#type' => 'textfield',
'#title' => t('Speaker Name'),
'#required' => TRUE,
'#attributes' => [
'class' => [
'',
],
],
'#prefix' => '',
'#suffix' => '',
];
$form['email'] = [
'#type' => 'email',
'#title' => 'E-mail',
'#required' => TRUE,
'#prefix' => '',
'#ajax' => [
'callback' => array($this, 'validateEmail'),
'event' => 'change',
'progress' => array(
'type' => 'throbber',
'message' => t('Verifying email...'),
),
],
'#suffix' => '',
];
$form['sessionTitle'] = [
'#type' => 'textfield',
'#title' => t('Session title'),
'#required' => TRUE,
'#prefix' => '',
'#suffix' => '',
];
$form['description'] = [
'#type' => 'textfield',
'#title' => t('Description'),
'#required' => TRUE,
'#prefix' => '',
'#suffix' => '',
];
$form['submit'] = [
'#type' => 'button',
'#value' => $this->t('Submit'),
'#attributes' => [
'class' => [
'form__submit',
],
],
'#ajax' => [
'callback' => 'Drupal\drupalcamp\Form\proposal::sendCallback',
'event' => 'click',
'progress' => [
'type' => 'throbber',
'message' => t('Your registration is been send...'),
],
],
];
return $form;
}
public function validateEmail(array &$form, FormStateInterface $form_state) {
if (!(\Drupal::service('email.validator')
->isValid($form_state->getValue('email')))
) {
$ajax_response = new AjaxResponse();
$ajax_response->addCommand(new HtmlCommand('#response-message', t('Email in not valid. Please enter a valid email address.')));
// Return the AjaxResponse Object.
return $ajax_response;
}
else {
$ajax_response = new AjaxResponse();
$ajax_response->addCommand(new HtmlCommand('#response-message', ''));
// Return the AjaxResponse Object.
return $ajax_response;
}
}
public function submitForm(array &$form, FormStateInterface $form_state)
{
$mailManager = \Drupal::service('plugin.manager.mail');
$module = 'drupalcamp';
$key = 'proposal_form';
$system_site_config = \Drupal::config('system.site');
$to = $system_site_config->get('mail');
$params['message'] = $form_state->getValue('speakerName'); //TODO:fix field
$params['subject'] = $form_state->getValue('speakerName');
$params['name'] = $form_state->getValue('speakerName');
$params['email'] = $form_state->getValue('email');
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;
$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
if ($result['result'] !== true) {
$message = t('There was a problem');
drupal_set_message($message, 'error');
\Drupal::logger('drupalcamp')->error($message);
} else {
$message = t('Your proposal has been submitted.');
drupal_set_message($message);
\Drupal::logger('drupalcamp')->notice($message);
}
drupal_set_message($this->t('You have successfully submitted a proposal.'));
}
public static function sendCallback(array &$form, FormStateInterface $form_state)
{
if((\Drupal::service('email.validator')->isValid($form_state->getValue('email')))&&(!empty($form_state->getValue('speakerName')))&&(!empty($form_state->getValue('sessionTitle')))&&(!empty($form_state->getValue('description')))) {
$speakerName = $form_state->getValue('speakerName');
$sessionTitle = $form_state->getValue('sessionTitle');
$email = $form_state->getValue('email');
$description =$form_state->getValue('description');
$node = Node::create(array(
'type' => 'proposals',
'title' => $speakerName.': '.$sessionTitle,
'langcode' => 'en',
'uid' => '1',
'status' => 1,
'field_email' => $email,
'field_speaker_name' => $speakerName,
'field_session_title' => $sessionTitle,
'body' => $description,
));
$node->save();
$ajax_response = new AjaxResponse();
$mailManager = \Drupal::service('plugin.manager.mail');
$module = 'drupalcamp';
$key = 'proposal_form';
$system_site_config = \Drupal::config('system.site');
$to = $system_site_config->get('mail');
$params['message'] = $form_state->getValue('speakerName'); //TODO:fix field
$params['subject'] = $form_state->getValue('speakerName');
$params['name'] = $form_state->getValue('speakerName');
$params['email'] = $form_state->getValue('email');
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;
$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
if ($result['result'] !== true) {
$message = t('There was a problem please try again later');
drupal_set_message($message, 'error');
\Drupal::logger('drupalcamp')->error($message);
} else {
$message = t('Your proposal has been submitted.');
drupal_set_message($message);
\Drupal::logger('drupalcamp')->notice($message);
$ajax_response->addCommand(new HtmlCommand('#proposal-form',''));
}
} else {
$message = t('Proposal not send. Please fill in all fields.');
}
$ajax_response->addCommand(new HtmlCommand('#response-message',$message));
// Return the AjaxResponse Object.
return $ajax_response;
}
} | AchillesKal/page2016 | modules/custom/drupalcamp/src/Form/proposal.php | PHP | gpl-2.0 | 6,115 |
// Standard imports
import java.util.Map;
// Application specific imports
import org.web3d.x3d.sai.*;
public class SAIExample1
implements X3DScriptImplementation, X3DFieldEventListener {
/** Color Constant, RED */
private static final float[] RED = new float[] {1.0f, 0, 0};
/** Color Constant, BLUE */
private static final float[] BLUE = new float[] {0, 0, 1.0f};
/** A mapping for fieldName(String) to an X3DField object */
private Map fields;
/** The isOver field */
private SFBool isOver;
/** The diffuseColor_changed field */
private SFColor diffuseColor;
//----------------------------------------------------------
// Methods from the X3DScriptImplementation interface.
//----------------------------------------------------------
/**
* Set the browser instance to be used by this script implementation.
*
* @param browser The browser reference to keep
*/
public void setBrowser(Browser browser) {
}
/**
* Set the listing of fields that have been declared in the file for
* this node. .
*
* @param The external view of ourselves, so you can add routes to yourself
* using the standard API calls
* @param fields The mapping of field names to instances
*/
public void setFields(X3DScriptNode externalView, Map fields) {
this.fields = fields;
}
/**
* Notification that the script has completed the setup and should go
* about its own internal initialization.
*/
public void initialize() {
isOver = (SFBool) fields.get("isOver");
diffuseColor = (SFColor) fields.get("diffuseColor_changed");
// Listen to events on isOver
isOver.addX3DEventListener(this);
}
/**
* Notification that this script instance is no longer in use by the
* scene graph and should now release all resources.
*/
public void shutdown() {
}
/**
* Notification that all the events in the current cascade have finished
* processing.
*/
public void eventsProcessed() {
}
//----------------------------------------------------------
// Methods from the X3DFieldEventListener interface.
//----------------------------------------------------------
/**
* Handle field changes.
*
* @param evt The field event
*/
public void readableFieldChanged(X3DFieldEvent evt) {
if (evt.getSource() == isOver) {
if (isOver.getValue() == true)
diffuseColor.setValue(RED);
else
diffuseColor.setValue(BLUE);
} else {
System.out.println("Unhandled event: " + evt);
}
}
}
| Norkart/NK-VirtualGlobe | Xj3D/spec_examples/x3d/SAIExample1.java | Java | gpl-2.0 | 2,730 |
/*
* \brief localization strings for fr_FR
*
* \file loc_fr_FR.js
*
* Copyright (C) 2006-2009 Jedox AG
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as published
* by the Free Software Foundation at http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*
* You may obtain a copy of the License at
*
* <a href="http://www.jedox.com/license_palo_bi_suite.txt">
* http://www.jedox.com/license_palo_bi_suite.txt
* </a>
*
* If you are developing and distributing open source applications under the
* GPL License, then you are free to use Palo under the GPL License. For OEMs,
* ISVs, and VARs who distribute Palo with their products, and do not license
* and distribute their source code under the GPL, Jedox provides a flexible
* OEM Commercial License.
*
* \author
* Drazen Kljajic <drazen.kljajic@develabs.com>
* Mladen Todorovic <mladen.todorovic@develabs.com>
* Srdjan Vukadinovic <srdjan.vukadinovic@develabs.com>
* Andrej Vrhovac <andrej.vrhovac@develabs.com>
* Predrag Malicevic <predrag.malicevic@develabs.com>
*
* \version
* SVN: $Id: loc_fr_FR.js 4895 2011-04-27 09:35:11Z l10n-tool $
*
*/
Jedox.wss.i18n.L10n = 'fr_FR';
Jedox.wss.i18n.separators = [ ',', '.', ';' ];
Jedox.wss.i18n.bool = { 'true': 'VRAI', 'false': 'FAUX' };
Jedox.wss.i18n.strings = {
// Menubar
"Import": "Import",
"Save as": "Enregistrer sous",
"Save Workspace": "Volet enregistrer",
"File Search": "Recherche de fichiers",
"Permission": "Autorisation",
"Print Area": "Zone d'impression",
"Print Preview": "Aperçu avant impression",
"Print": "Imprimer",
"Send to": "Envoyer vers",
"Form Elements": "Éléments de formulaire",
"ComboBox": "Liste déroulante",
"Can\'t Repeat": "Répétition impossible",
"Quick Publish": "Publication rapide",
"Can\'t Undo": "Impossible d'annuler",
"Can\'t Redo": "Impossible de rétablir",
"WSS Clipboard": "Presse-papiers",
"Paste as Hyperlink": "Coller comme lien hypertexte",
"Clear": "Effacer",
"Delete Rows": "Supprimer les lignes",
"Delete Columns": "Supprimer les colonnes",
"Move or Shopy Sheet": "Déplacer ou copier la feuille",
"Replace": "Remplacer",
"Go To": "Atteindre",
"Object": "Objet",
"Normal": "Normal ",
"Page Break Preview": "Aperçu des sauts de page",
"Task Pane": "Panneau des tâches",
"Header and Footer": "En-tête et pied de page",
"Comments": "Commentaires",
"Custom View": "Affichage personnalisé",
"Full Screen": "Plein écran",
"Zoom": "Zoom ",
"Entire row": "Insertion de lignes",
"Entire column": "Insertion de colonnes",
"Worksheet": "Feuille",
"Symbol": "Caractères spéciaux",
"Page Break": "Saut de page",
"Diagram": "Diagramme",
"Edit Hyperlink": "Editer le lien hypertexte",
"Row": "Ligne",
"Row Height": "Hauteur de ligne",
"Autofit Row Height": "Ajustement automatique des lignes",
"Autofit Column Width": "Ajustement automatique des colonnes",
"Sheet": "Feuille",
"AutoFormat": "Mise en forme automatique",
"Conditional Formatting": "Mise en forme conditionnelle",
"Style": "Style ",
"Tools": "Outils",
"Spelling": "Orthographe",
"Research": "Recherche",
"Error Checking": "Vérification des erreurs",
"Shared Workspace": "Espace de travail partagé",
"Share Workbook": "Partager le classeur",
"Track Changes": "Suivi des modifications",
"Compare and Merge Workbooks": "Comparaison et fusion de classeurs",
"Online Collaboration": "Collaboration en ligne",
"Goal Seek": "Valeur cible",
"Scenarios": "Scénarios",
"Formula Auditing": "Audit de formules",
"Macros": "Macros",
"Add-Ins": "Macros complémentaires",
"AutoCorrect Options": "Options de correction automatique",
"Customize": "Personnaliser",
"Options": "Options ",
"Palo": "Palo ",
"Paste View": "Créer une vue",
"Paste SubSet": "Coller le sous-ensemble",
"Paste Data Function": "Fonction d\'accès aux données",
"Data Import": "Import de données",
"Palo Wizard": "Assistant Palo",
"WikiPalo": "WikiPalo",
"About": "A propos de",
"Data": "Données",
"Filter": "Filtre",
"Form": "Formulaire",
"Subtotals": "Sous-totaux",
"Validation": "Validation ",
"Table": "Table ",
"Text to Columns": "Convertir",
"Group and Outline": "Groupe et contours",
"Import External Data": "Données externes",
"XML": "XML ",
"Refresh Data": "Actualisation des données",
"Auto-Refresh Data": "Actualisation automatique des données",
"Auto-Calculate Data":"Calculation automatique des données",
"New Window": "Nouvelle fenêtre",
"Arrange": "Réorganiser",
"Compare Side by Side with": "Comparer côte à côte avec",
"Split": "Fractionner",
"Freeze Panes": "Figer les volets",
"Worksheet-Server Help": "Aide sur Worksheet-Server",
"Jedox Online": "Jedox_Online",
"Contact us": "Contactez-nous",
"Check for Updates": "Rechercher les mises à jour",
"Customer Feedback Options": "Options pour les commentaires utilisateurs",
"About Worksheet-Server": "A propos de Worksheet-Server",
"About Palo Suite":"A propos de Palo Suite",
// Formatbar
"Center text": "Au centre",
"Align Text Right": "Aligné à droite",
"Show/Hide Grid": "Afficher/masquer quadrillage",
"Item Lock/Unlock": "Verrouiller les cellules",
"Insert Chart": "Insérer un graphique",
"Back": "Retour",
"Back To": "Retour à",
"Refresh / Recalculate": "Actualiser / Recalculer",
"Print To PDF": "Imprimer en PDF",
"Download": "Télécharger",
"Download Workbook": "Télécharger le classeur",
// Sheet Selector
"First Sheet": "La première feuille",
"Previous Sheet": "La feuille précédente",
"Next Sheet": "La feuille suivante",
"Last Sheet": "La dernière feuille",
"Delete Worksheet": "Supprimer la feuille",
"delLastWorksheet": "Un classeur doit contenir au moins une feuille.<br>Pour supprimer les feuilles sélectionnées, vous devez insérer d'abord une nouvelle feuille.",
"Move Worksheet": "Déplacer la feuille",
"moveLastWorksheet": "Un classeur doit contenir au moins une feuille.<br>Pour déplacer les feuilles sélectionnées, vous devez insérer d'abord une nouvelle feuille.",
// Workbook
"saveFileErr": "Votre fichier n'a pas pu être enregistré !",
"errWBSave_nameExists": "{Name} existe déjà.<br>Souhaitez-vous remplacer le fichier ?",
"errWBSave_noParent": "Nom du classeur \"{Name}\" est trop court.<br>Il doit contenir au moins 2 caractères.",
"errWBSave_noParentAccess": "Nom du classeur \"{Name}\" est trop long.<br>Il ne doit pas contenir plus de 64 caractères.",
"errWBSave_noAccess": "Vous ne pouvez pas enregistrer ce classeur car <br>un autre classeur \"(nom) \" est toujours ouvert.<br><br>Sélectionnez un autre nom ou fermez le même classeur.",
// Import Dialog
"impDlg_fieldLbl": "Fichier à importer (seulement les fichiers xlsx sont permis)",
"impDlg_msgWrongType": "Dans ce champ, vous devez entrer la totalité du chemin d'accès au fichier xlsx !",
"Upload": "Importer",
"Import Error": "Erreur d'importation",
"imp_err_msg": "Il n'est pas possible d'importer le fichier \"{Name}\" ",
// Insert Function Dialog
"Select a category": "Sélectionnez une catégorie",
"Select a function": "Sélectionnez une fonction",
"Functions": "Fonctions",
"Insert Function": "Insérer une fonction",
// Save As Dialog
"newWBName": "Entrez le nouveau nom de fichier",
// Errors
"srvNotRespond": "Erreur fatale : le serveur ne répond pas ! \N Le client a été arrêté.",
"Invalid input!": "Entrée non valide !",
"Override me!": "Ignorez l'erreur !",
"Error Data": "Erreur de données",
"General Error": "Erreur générale",
"Application Backend Error": "Backend application erreur",
"Server Error": "Erreur du serveur",
"This is a fatal error, re-login will be required!": "Il s'agit d'une erreur fatale. Cela nécessite un nouvel login!",
// Insert/Edit Chart
"End Select Range": "Fin de la plage sélectionnée",
"Select Data Source": "Sélectionnez la source de données",
"Input Error": "Erreur de saisie",
"Unsupported Element": "Elément non supporté",
"Operation Error": "Erreur d'opération",
"Data Source": "Source de données",
"Chart data range": "Plage de données du graphique",
"Group data by": "Série en",
"Use series labels": "Utiliser les noms des séries",
"Label location": "Position de l'étiquette",
"Use category labels": "Utiliser les noms de catégories",
"Select Range": "Sélectionner une plage",
"Labels": "Étiquettes",
"Chart title": "Titre du graphique",
"Edit Chart": "Editer le graphique",
"Cols": "Cimes",
"Delete Chart": "Supprimer le graphique",
"chartDlg_invalidChartType": "Le type du graphique n\'est pas valide.",
"chartDlg_rangeEmpty": "La plage de cellules est vide. Veuillez entrer des données ou choisir une source de données valide.",
"chartDlg_deleteError": "Le graphique sélectionné ne peut pas être supprimé!",
"chartDlg_EditError": "Les propriétés actuelles du graphique ne peuvent pas être récupérées",
"chartDlg_unsupportedChartType": "Le type de graphique sélectionné sera bientôt disponible !",
"chartDlg_genError": "La création du graphique n\'est pas possible. Veuillez vérifier les propriétés du graphique sélectionné.",
"Incorect Chart Size": "La taille du graphique est incorrect",
"infoChart_wrongSize": "La nouvelle taille du graphique n\'est pas bonne, il est automatiquement ajusté à la taille appropriée.",
"infoChart_wrongSize2": "Certains graphiques n'ont pas la taille appropriée. Leur taille sera automatiquement ajustée.",
"Change Chart Type": "Changer le type du graphique",
"Format Chart Properties": "Formater le graphique",
"Scales": "Echelles",
"Zones": "Gammes",
"Scale": "Echelle",
"Zones options": "Options des gammes",
"Points": "Aiguilles",
"Points options": "Options des aiguilles",
"Categories": "Catégories",
"Type": "Objet",
"Sort Ascending": "Tri croissant",
"Sort Descending": "Tri descendant",
"Group by": "Groupe par",
//editChart
"Column": "Histogramme",
"Area": "Aires",
"X Y (Scatter)": "Nuages de points",
"Stock": "Bousier",
"Radar": "Radar",
"Meter": "Tachymètre",
"Clustered Column": "Histogramme groupé",
"Stacked Column": "Histogramme empilé",
"100% Stacked Column": "Histogramme empilé 100%",
"3-D Clustered Column": "Histogramme groupé avec effet 3D",
"Stacked Column in 3-D": "Histogramme empilé avec effet 3D",
"100% Stacked Column in 3-D": "Histogramme empilé 100% avec effet 3D",
"Clustered Cylinder": "Histogramme groupé à formes cylindriques",
"Stacked Cylinder": "Histogramme empilé à formes cylindriques",
"100% Stacked Cylinder": "Histogramme empilé 100% à formes cylindriques",
"Stacked Line": "Courbes empilées",
"100% Stacked Line": "Courbes empilées 100%",
"Rotated Line": "Courbes pivotées",
"Line with Markers": "Courbes avec marques de données affichées à chaque point",
"Stacked Line with Markers": "Courbes empilées avec marques de données affichées à chaque point",
"100% Stacked Line with Markers": "Courbes empilées 100% avec marques de données affichées à chaque point",
"Rotated Line with Markers": "Courbes pivotées avec marques de données affichées à chaque point",
"3-D Line": "Courbes avec effet 3D",
"Pie in 3-D": "Secteurs avec effet 3D",
"Exploded Pie": "Secteurs éclatés",
"Exploded Pie in 3-D": "Secteurs éclatés avec effet 3D",
"Clustered Bar": "Barres groupées",
"Stacked Bar": "Barres empilées",
"100% Stacked Bar": "Barres empilées 100%",
"Clustered Bar in 3-D": "Barres groupées avec effet 3D",
"Stacked Bar in 3-D": "Barres empilées avec effet 3D",
"100% Stacked Bar in 3-D": "Barres empilées 100% avec effet 3D",
"Clustered Horizontal Cylinder": "Barres groupées de formes cylindriques",
"Stacked Horizontal Cylinder": "Barres empilées de formes cylindriques",
"100% Stacked Horizontal Cylinder": "Barres empilées 100% de formes cylindriques",
"Stacked Area": "Aires empilées",
"100% Stacked Area": "Aires empilées 100%",
"3-D Area": "Aires avec effet 3D",
"Stacked Area in 3-D": "Aires empilées avec effet 3D",
"100% Stacked Area in 3-D": "Aires empilées 100% avec effet 3D",
"Scatter with only Markers": "Nuage de points avec marques des données",
"Scatter with Smooth Lines and Markers": "Nuage de points reliés par une courbe lissée",
"Scatter with Smooth Lines": "Nuage de points avec lissage sans marquage des données",
"Scatter with Straight Lines and Markers": "Nuage de points reliés par une courbe",
"Scatter with Straight Lines": "Nuage de points reliés par une courbe sans marquage des données",
"High-Low-Close": "Haut-bas-fermé",
"Open-High-Low-Close": "Ouvert-haut-bas-fermé",
"Doughnut": "Anneau",
"Exploded Doughnut": "Anneau éclaté",
"Bubble": "Bulles",
"Bubble with a 3-D Effect": "Bulle avec effet 3D",
"Radar with Markers": "Radar avec marquage des données",
"Filled Radar": "Radar plein",
"Odometer Full": "Cercle-Tachymètre",
"Odometer Full Percentage": "Cercle-Tachymètre avec %",
"Odometer Half": "Demi-Cercle-Tachymètre",
"Odometer Half Percentage": "Demi-Cercle-Tachymètre avec %",
"Wide Angular Meter": "Grand-Angle-Tachymètre",
"Horizontal Line Meter": "Tachymètre horizontal",
"Vertical Line Meter": "Tachymètre vertical",
"Fill": "Remplir",
"Border Color": "Couleur de la bordure",
"No fill": "Ne pas remplir",
"Solid fill": "Remplissage plein",
"Automatic": "Automatique",
"No line": "Pas de ligne",
"Solid line": "Ligne solide",
"Source Data Options": "Options de la source de données",
"Chart Data Range": "Plage de données du graphique",
"Group Data By": "Série en",
"Columns": "Colonnes",
"Rows": "Lignes",
"Yes": "Oui",
"No": "Non",
"Font Options": "Options de police",
"Title Options": "Options du titre",
"Legend Options": "Options de la légende",
"Horizontal Axis": "Axe des abscisses",
"Horizontal axis": "Axe des abscisses",
"Vertical Axis": "Axe des ordonnées",
"Vertical axis": "Axe des ordonnées",
"Auto": "Auto ",
"Fixed": "Fixé",
"Major Unit": "Grand unité",
"Minor Unit": "Petit unité",
"Chart Type": "Type du graphique",
"Chart Area": "Zone du graphique",
"Plot Area": "Zone de la figure",
"Source Data": "Source de données",
"Title": "Titre",
"Legend": "Légende",
"Axes": "Axes",
"Format Chart": "Format du graphique",
"Series Options":"Options des séries",
"Series":"Séries",
"Office":"Bureau",
"Apex":"Apex",
"Aspect":"Aspect",
"Name":"Nom",
"General":"Général",
"No border":"Aucun bordure",
"Select Source Data":"Source de données",
//Cell Comments
"Comment": "Commentaire",
"Edit Comment": "Editer le commentaire",
"Delete Comment": "Supprimer le commentaire",
"Hide Comment": "Masquer le commentaire",
"Show/Hide Comment": "Afficher/masquer le commentaire",
"Insert Comment": "Insérer un commentaire",
// PALO Paste View
"Choose Cube": "Sélectionner le cube",
"Wrap Labels": "Réaligner",
"Fixed width": "Largeur fixe",
"Show element selector on doubleclick": "Montrer le sélecteur en double-cliquant",
"Paste at selected cell": "Coller dans la cellule sélectionnée",
"Page selector": "Selecteur de page",
"Column titles": "Titres en en-tête de colonne",
"Row titles": "Titres de ligne",
"Select Elements": "Choisir un élément",
"Please wait": "Veuillez patienter",
"Obtaining data!": "Transmission des données!",
// Select Elements
"B": " B ",
"Select Branch": "Choisir une branche",
"Invert Selec": "Inverser la sélection",
"Paste Vertically": "Coller verticalement",
"Ascending": "Ordre croissant",
"Descending": "Ordre décroissant",
"Clear list": "Vider la liste",
"Pick list": "Liste de choix",
"_msg: se_Tip": "Astuce",
"Show all selection tools": "Afficher tous les outils de sélection",
"insert database elements": "Insérer des éléments de la base de données ",
"insert server/database (connection)": "Insérer Serveur/base de données (connexion)",
"insert cube name": "Insérer le nom du cube",
"insert dimension names": "Insérer les noms des dimensions",
"Invert Select": "Inverser la sélection",
"Paste horizontaly": "Coller horizontalement",
// Paste Data Functions
"Paste Data Functions": "Fonction d\'accès aux données",
"Attribute Cubes": "Cube d'attributs",
"Guess Arguments": "Choix automatique des paramètres",
// Format Cells Dialog
"Format Cells": "Format des cellules",
"Number": "Nombre",
"Currency": "Monétaire",
"Accounting": "Comptabilité",
"Date": "Date",
"Time": "Heure",
"Percentage": "Pourcentage",
"Fraction": "Fraction",
"Scientific": "Scientifique",
"Special": "Spécial",
"Custom": "Personnalisé",
"$ US Dollar": "Dollar $ US",
"€ Euro": "Euro €",
"£ GB Pound": "Anglais £",
"CHF Swiss Francs": "Francs Suisse CHF",
"¥ Japanese Yen": "Yen japonais ¥",
"YTL Turkey Liras": "Lires turques YTL",
"Zł Poland Zlotych": "Zloty polonais Zł",
"₪ Israel, New Shekels": "Nouveaux Shekels israéliens ₪",
"HKD Hong Kong Dollar": "Hong Kong Dollar HKD",
"KC Czech Koruny": "Couronnes tchèques KC",
"CNY China Yuan": "Yen chinois CNY",
"P Russian Rubles": "Roubles russes P",
"_catDescr: general": "Les cellules avec un format Standard n\'ont pas de format de nombre spécifique.",
"_catDescr: number": "Le format Nombre est utilisé pour l\'affichage général des nombres. Les catégories Monétaire et Comptabilité offrent des formats spéciaux pour les valeurs monétaires.",
"_catDescr: currency": "Les formats Monétaire sont utilisés pour des valeurs monétaires générales. Utilisez les formats Comptabilité pour aligner les décimaux dans une colonne.",
"_catDescr: accounting": "Les formats Comptabilité alignent les symboles monétaires et les décimaux dans une colonne.",
"_catDescr: date": "Les formats Date affichent les numéros de date et d\'heure comme valeurs de date. À l\'exception des éléments précédés d\'un astérisque(*), l\'ordre des parties de la date ne change pas en fonction du système d\'exploitation.",
"_catDescr: time": "Les formats Heures affichent les numéros de date et heure comme valeurs d\'heure. À l\'exception des éléments précédés d\'un astérisque(*), l\'ordre des parties de la date ou de l\'heure ne change pas en fonction du système d\'exploitation.",
"_catDescr: percentage": "Les formats Pourcentage multiplient la valeur de la cellule par 100 et affichent le résultat avec le symbole pourcentage.",
"_catDescr: special": "Les formats Spécial sont utilisés pour contrôler des valeurs de liste et de base de données.",
"_catDescr: text": "Les cellules de format Texte sont traitées comme du texte même si c\'est un nombre qui se trouve dans la cellule. La cellule est affichée exactement comme elle a été entrée.",
"_catDescr: custom": "Entrez le code du format de nombre, en utilisant un des codes existants comme point de départ.",
"Sample": "Exemple",
"Locale (location)": "Paramètres régionaux (emplacement)",
"Category": "Catégorie",
"Up to one digit(1/4)": "D'un chiffre(1/4)",
"Up to two digits(21/35)": "De deux chiffres(21/35)",
"Up to three digits(312/943)": "De trois chiffres(312/943)",
"Up to halves(1/2)": "Demis(1/2)",
"Up to quarters(2/4)": "Quarts(2/4)",
"Up to eights(4/8)": "Huitièmes(4/8)",
"Up to sixteenths(8/16)": "Seizièmes(8/16)",
"Up to tenths(3/10)": "Dixièmes(3/10)",
"Up to hundredths(30/100)": "Centièmes(30/100)",
"Context": "Contexte",
"Left-to-Right": "De gauche à droite",
"Right-to-Left": "De droite à gauche",
"Top": "Haut",
"Justify": "Justifié",
"Distributed": "Distribué",
"Distributed (Indent)": "Distribué (Retrait)",
"Center across section": "Centré sur plusieurs colonnes",
"Left (Indent)": "Gauche (Retrait)",
"Decimal places": "Décimales",
"Negative numbers": "Nombres négatifs",
"Use 1000 Separator (.)": "Utiliser le séparateur de milliers(.)",
"Wrap Text": "Renvoyer à la ligne automatiquement",
"Text alignment": "Alignement du texte",
"Vertical": "Verticale",
"Horizontal": "Horizontal",
"Text control": "Contrôle du texte",
"Merge cells": "Fusionner les cellules",
"Text direction": "Orientation du texte",
"Line": "Courbes",
"Color": "Couleur",
"Presets": "Présélections",
"Border": "Bordure",
"The selected border style can be applied by clicking the presets, preview diagram or the buttons above.": "Le style de bordure sélectionné peut être appliqué en cliquant sur l\'une des présélections ou les autres boutons ci-dessus.",
"No Color": "Pas de couleur",
"More Colors": "Plus de couleurs",
"Background color": "Couleur de fond",
"Pattern style": "Motifs",
"Locked": "Verrouillée",
"Hidden": "Masquée",
"Normal font": "Police normale",
"Strikethrough": "Barré",
"Overline": "Souligné",
"Effects": "Effets",
"Font style": "Style ",
"This is a TrueType font. The same font will be used on both your printer and your screen.": "Police TrueType, identique à l'écran et à l'impression.",
"-1234,10": "-1234,10 ",
"1234,10": "1234,10 ",
"Protection": "Protection",
"Font": "Police ",
"Locking cells or hiding formulas has no effect until you protect the worksheet.": "Verrouillé ou Masqué a seulement des effets après la protection de la feuille.",
"Merge": "Fusionner",
"Wrap text": "Renvoyer à la ligne automatiquement",
"General format cells have no formatting.": "Les cellules de format Standard n\'ont pas de format de nombre spécifique.",
// Main Context Menu
"Edit Micro Chart": "Editer le micrographique",
// DynaRanges
"Local List": "Liste locale",
"Vertical Hyperblock": "DynaRange vertical",
"Horizontal Hyperblock": "DynaRange horizontal",
"Switch Direction": "Changer la direction",
"Edit List": "Editer la liste",
// hb Dialog
"_tit: hb Properties": "Propriétés du DynaRange",
"Standard": "Standard",
"Text Format of the List": "Format texte de la liste",
"List Selector": "Sélecteur de la liste",
"Drill down, begin at level": "Drill down, commencer au niveau",
"Indent Text": "Indenter le texte",
"Fixed column width": "Largeur fixé",
"Display": "Affichage",
"Filling": "Remplissage",
"Pattern": "Motifs",
"_name: UnnamedHb": "DynaRange",
"Solid": "Solide",
"Dotted": "Pointillé",
"Dashed": "En trait",
"Direction": "Orientation",
"Width": "Largeur",
"auto": "auto ",
"fixed": "fixé",
"Set column width": "Définir la largeur des colonnes",
// Unhide Windows
"Unhide workbook": "Afficher le classeur",
// MicroChart Dialog
"Bar": "Barres",
"Dots": "Points",
"Doted Line": "Ligne point.",
"Whisker": "Ligne mince",
"Pie": "Secteurs",
"0..max": "0...max",
"min..max": "min..max",
"user defined": "Personnalisé",
"Select Cell": "Choix de cellule",
"Scaling": "Échelle",
"Source": "Source",
"Target": "Affichage dans",
"Min": "Min",
"Max": "Max",
"pos. values": "Valeurs positives",
"neg. values": "Valeurs négatives",
"win": "Profit",
"tie": "Equivalent",
"lose": "Perte",
"first": "Première",
"last": "Dernière",
"min": "min",
"max": "max",
// Arrange Windows Dialog
"Arrange Windows": "Réorganiser",
"Tiled": "Mosaïque",
"Cascade": "Cascade",
//Open Dialog
"Look in": "Rechercher dans",
"My Recent Documents": "Documents récents",
"My Workbook Documents": "Mes documents",
"Go Up one level": "Dossier parent",
"Adds New folder to the list": "Ajouter un nouveau dossier à la liste",
"File name": "Nom de fichier",
"Files of type": "Type de fichiers",
"Work Sheet Files": "Feuilles de calcul",
"All Files": "Tous les fichiers",
"Save as type": "Type de fichiers",
"Work Sheet Files (*.wss)": "Feuilles de calcul (*.wss)",
"save_as_err_msg": "Le nom du fichier <b>\"{fileName}\"</b> n\'est pas valide. Veuillez entrer un nom valide.",
"Database read error":"Erreur de lecture de base de données",
"read_data_err":"Impossible de lire la base de données. Veuillez actualiser le groupe de dossiers.",
"Database write error":" Erreur d'écriture dans la base de données",
"write_data_err":"Impossible d'écrire dans la base. Veuillez actualiser le groupe de dossiers.",
// Format Col/Row dialog
"Row height": "Hauteur de ligne",
"Column width": "Largeur de colonne",
// Conditional Formatting dialog + Manage Conditional FMT
"Format all cells based on their values": "Mettre en forme toutes les cellules d'après leur valeur",
"Format only cells that contain": "Appliquer une mise en forme uniquement aux cellules avec contenu déterminé",
"Format only top or bottom ranked values": "Appliquer une mise en forme uniquement aux valeurs classées parmi les premières ou les dernières valeurs",
"Format only values that are above or below average": "Appliquer une mise en forme uniquement aux valeurs au-dessus ou en-dessous de la moyenne",
"Format only unique or duplicate values": "Appliquer une mise en forme uniquement aux valeurs uniques ou aux doublons",
"Use a formula to determine which cells to format": "Utiliser une formule pour déterminer pour quelles cellules le format sera appliqué",
"Current Selection": "Sélection actuelle",
"This Worksheet": "Cette feuille de calcul",
"Edit Rule": "Modifier la règle",
"Delete Rule": "Effacer la règle",
"Conditional Formatting Rules Manager": "Gestionnaire des règles de mise en forme conditionnelle",
"Show formatting rules for": "Affiche les règles de mise en page pour",
"Rule (applied in order shown)": "Règle (appliqué de haut en bas)",
"Edit Formatting Rule": "Modifier règle de mise en forme",
"Applies to": "Appliqué à",
"2-Color Scale": "Échelle à deux couleurs",
"3-Color Scale": "Échelle à trois couleurs",
"Lowest value": "Valeur inférieure",
"Percent": "Pourcentage",
"Formula": "Formule",
"Percentile": "Centile",
"Highest value": "Valeur supérieure",
"above": "au-dessus",
"below": "en-dessous",
"equal or above": "égales ou au-dessus",
"equal or below": "égales ou en-dessous",
"1 std dev above": "1 écart-type au-dessus",
"2 std dev above": "2 écarts-type au-dessus",
"3 std dev above": "3 écarts-type au-dessus",
"1 std dev below": "1 écart-type en-dessous",
"2 std dev below": "2 écarts-type en-dessous",
"3 std dev below": "3 écarts-type en-dessous",
"duplicate": "en double",
"unique": "unique",
"Cell Value": "Valeur de la cellule",
"Specific Text": "Texte spécifique",
"Dates Occurring": "Dates se produisant",
"Blanks": "Cellules vides",
"No Blanks": "Aucune cellule vide",
"Errors": "Erreurs",
"No errors": "Aucune erreur",
"between": "Comprise entre",
"not between": "non comprise entre",
"equal to": "égale à",
"not equal to": "différente de",
"greater than": "supérieure à",
"less than": "inférieure à",
"greater than or equal to": "supérieure ou égale à",
"less than or equal to": "inférieure ou égale à",
"containing": "contenant",
"not containing": "ne contenant pas",
"beginning with": "commençant par",
"ending with": "se terminant par",
"Yesterday": "Hier",
"Today": "Aujourd'hui",
"Tomorrow": "Demain",
"In the last 7 days": "Dans les sept derniers jours",
"Last week": "Semaine dernière",
"This week": "Cette semaine",
"Next week": "Semaine prochaine",
"Last month": "Le mois dernier",
"This month": "Ce mois",
"Next month": "Mois prochain",
"Midpoint": "Point central",
"New Formatting Rule": "Nouvelle règle de mise en forme",
"Select a Rule Type": "Sélectionnez un type de règles",
"Edit the Rule Description": "Instructions de règle",
"Stop If True": "Arrêter si vrai",
"Average Value": "Valeur moyenne",
"grater than": "supérieure à",
"Minimum": "Minimum",
"Maximum": "Maximum",
"and": "et",
"Format only cells with": "Appliquer une mise en forme uniquement aux cellules contenant",
"% of the selected range": "% de la plage sélectionnée",
"Format values that rank in the": "Appliquer une mise en forme aux valeurs figurant dans les",
"the average for the selected range": "la moyenne de la plage sélectionnée",
"Format values that are": "Appliquer une mise en forme aux valeurs qui",
"values in the selected range": "Valeurs dans la plage sélectionnée",
"Format all": "Appliquer une mise en forme à toutes",
"Format values where this formula is true": "Appliquer une mise en forme aux valeurs pour lesquelles cette formule est vraie",
// Insert Hyperlink dialog
"Text to display": "Nom du lien",
"E-mail address": "Adresse de messagerie",
"Subject": "Objet",
"Edit the new document later": "Modifier le nouveau document ultérieurement",
"Edit the new document now": "Modifier le nouveau document maintenant",
"Cell Reference": "Référence de cellule",
"Text": "Texte",
"Web Address": "Adresse Web",
"Type the cell reference": "Tapez la référence de la cellule",
"_cell_sheet_reference": "Cible (cellule ou feuille)",
"_error: empty hl name": "Le nom de lien hypertexte (texte à afficher) est vide. Veuillez ajouter un nom.",
"This field is required": "Ce champ est obligatoire",
"Select a place in this document": "Veuillez sélectionnez un emplacement dans le document",
"Name of new document": "Nom du nouveau document",
"When to edit": "Quand modifier",
"Link to": "Lien vers",
"Address": "Adresse",
"Existing File": "Fichier existant",
"Place in This Document": "Emplacement dans ce document",
"Create New Document": "Créer un document",
"Web page": "Page Web",
"E-mail Address": "Adresse de messagerie",
"No images to display": "Pas d'image à afficher",
"Screen tip": "Info bulle",
"Insert Hyperlink": "Insérer un lien hypertexte",
"Selection": "Sélection",
"Named Rang": "Plage nommée",
"Variable": "Variable",
"Constant Value": "Valeur constante",
"Constant List": "Liste constante",
"Variable list": "Liste variable",
"From Cell": "De la cellule",
"Hyperlink Error": "Erreur de lien hypertexte",
"_hl_missing_target_node": "Le document lié n\'existe pas. Il a peut être été déplacé ou supprimé. Veuillez en choisir un autre.",
"_hl_missing_target_sheet_nr":"La feuille liée ou la plage nommée n\'existe pas. Elle a peut être été renommée ou supprimée. Veuillez en choisir une autre.",
"_hl_no_selected_file": "Vous n'avez sélectionné aucun fichier. <br> Veuillez sélectionner un fichier et essayer à nouveau.",
"Transfer": "Transfert",
"Transfer to": "Transfert à",
"Transfer To (Key)": "Transfert à",
"Transfer From (Key)": "Transfert de",
"Transfer From": "Transfert de",
"Named Range": "Plage nommée",
"Update": "Actualiser",
"Picture Hyperlink": "Lien hypertexte d\'une image",
//Insert Picture Dialog
"Select a picture": "Sélectionner une image",
"Photo": "Photo",
"File Name": "Nom du fichier",
"Enter the File name": "Indiquer le nom du fichier.",
"Enter the File description": "Indiquer la description du fichier",
"_lbl: picToImport": "Fichier image pour l'import (uniquement .gif, .jpg, .jpeg et .png possible)",
"Edit Picture": "Modifier l'image",
"Delete Picture": "Supprimer l'image",
"impImg_msgWrongType": "Format d'image non supporté !",
"imgDlg_genError": "L\'import de l\'image n\'est pas possible.",
"imgDlg_deleteError": "Il n'est pas possible de supprimer l'image sélectionnée !",
"Unable to import picture": "L\'import de l\'image n\'est pas possible.",
"imgFile_toBig": "L\'image est trop grande. La taille maximale de l\'image est 2MB.",
"imgFile_unsupportedType": "Format d'image non supporté !",
"imgFile_undefError": "Une erreur inconnue est survenue.",
"Reset": "Annuler",
//Sheet Move OR Copy dialog
"(new book)": "(nouvelle feuille de calcul)",
"(move to end)": "(mettre à la fin)",
"To Book": "Dans la feuille de calcul",
"Before sheet": "Coller avant",
"Move or Copy": "Déplacer/Copier",
"Create a copy": "Créer une copie",
//Rename Sheet Dialog
"New Name": "Nouveau nom",
"informationMsg": "Le nom existe déjà",
"adviceMsg": "Indiquer un nouveau nom",
// Status Bar Localization
"Designer": "Designer",
"User": "Utilisateur",
"QuickView": "Aperçu rapide",
"Ready": "Prêt",
"Mode": "Mode",
//Paste Special Dialog
"All using Source theme": "Tout ce qu'utilise la plage source",
"All except borders": "Tout sauf bordure",
"Column widths": "Largeurs des colonnes",
"Formulas and number": "Formules et nombre",
"Values and number formats": "Valeurs et format de nombres",
"Substract": "Soustraire",
"Multiply": "Multiplier",
"Divide": "Diviser",
"Skip blanks": "Sauter les blancs",
"Transpose": "Transposer",
"Paste Link": "Insérer lien",
"Formulas and number formats": "Formules et formats de nombres",
"Myltiply": "Multiplier",
"Transponse": "Transposer",
"All": "Tous",
"Content Types": "Types de contenu",
"Values": "Valeurs",
"Styles": "Styles",
"Formats": "Formats",
"Conditional Formats": "Format conditionnel",
"Cell Metadata": "Métadonnée de cellule",
"Cancel": "Annuler",
"OK": "OK ",
//Name Manager Dialog
"Value": "Valeur",
"Refers To": "Fait référence à",
"Scope": "Portée",
"Name Manager": "Gérer les noms",
"Edit Name": "Modifier le nom",
"Save Range": "Enregistrer la plage",
"Names Scoped to Worksheet": "Noms limités à cette feuille",
"Names Scoped to Workbook": "Noms limités à ce classeur",
"Names With Errors": "Noms avec erreurs",
"Names Without Errors": "Noms sans erreur",
"Named formula couldn't be created": "La formule nommée n\'a pas pu être créée",
// Hyperlink
"follHLInvalidRef": "Référence non valide",
"follHLTmpDisabledRef": "Référence temporairement désactivée",
"follHLInvalidRng": "Il n'est pas possible d'accéder à l'adresse du lien hypertexte.",
"follHLInvalidSheet": "La feuille de calcul n\'existe pas.",
"follHLNamedRngUnsupport": "Le lien hypertexte contient un lien vers une plage de cellules avec noms - actuellement non supporté.",
"follHLInvalidFormat": "Le format du lien hypertexte est invalide.",
"follHLInvalidWB": "Il n'est pas possible de trouver et d'ouvrir le classeur indiqué par le lien hypertexte.",
"follHLInvalidDoc": "Il n'est pas possible de trouver et d'ouvrir le document indiqué par le lien hypertexte.",
"follHLInvalidURL": "L\'URL du lien hypertexte est invalide.",
"follHLTmpDisabledWB": "Les liens vers d\'autres classeurs ne fonctionnent pas dans ce mode d\'application.",
"follHLTmpDisabledWS": "Les liens vers d\'autres feuilles ne fonctionnent pas dans ce mode d\'application.",
"follHLInvTrgNRange": "Le plage cible nommé n\'existe pas.",
"follHLNotSuppInStandalone": "La cible du lien hypertexte n\'est pas supporté en mode standalone. Il ne peut être utilisés que dans Palo Studio.",
"HLCntxNewWin": "Ouvrir le lien dans une nouvelle fenêtre.",
"HLCntxNewTab": "Ouvrir le lien dans un nouvel onglet.",
"HLCntxRemove": "Supprimer le lien hypertexte",
"HLInvalidRefNotice": "Veuillez modifier pour le faire fonctionner correctement.",
//New Name Dialog
"Workbook": "Classeur",
"newNameDlg_WarningMsg": "Vous n'avez pas correctement indiqué les paramètres. <br>Veuillez corriger les paramètres et essayer à nouveau.",
"newNameDlg_NameWarningMsg": "Le nom indiqué n\'est pas valide.<br><br>La raison peut être :<br> - Le nom commence par une lettre ou un souligné<br> - Le nom contient un espace ou un autre signe non valide<br> - Le nom est en conflit avec le nom d\'un élément de la solution ou avec un autre nom d\'objet dans le classeur",
//Page Setup Dialog
"Header": "En-tête",
"Footer": "Pied de p.",
"Horizontally": "Horizontalement",
"Vertically": "Verticalement",
"Orientation": "Centrer sur la page",
"Custom Header": "En-tête personnalisé",
"Custom Footer": "Pied de page personnalisé",
"Print area": "Zone d'impression",
"Gridlines": "Quadrillage",
"Cell Errors As": "Cellules avec erreurs",
"Down, then over": "Première vers le bas",
"Over, then down": "Première à droite",
"Page order": "Ordre des pages",
"Adjust to": "Taille ",
"Fit to": "Ajuster",
"Page": "Page",
"Margins": "Marges",
"Header/Footer": "En-tête/Pied de page",
"(none)": "(Aucun)",
"Book": "Classeur",
"of": "de",
"Format text": "Format texte",
"Portrait": "Portrait",
"Landscape": "Paysage",
"Paper size": "Format du papier",
"Letter": "Format lettre",
"Print quality": "Qualité d'impression",
"First page": "Commencer la numérotation à",
//Custom Header Footer
"customHFLbl": "Pour formater le texte, sélectionnez le texte et cliquez ensuite sur le bouton Formet texte. <br>"+
"Pour insérer des numéros de page, la date, l'heure, des noms de fichier, des noms de feuille de calcul ou un chemin d'accès, positionnez le curseur dans la barre de traitement et cliquez sur le bouton souhaité.<br>"+
"Pour insérer une image, cliquez sur le bouton Insérer une image. <br><br>",
"Insert Page Number": "Insérer le numéro de page",
"Insert Number of Pages": "Insérer le nombre de pages",
"Insert Date": "Insérer la date",
"Insert Time": "Insérer l'heure",
"Insert File Name": "Insérer le nom du fichier",
"Insert Sheet Name": "Insérer le nom de la feuille de calcul",
"Insert Picture": "Insérer une image",
"Left section": "Section à gauche",
"Center section": "Section au milieu",
"Right section": "Section à droite",
// Suspend Mode
"suspModeMsg": "Le mode de designer est bloqué parce que le mode d\'utilisateur est ouvert dans une fenêtre.<br><br>Pour continuer, veuillez fermez cette fenêtre.",
"Suspend Mode": "Mode en pause",
// Form ComboBox Dialog
"Format ComboBox": "Formater la ComboBox",
"List Type": "Type de liste",
"Palo Subset": "Sous-ensemble Palo",
"Cell": "Cellule",
"Select Wizard type": "Choisissez le type d'assistant",
"WSS_FormComboBox_empty_source": "La source n\'est pas indiquée.",
"WSS_FormComboBox_empty_target": "La destination n\'est pas indiquée.",
"formel_inv_add": "Il n'est pas possible d'insérer l'élement formulaire.",
"formel_exists": "L\'élément \"{nom}\" existe déjà.",
"formel_nrange_exists": "Le nom de la plage cible \"{Nom}\" existe déjà.",
"formel_no_nrange": "Le nom de la plage cible \"{Name}\" n\'existe pas.",
"formel_inv_target": "La cellule cible ou la plage cible non valide.",
"formel_inv_target_sheet": "La feuille cible \"{name}\" n\'existe pas.",
"formel_add_wsel_err": "L\'insertion de l\'élément formulaire à la mémoire WSEl a échoué",
"formel_proc_err": "Erreur de l'élément formulaire",
"formel_edit": "Modifier {type}",
"formel_delete": "Supprimer {type}",
"formel_assign_macro_err": "Impossible d'assigner une macro.",
"formel_no_el": "L\'élément cible n\'a pas été trouvé.",
"ComboBox Name": "Nom de la ComboBox",
"Subset": "Sous-ensemble",
"checkbox_inv_state": "La Check Box a un statut invalide.",
"CheckBox Name": "Nom de la Check Box",
"Unchecked": "Non coché",
"Checked": "Coché",
"Mixed": "Mélangé",
"Format Control": "Contrôle format",
"Checkbox Label": "Libellé de la Check Box",
"Button Label": "Libellé du bouton",
"Button Name": "Nom du bouton",
"Assign Macro": "Assigner une macro",
"Application Error": "Erreur d'application",
"noWBtoSwitch": "Il n'est pas possible de basculer vers la feuille sélectionnée.",
"noWBtoClose": "Il n'est pas possible de de fermer le classeur sélectionné.",
// Load Workbook messages
"errLoadWB_intro": "Il n'est pas possible d'ouvrir le classeur.",
"errLoadWB_noNode": "La connexion n\'a pas été trouvée.",
"errLoadWB_noFile": "Le fichier n\'existe pas.",
"errLoadWB_selErr": "Il n'est pas possible de sélectionner un classeur déjà ouvert.",
"errLoadWB_coreErr": "Le système ne peut pas ouvrir le classeur sélectionné",
"errLoadWB_noRights": "Droits d'accès insuffisants.",
"errLoadWB_cyclicDep": "Cyclic dépendance existe entre le classeur sélectionné et ses ressources.",
// PALO Import Wizard
"PALO Import Wizard": "Assistant d'import Palo",
"impPalo_msgWrongType": "Le chemin d\'accès complet vers le fichier TXT ou CSV doit être présent dans ce champ !",
"impPalo_msgFieldBlank": "Veuillez choisir un fichier !",
"Next": "Suivant",
"Decimalpoint": "Point décimal",
"_msg: Palo Import 1": "Cet assistant va vous permettre de parcourir les enregistrements dans la première ligne de la feuille active.",
"_msg: Palo Import 21": "A cette étape, vous allez indiquer le fichier texte à importer.",
"_msg: Palo Import 3": "Cliquez sur suivant pour voir l'enregistrement suivant ou terminer pour parcourir tous les enregistrements.",
"Select the sourcefile (*.txt, *.csv)": "Choisissez le fichier source (*.txt, *.csv).",
"Flat Textfile (*.txt, *.csv)": "Fichier texte (*.txt, *.csv)",
"ODBC Query": "Requête ODBC",
"Internal Loop (increse A1 until error in B1)": "Boucle interne (augmente A1 jusqu'à provoquer une erreur en B1)",
"Tab": "Tabulation",
"Comma": "Virgule",
"Semicolon": "Point virgule",
"Blank": "Blanc",
"User-defined": "Défini par l'utilisateur",
"Header exists": "En-têtes existants",
"Step by Step": "Pas à pas",
"_msg: PaloImport Wait": "Veuillez patienter, les données sont importées dans la feuille !",
"Importing": "L\'import est en cours",
"Finish": "Terminé",
"_msg: PaloImport Upload": "Les données PALO ont été importées",
"Uploading": "Chargement",
// Function arguments dialog: funcArgs.js
"_error: fnc_desc": "Erreur lors du chargement de la description de la fonction",
"fnc_no_params": "La fonction n\'a pas de paramètres",
"Function Arguments": "Arguments de la fonction",
//Edit Macro
"New Module": "Nouveau module",
"Add New Module": "Ajouter un nouveau module",
"Find": "Rechercher",
"Modules Repository": "Référentiel de Modules",
"Error Renaming Module": "Erreur en renommant le module",
"rename_module_error_msg": "Erreur_renommant_le_module",
"Macro Editor": "Editeur de Macro",
"Rename Module": "Renommer le module",
"Delete Module": "Supprimer le module",
"Module": "Module",
"edit_macro_no_module_selected_err": "edition_macro_erreur_aucun_module_sélectionné",
"Error": "Erreur",
//autoRefresh.js
"Refresh every": "Actualiser toutes les",
"seconds": "secondes",
"Auto Refresh": "Actualisation automatique",
// Autosave
"File not saved": "Le fichier n\'est pas été enregistré",
"autosave_msg": "Voulez-vous enregistrer vos modifications?",
"Open and Repair": "Ouvrir et réparer",
"Size": "Taille ",
"date_format": "d/m/Y H:i:s",
"astype_orig": "Ouvrir le fichier original (Date: {date} / Taille: {size})",
"astype_recov": "Ouvrir le fichier de récupération de la liste:",
"as_msg": "Le classeur n\'a pas été fermé correctement. Comment voulez-vous procéder?",
// Quick Publish
"_QP_unsaved_warning": "Le document non enregistré ne peut pas être publié. Souhaitez-vous enregistrer le document maintenant?",
"_QP_error": "La publication n\'a pas fonctionné. Veuillez essayer de nouveau",
"Report name": "Nom du rapport",
"_QP_double_warning": "Un rapport nommé <b>{rName}</b> existe déjà dans le dossier sélectionné. Veuillez le renommer ou utiliser le nom suggéré.",
"_QP_noSelection": "Veuillez sélectionnez le dossier où le classeur devrait être publié.",
"Group": "Groupe",
"Hierarchy": "Hiérarchie",
"Publish": "Publication",
"_QP_directions": "Choisissez le dossier où vous souhaitez publier le classeur.",
"_QP_success": "Le classeur a été publié avec succès!",
"Report must have name": "Le rapport doit porter un nom",
//ribbon.js
"Home":"Accueil",
"View": "Affichage",
"New<br>document":"Nouveau<br>document",
"Create new document":"Créer un nouveau document",
"Open":"Ouvrir",
"Recent":"Dernières",
"Open document":"Ouvrir un document",
"Save":"Enregistrer",
"Save document":"Enregistrer le document",
"Export":"Export ",
"XLSX":"XLSX ",
"PDF":"PDF ",
"HTML":"HTML ",
"Save As":"Enregistrer sous",
"Save As document":"Enregistrer comme un document",
"Close":"Fermer",
"Operation":"Opération",
"Undo":"Annuler",
"Redo":"Rétablir",
"Clipboard":"Presse-papiers",
"Paste":"Coller",
"Paste Special":"Collage spécial",
"Cut":"Couper",
"Copy":"Copier",
"Format Painter":"Reproduire la mise en forme",
"Bold":"Gras",
"Italic":"Italique",
"Bottom Border":"Bordure inférieure",
"Top Border": "Bordure supérieure",
"Left Border": "Bordure gauche",
"Right Border": "Bordure droite",
"All Borders": "Toutes les bordures",
"Outside Borders": "Bordures extérieures",
"Thick Outside Border": "Bordure extérieure épaisse",
"No Border": "Aucune bordure",
"Top and Bottom Border": "Bordure en haut et en bas",
"Thick Bottom Border": "Bordure épaisse en bas",
"Top and Thick Bottom Border": "Bordure simple en haut et épaisse en bas",
"More Borders": "Plus de bordure",
"Fill Color": "Couleur de remplissage",
"Font Color":"Couleur de police",
"Alignment":"Alignement",
"Left":"À gauche",
"Align Text Left":"Aligner le texte à gauche",
"Center":"Au centre",
"Align Text Center":"Aligner le texte au centre",
"Right":"À droite",
"Merge Cells":"Fusionner les cellules",
"Unmerge Cells":"Annuler la fusion des cellules",
"Cells":"Cellules",
"Insert Rows":"Insérer des lignes",
"Insert Columns":"Insérer des colonnes",
"Insert Sheet":"Insérer une feuille",
"Delete":"Supprimer",
"Delete Sheet":"Supprimer la feuille",
"Format":"Format ",
"AutoFit Row Height":"Ajustement automatique des lignes",
"Column Width":"Largeur de colonne",
"AutoFit Column Width":"Ajustement automatique des colonnes",
"Rename Sheet":"Renommer la feuille",
"Move or Copy Sheet":"Déplacer où copier la feuille",
"Lock<br>Unlock":"Verouillée<br>déverrouillée",
"Conditional<br>Formating":"Mise en forme<br>conditionnelle",
"New Rule":"Nouvelle règle",
"Clear Rules":"Supprimer des règles",
"Clear Rules from Selected Cells":"Supprimer les règles des cellules sélectionnées",
"Clear Rules from Entire Sheet":"Supprimer les règles de la feuille entière",
"Manage Rules":"Gérer les règles",
"Editing":"Modifier",
"Clear All":"Effacer tout",
"Clear Formats":"Effacer le format",
"Clear Contents":"Effacer le contenu",
"Quick View":"Aperçu rapide",
"Designer Preview": "Aperçu Designer",
"User Mode":"Mode d\'utilisateur",
"Open User Mode":"Ouvrir le mode d'utilisateur",
"Insert":"Insertion",
"Ilustrations":"Illustrations",
"Picture":"Image",
"Links":"Liens",
"Hyperlink":"Hyperlien",
"Charts":"Graphiques",
"Chart":"Graphique",
"Micro Chart":"Micrographique",
"Page Layout":"Mise en page",
"Themes":"Thèmes",
"Theme":"Thème",
"Blue (default)":"Bleu (défaut)",
"Gray":"Gris",
"Dark":"Sombre",
"Page Setup":"Mise en page",
"Print<br>Preview":"Aperçu<br>avant impression",
"Formulas":"Formules",
"Function":"Fonction",
"Insert<br>Funciton":"Insérer<br>fonction",
"Defined Names":"Noms définis",
"Name<br> Manager":"Gestion<br>des noms",
"Define Name":"Définir un nom",
"Calculation":"Calcul",
"Refresh<br>Data":"Actualiser les données",
"Auto - Refresh Data":"Actualiser les données automatiquement",
"Show/Hide":"Afficher/Masquer",
"Toolbars":"Barres d'outils",
"Formula Bar":"Barre de formule",
"Status Bar":"Barre d'état",
"Window":"Fenêtre",
"Arrange <br>All":"Réorganiser<br>tous",
"Hide":"Masquer",
"Unhide":"Démasquer",
"Developer":"Développeurs",
"Controls":"Contrôles",
"Macro <br>Editor":"Editeur <br>Macro",
"Combo Box":"Liste Déroulante",
"Check Box":"Case à cocher",
"Button":"Bouton",
"Dyna Ranges":"Dyna_Ranges",
"Horizontal <br> Dyna Range":"Dyna Range <br> Horizontal",
"Vertical <br> Dyna Range":"Dyna Range <br> Vertical",
"Create or Modify Reports":"Créer ou modifier les rapports",
"Paste <br>View":"Créer<br>une vue",
"Paste Elements":"Coller des éléments",
"Paste Subset":"Coller un sous-ensemble",
"Paste Function":"Fonction d'accès aux données",
"Control and Modify Palo":"Contrôler et modifier Palo",
"Modeller":"Outil de modélisation",
"Import Data":"Import de données",
"Save as Snapshot":"Sauvegarder comme instantané",
"Info":"Info",
"Wiki Palo":"Wiki Palo",
"About Palo":"À propos de Palo",
"Open documents": "Ouvrir des documents",
"Help": "Aide",
"_bold": "_gras",
"_italic": "_italique",
"Data labels orientation": "Orientation des étiquettes de données",
"Rotate all text 90": "Rotation 90 du texte",
"Rotate all text 270": "Rotation 270 du texte",
"Custom angle": "Angle spécifique",
"Palo_get_paste_view_init": "La vue collée n\'a pas été correctement stockée. Essayez de la recréer.",
"Vertical Dynarange": "Vertical_DynaRange",
"Horizontal Dynarange": "Horizontal_DynaRange",
"CheckBox": "Case à cocher",
"Variables": "Variables",
"Private": "Privé",
"Current Value": "Valeur Courante",
"Used Variables": "Variables utilisées",
"invalidContext": "L\'application a essayé d\'utiliser un contexte inexistant.",
"Bring Forward": "Déplacer d\'un niveau vers l\'avant",
"Bring to Front": "Déplacer vers l\'avant",
"Please select rule to edit": "Veuillez sélectionner la règle à modifier.",
"Send Backward": "Déplacer d\'un niveau vers l\'arrière",
"Send to Back": "Déplacer vers l\'arrière",
"save_as_override_msg": "Le fichier <b>{fileName}</b> existe déjà. Voulez-vous remplacer le fichier existant?",
"execHLInvRange": "La cellule ou la plage du lien hypertexte n\'est pas valide.",
"#N/A": "#N/A",
"Bold Italic": "Gras Italique",
"Cell/Range": "Cellule//Gamme",
"Control": "Contrôle",
"First": "Première",
"Inside": "A l'intérieur",
"Last": "Dernier",
"Lose": "Perte",
"Micro Chart Type": "Type",
"Neg. Values": "Valeurs nég",
"None": "Aucun",
"Open Recent": "Classeurs dernières",
"Outline": "A l'extérieur",
"Pos. Values": "Valeurs pos.",
"Reference": "Référence",
"Regular": "Régulier",
"Tie": "Équilibre",
"Win": "Profit",
"blank": "Laisser vide",
"displayed": "Imprimer",
"normal size": "de la taille normale",
"page(s) wide by": "page(s) en largeur sur",
"tall": "en hauteur",
"wsel_inv_target": "La cellule cible ou la plage cible n\'est pas valide.",
"wsel_inv_target_sheet": "La feuille cible \"{name}\" n\'existe pas.",
"wsel_nrange_exists": "Le zone cible indiquée \"{name}\" existe déjà.",
"Widgets": "Widgets",
"Custom Widget": "Widget personnalisé",
"widget_exists": "Widget \"{name}\" existe déjà.",
"widget_add_wsel_err": "Adjonction de Widget au stockage WSEl était echoué.",
"widget_edit": "Éditer Widget",
"widget_delete": "Supprimer Widget",
"WSS_Forms_empty_name": "Le nom n\'est pas précisé",
"WSS_Widget_empty_content": "Le contenu des Widgets n\'est pas spécifié. S\'il vous plaît entrez le code HTML ou l\'URL.",
"New name": "Nouveau nom",
"inset_name_err_msg": "La formule nommée n'a pas pu être créé.",
"currCoord_validate_err_msg": "Vous devez entrer une référence valide où vous voulez aller, ou tapez un nom valide pour la sélection.",
"Show borders in User mode": "Afficher les bordures en mode utilisateur.",
"new_folder_name_warrning": "Le nom de dossier <b> {new_name} </b> existe déjà. Type un autre nom pour le dossier.",
"imp_success_msg": "Le fichier a été importé avec succès.",
"Import log": "Journal d\'importation",
"floatingElement_wrongSizePos": "La taille ou la position de l\'élément n\'est pas valide. Veuillez vérifier les valeurs de la taille et de la position dans le cadre.",
"invalid_chart_sizepos": "La taille ou la position du graphique n\'est pas valide. Veuillez entrer des valeurs valides.",
"invalid_picture_size": "La taille ou la position de l\'image n\'est pas valide. Veuillez entrer des valeurs valides.",
"fopperLic": "Le licence pour imprimer PDF.",
"License could not be checked": "La licence n\'a pas pu être vérifiée.",
"License could not be found.": "La licence n\'a pas pu être trouvée.",
"License could not be read.": "La licence n\'a pas pu être lu.",
"License is not valid.": "La licence n\'est pas valide.",
"no_perm_err_msg": "Vous n\'avez pas la permission pour cette opération.",
"Zero suppression": "Omission du zéro",
"Lock": "Verouiller",
"Unlock": "Déverrouiller",
"Vertical DynaRange": "Vertical DynaRange",
"Horizontal DynaRange": "Horizontal DynaRange",
"_error: empty targ name": "La cible du lien hypertexte est vide. Veuillez sélectionner ou entrer cible valide.",
"Select target or <br />input frame name": "Options des trames",
"Format Widget": "Format Widget",
"Widget Name": "Nom de Widget",
"macro_preselection_err_msg": "La macro affectée n\'est pas trouvé.<br>La macro affectée est renommé ou supprimé.<br>Veuillez réaffecter la macro à nouveau!",
"Content": "Contenu",
"errLoadFS_intro": "Impossible de charger le frameset.",
"errLoadFS_noNode": "Impossible de trouver le frameset.",
"Format painter": "Reproduire la mise en forme",
"no_uxpc_err_msg": "Impossible d\'obtenir le privilège du système local.",
"no_file_err_msg": "Impossible d\'accéder à le fichier local.",
"Size & Position": "Taille et position",
"Height": "Hauteur",
"errFrameSave_noAccess": "Impossible d\'enregistrer le classeur \"{name}\" dans le frame \"{frame}\" en raison de\ndroits d\'accès insuffisants.",
"macro_selection_wrg_msg": "Impossible d\'attribuer macro. Votre sélection est vide.<br>Veuillez sélectionner un macro dans la liste, et essayez à nouveau.",
"Show legend": "Afficher la légende",
"Bottom": "Dessous",
"Top Right": "En haut à droite",
"Show the legend without overlapping the chart": "Afficher la légende sans chevauchement du graphique",
"Minimum value is 10": "La valeur minimale est 10",
"Not correct format": "Le format n\'est pas correct",
"min 10": "min 10",
"Target_formElems": "Cible",
"Convert": "Convertir",
"Show log": "Afficher le journal.",
"All Workbook Files": "Tous les classeur.",
"fnArg_multiple": "multiples",
"fnArg_number": "nombre",
"fnArg_sequence": "séquence",
"fnArg_any": "tout",
"fnArg_logical": "logique",
"fnArg_reference": "référence",
"fnArg_text": "texte"
};
| fschaper/netcell | ui/docroot/ui/wss/base/i18n/loc_fr_FR.js | JavaScript | gpl-2.0 | 53,246 |
public class TreeNodeConverter : System.ComponentModel.TypeConverter
{
// Constructors
public TreeNodeConverter() {}
// Methods
public virtual bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, Type destinationType) {}
public virtual object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) {}
public bool CanConvertFrom(Type sourceType) {}
public bool CanConvertTo(Type destinationType) {}
public object ConvertFrom(object value) {}
public virtual object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {}
public object ConvertFromInvariantString(string text) {}
public virtual object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary propertyValues) {}
public virtual bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) {}
public virtual System.ComponentModel.PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributes) {}
public virtual bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) {}
public virtual System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) {}
public virtual bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) {}
public virtual bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) {}
public virtual bool IsValid(System.ComponentModel.ITypeDescriptorContext context, object value) {}
public virtual bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType) {}
public object ConvertFromInvariantString(System.ComponentModel.ITypeDescriptorContext context, string text) {}
public object ConvertFromString(string text) {}
public object ConvertFromString(System.ComponentModel.ITypeDescriptorContext context, string text) {}
public object ConvertFromString(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, string text) {}
public object ConvertTo(object value, Type destinationType) {}
public string ConvertToInvariantString(object value) {}
public string ConvertToInvariantString(System.ComponentModel.ITypeDescriptorContext context, object value) {}
public string ConvertToString(object value) {}
public string ConvertToString(System.ComponentModel.ITypeDescriptorContext context, object value) {}
public string ConvertToString(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {}
public object CreateInstance(System.Collections.IDictionary propertyValues) {}
public bool GetCreateInstanceSupported() {}
public System.ComponentModel.PropertyDescriptorCollection GetProperties(object value) {}
public System.ComponentModel.PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value) {}
public bool GetPropertiesSupported() {}
public System.Collections.ICollection GetStandardValues() {}
public bool GetStandardValuesExclusive() {}
public bool GetStandardValuesSupported() {}
public bool IsValid(object value) {}
public Type GetType() {}
public virtual string ToString() {}
public virtual bool Equals(object obj) {}
public virtual int GetHashCode() {}
}
| Pengfei-Gao/source-Insight-3-for-centos7 | SourceInsight3/NetFramework/TreeNodeConverter.cs | C# | gpl-2.0 | 3,537 |
<?php
/*
Template Name: 近期留言
*/
?>
<?php get_header(); ?>
<article id="primary" class="site-content">
<section class="content">
<?php while ( have_posts() ) : the_post(); ?>
<div id="message" class="message-page">
<ul>
<?php
$show_comments = 45;
$my_email = get_bloginfo ('admin_email');
$i = 1;
$comments = get_comments('number=200&status=approve&type=comment');
foreach ($comments as $my_comment) {
if ($my_comment->comment_author_email != $my_email) {
?>
<li>
<a href="<?php echo get_permalink($my_comment->comment_post_ID); ?>#comment-<?php echo $my_comment->comment_ID; ?>" title="发表在 > <?php echo get_the_title($my_comment->comment_post_ID); ?>" >
<?php echo get_avatar($my_comment->comment_author_email,64); ?>
<strong><span class="comment_author"><?php echo $my_comment->comment_author; ?></span></strong>
<?php echo convert_smilies($my_comment->comment_content); ?>
</a>
</li>
<?php
if ($i == $show_comments) break;
$i++;
}
}
?>
</ul>
</div>
<!-- #message -->
<?php endwhile; ?>
</section>
<!-- #content -->
</article>
<!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?> | scuxiayiqian/wordpress | wp-content/themes/Ality/template-message.php | PHP | gpl-2.0 | 1,282 |
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
package com.mediatek.ngin3d.demo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class DemolistGlo3D extends Activity {
private ListView mListView;
private MyAdapter mMyAdapter;
public List<String> mListTag = new ArrayList<String>();
private List<String> mData = new ArrayList<String>();
private HashMap<String, Object> mImageMap = new HashMap<String, Object>();
private static final String packageName = "com.mediatek.ngin3d.demo";
private String[] mGloActivity3 = {
"Glo3DDemo",
"ProjectionsDemo",
"Glo3DTextureDemo",
"Glo3DAntiAliasingDemo",
"Glo3DScaleRotationDemo",
"EularAngleDemo",
"EulerOrderDemo",
"OptimusPrime",
"CustomMaterials",
"LightDemo"
};
/***
* this method to avoid loading the picture from Resource caused by OOM
*
* @param context
* @param resId
* @return Bitmap
*/
public static Bitmap readBitMap(Context context, int resId) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is, null, opt);
}
private void initImageMap() {
mImageMap.clear();
mImageMap.put("Glo3DDemo", R.drawable.demo_glo3ddemo);
mImageMap.put("ProjectionsDemo", R.drawable.demo_projectionsdemo);
mImageMap.put("Glo3DTextureDemo", R.drawable.demo_glo3dtexturedemo);
mImageMap.put("Glo3DAntiAliasingDemo", R.drawable.demo_glo3dantialiasingdemoapp);
mImageMap.put("Glo3DScaleRotationDemo", R.drawable.demo_glo3dscalerotationdemoapp);
mImageMap.put("EularAngleDemo", R.drawable.demo_eularabgledemoapp);
mImageMap.put("StereoSpace3DDemo", R.drawable.demo_stereo3ddemoapp);
mImageMap.put("EulerOrderDemo", R.drawable.demo_eulerorderdemoapp);
mImageMap.put("OptimusPrime", R.drawable.demo_optimusprimedemoapp);
mImageMap.put("CustomMaterials", R.drawable.demo_custommaterials);
mImageMap.put("LightDemo", R.drawable.demo_lightdemo);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mListView = (ListView) findViewById(R.id.list);
mMyAdapter = new MyAdapter(this,
android.R.layout.simple_expandable_list_item_1, getData());
mListView.setAdapter(mMyAdapter);
initImageMap();
mListView.setOnItemClickListener(new ListView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
try {
startActivity(new Intent(getBaseContext(), Class.forName(packageName + "."
+ mData.get(position))));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
private Object getImageFromMap(Object key) {
return mImageMap.get(key);
}
private List<String> getData() {
mListTag.add("Glo");
mData.add("Glo");
for (int i = 0; i < mGloActivity3.length; i++) {
mData.add(mGloActivity3[i]);
}
return mData;
}
class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int position) {
return !mListTag.contains(getItem(position));
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (mListTag.contains(getItem(position))) {
view = LayoutInflater.from(getContext()).inflate(R.layout.list_item_tag, null);
} else {
view = LayoutInflater.from(getContext()).inflate(R.layout.list_item, null);
if (getImageFromMap(getItem(position)) != null) {
Bitmap bmp = readBitMap(this.getContext(),
(Integer) getImageFromMap(getItem(position)));
ImageView imageView = (ImageView) view.findViewById(R.id.group_list_item_image);
imageView.setImageBitmap(bmp);
}
}
TextView textView = (TextView) view.findViewById(R.id.group_list_item_text);
textView.setText(getItem(position));
return view;
}
}
}
| rex-xxx/mt6572_x201 | mediatek/frameworks/opt/ngin3d/demos/App/ngin3dDemo/src/com/mediatek/ngin3d/demo/DemolistGlo3D.java | Java | gpl-2.0 | 7,673 |
__author__ = 'Artur Barseghyan <artur.barseghyan@gmail.com>'
__copyright__ = 'Copyright (c) 2013 Artur Barseghyan'
__license__ = 'GPL 2.0/LGPL 2.1'
__all__ = ('FIT_METHOD_CROP_SMART', 'FIT_METHOD_CROP_CENTER', 'FIT_METHOD_CROP_SCALE',
'FIT_METHOD_FIT_WIDTH', 'FIT_METHOD_FIT_HEIGHT', 'DEFAULT_FIT_METHOD', 'FIT_METHODS_CHOICES',
'FIT_METHODS_CHOICES_WITH_EMPTY_OPTION', 'IMAGES_UPLOAD_DIR')
from django.utils.translation import ugettext_lazy as _
FIT_METHOD_CROP_SMART = 'smart'
FIT_METHOD_CROP_CENTER = 'center'
FIT_METHOD_CROP_SCALE = 'scale'
FIT_METHOD_FIT_WIDTH = 'fit_width'
FIT_METHOD_FIT_HEIGHT = 'fit_height'
DEFAULT_FIT_METHOD = FIT_METHOD_CROP_CENTER
FIT_METHODS_CHOICES = (
(FIT_METHOD_CROP_SMART, _("Smart crop")),
(FIT_METHOD_CROP_CENTER, _("Crop center")),
(FIT_METHOD_CROP_SCALE, _("Crop scale")),
(FIT_METHOD_FIT_WIDTH, _("Fit width")),
(FIT_METHOD_FIT_HEIGHT, _("Fit height")),
)
FIT_METHODS_CHOICES_WITH_EMPTY_OPTION = [('', '---------')] + list(FIT_METHODS_CHOICES)
IMAGES_UPLOAD_DIR = 'dash-image-plugin-images'
| georgistanev/django-dash | src/dash/contrib/plugins/image/defaults.py | Python | gpl-2.0 | 1,080 |
--TEST--
Test arsort() function : usage variations - unexpected values for 'array_arg' argument
--FILE--
<?php
/* Prototype : bool arsort(array &array_arg [, int sort_flags])
* Description: Sort an array and maintain index association
Elements will be arranged from highest to lowest when this function has completed.
* Source code: ext/standard/array.c
*/
/*
* testing arsort() by providing different unexpected values for array argument with following flag values.
* 1. flag value as defualt
* 2. SORT_REGULAR - compare items normally
* 3. SORT_NUMERIC - compare items numerically
* 4. SORT_STRING - compare items as strings
*/
echo "*** Testing arsort() : usage variations ***\n";
// get an unset variable
$unset_var = 10;
unset ($unset_var);
// resource variable
$fp = fopen(__FILE__, "r");
//array of values with indices to iterate over
$unexpected_values = array (
// int data
0 => 0,
1 => 1,
2 => 12345,
3 => -2345,
// float data
4 => 10.5,
5 => -10.5,
6 => 10.5e3,
7 => 10.6E-2,
8 => .5,
// null data
9 => NULL,
10 => null,
// boolean data
11 => true,
12 => false,
13 => TRUE,
14 => FALSE,
// empty data
15 => "",
16 => '',
// string data
17 => "string",
18 => 'string',
// object data
19 => new stdclass(),
// undefined data
20 => @undefined_var,
// unset data
21 => @unset_var,
// resource variable
22 => $fp
);
// loop though each element of the array and check the working of arsort()
// when $array arugment is supplied with different values from $unexpected_values
echo "\n-- Testing arsort() by supplying different unexpected values for 'array' argument --\n";
echo "\n-- Flag values are defualt, SORT_REGULAR, SORT_NUMERIC, SORT_STRING --\n";
$counter = 1;
for($index = 0; $index < count($unexpected_values); $index ++) {
echo "-- Iteration $counter --\n";
$value = $unexpected_values [$index];
var_dump( arsort($value) ); // expecting : bool(false)
var_dump( arsort($value, SORT_REGULAR) ); // expecting : bool(false)
var_dump( arsort($value, SORT_NUMERIC) ); // expecting : bool(false)
var_dump( arsort($value, SORT_STRING) ); // expecting : bool(false)
$counter++;
}
echo "Done";
?>
--EXPECTF--
*** Testing arsort() : usage variations ***
-- Testing arsort() by supplying different unexpected values for 'array' argument --
-- Flag values are defualt, SORT_REGULAR, SORT_NUMERIC, SORT_STRING --
-- Iteration 1 --
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 2 --
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 3 --
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 4 --
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, integer given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 5 --
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 6 --
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 7 --
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 8 --
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 9 --
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, double given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 10 --
Warning: arsort() expects parameter 1 to be array, null given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, null given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, null given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, null given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 11 --
Warning: arsort() expects parameter 1 to be array, null given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, null given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, null given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, null given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 12 --
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 13 --
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 14 --
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 15 --
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, boolean given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 16 --
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 17 --
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 18 --
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 19 --
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 20 --
Warning: arsort() expects parameter 1 to be array, object given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, object given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, object given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, object given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 21 --
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 22 --
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, string given in %sarsort_variation1.php on line %d
bool(false)
-- Iteration 23 --
Warning: arsort() expects parameter 1 to be array, resource given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, resource given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, resource given in %sarsort_variation1.php on line %d
bool(false)
Warning: arsort() expects parameter 1 to be array, resource given in %sarsort_variation1.php on line %d
bool(false)
Done | ssanglee/capstone | php-5.4.6/ext/standard/tests/array/arsort_variation1.phpt | PHP | gpl-2.0 | 13,477 |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
namespace Org.BouncyCastle.Utilities.Date
{
public sealed class DateTimeObject
{
private readonly DateTime dt;
public DateTimeObject(
DateTime dt)
{
this.dt = dt;
}
public DateTime Value
{
get { return dt; }
}
public override string ToString()
{
return dt.ToString();
}
}
}
#endif
| JohnMalmsteen/mobile-apps-tower-defense | Assets/Best HTTP (Pro)/BestHTTP/SecureProtocol/util/date/DateTimeObject.cs | C# | gpl-2.0 | 406 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Layman is a complete library for the operation and maintainance
on all gentoo repositories and overlays
"""
import sys
try:
from layman.api import LaymanAPI
from layman.config import BareConfig
from layman.output import Message
except ImportError:
sys.stderr.write("!!! Layman API imports failed.")
raise
class Layman(LaymanAPI):
"""A complete high level interface capable of performing all
overlay repository actions."""
def __init__(self, stdout=sys.stdout, stdin=sys.stdin, stderr=sys.stderr,
config=None, read_configfile=True, quiet=False, quietness=4,
verbose=False, nocolor=False, width=0, root=None
):
"""Input parameters are optional to override the defaults.
sets up our LaymanAPI with defaults or passed in values
and returns an instance of it"""
self.message = Message(out=stdout, err=stderr)
self.config = BareConfig(
output=self.message,
stdout=stdout,
stdin=stdin,
stderr=stderr,
config=config,
read_configfile=read_configfile,
quiet=quiet,
quietness=quietness,
verbose=verbose,
nocolor=nocolor,
width=width,
root=root
)
LaymanAPI.__init__(self, self.config,
report_errors=True,
output=self.config['output']
)
return
| jmesmon/layman | layman/__init__.py | Python | gpl-2.0 | 1,585 |
package vistas.actores;
import java.awt.Color;
import java.awt.Graphics;
public class ActorObject extends Actor {
@Override
public void dibujar(Graphics g) {
g.setColor(Color.white);
g.drawRect (20, 20, 10, 10);
}
}
| algo3-2015-fiuba/algocraft | src/vistas/actores/ActorObject.java | Java | gpl-2.0 | 230 |
<?php
/*
* @package MijoShop
* @copyright 2009-2013 Mijosoft LLC, mijosoft.com
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
* @license GNU/GPL based on AceShop www.joomace.net
*/
// No Permission
defined('_JEXEC') or die('Restricted access');
class ModelCatalogDownload extends Model {
public function addDownload($data) {
$this->db->query("INSERT INTO " . DB_PREFIX . "download SET filename = '" . $this->db->escape($data['filename']) . "', mask = '" . $this->db->escape($data['mask']) . "', remaining = '" . (int)$data['remaining'] . "', date_added = NOW()");
$download_id = $this->db->getLastId();
foreach ($data['download_description'] as $language_id => $value) {
$this->db->query("INSERT INTO " . DB_PREFIX . "download_description SET download_id = '" . (int)$download_id . "', language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "'");
}
}
public function editDownload($download_id, $data) {
if (!empty($data['update'])) {
$download_info = $this->getDownload($download_id);
if ($download_info) {
$this->db->query("UPDATE " . DB_PREFIX . "order_download SET `filename` = '" . $this->db->escape($data['filename']) . "', mask = '" . $this->db->escape($data['mask']) . "', remaining = '" . (int)$data['remaining'] . "' WHERE `filename` = '" . $this->db->escape($download_info['filename']) . "'");
}
}
$this->db->query("UPDATE " . DB_PREFIX . "download SET filename = '" . $this->db->escape($data['filename']) . "', mask = '" . $this->db->escape($data['mask']) . "', remaining = '" . (int)$data['remaining'] . "' WHERE download_id = '" . (int)$download_id . "'");
$this->db->query("DELETE FROM " . DB_PREFIX . "download_description WHERE download_id = '" . (int)$download_id . "'");
foreach ($data['download_description'] as $language_id => $value) {
$this->db->query("INSERT INTO " . DB_PREFIX . "download_description SET download_id = '" . (int)$download_id . "', language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "'");
}
}
public function deleteDownload($download_id) {
$this->db->query("DELETE FROM " . DB_PREFIX . "download WHERE download_id = '" . (int)$download_id . "'");
$this->db->query("DELETE FROM " . DB_PREFIX . "download_description WHERE download_id = '" . (int)$download_id . "'");
}
public function getDownload($download_id) {
$query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "download d LEFT JOIN " . DB_PREFIX . "download_description dd ON (d.download_id = dd.download_id) WHERE d.download_id = '" . (int)$download_id . "' AND dd.language_id = '" . (int)$this->config->get('config_language_id') . "'");
return $query->row;
}
public function getDownloads($data = array()) {
$sql = "SELECT * FROM " . DB_PREFIX . "download d LEFT JOIN " . DB_PREFIX . "download_description dd ON (d.download_id = dd.download_id) WHERE dd.language_id = '" . (int)$this->config->get('config_language_id') . "'";
if (!empty($data['filter_name'])) {
$sql .= " AND dd.name LIKE '" . $this->db->escape($data['filter_name']) . "%'";
}
$sort_data = array(
'dd.name',
'd.remaining'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY dd.name";
}
if (isset($data['order']) && ($data['order'] == 'DESC')) {
$sql .= " DESC";
} else {
$sql .= " ASC";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->rows;
}
public function getDownloadDescriptions($download_id) {
$download_description_data = array();
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "download_description WHERE download_id = '" . (int)$download_id . "'");
foreach ($query->rows as $result) {
$download_description_data[$result['language_id']] = array('name' => $result['name']);
}
return $download_description_data;
}
public function getTotalDownloads() {
$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "download");
return $query->row['total'];
}
}
?> | Quartermain/providores | components/com_mijoshop/opencart/admin/model/catalog/download.php | PHP | gpl-2.0 | 4,560 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-08-21 18:59
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('dispatch', '0017_subsections'),
]
operations = [
migrations.CreateModel(
name='Podcast',
fields=[
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
('slug', models.SlugField(unique=True)),
('title', models.CharField(max_length=255)),
('description', models.TextField()),
('author', models.CharField(max_length=255)),
('owner_name', models.CharField(max_length=255)),
('owner_email', models.EmailField(max_length=255)),
('category', models.CharField(max_length=255)),
('image', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='dispatch.Image')),
],
),
migrations.CreateModel(
name='PodcastEpisode',
fields=[
('id', models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False)),
('title', models.CharField(max_length=255)),
('description', models.TextField()),
('author', models.CharField(max_length=255)),
('duration', models.PositiveIntegerField(null=True)),
('published_at', models.DateTimeField()),
('explicit', models.CharField(choices=[(b'no', b'No'), (b'yes', b'Yes'), (b'clean', b'Clean')], default=b'no', max_length=5)),
('file', models.FileField(upload_to=b'podcasts/')),
('type', models.CharField(default='audio/mp3', max_length=255)),
('image', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='dispatch.Image')),
('podcast', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='dispatch.Podcast')),
],
),
]
| ubyssey/dispatch | dispatch/migrations/0018_podcasts.py | Python | gpl-2.0 | 2,099 |
/****************************************************************************
**
** This file is part of the Qtopia Opensource Edition Package.
**
** Copyright (C) 2008 Trolltech ASA.
**
** Contact: Qt Extended Information (info@qtextended.org)
**
** This file may be used under the terms of the GNU General Public License
** versions 2.0 as published by the Free Software Foundation and appearing
** in the file LICENSE.GPL included in the packaging of this file.
**
** Please review the following information to ensure GNU General Public
** Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html.
**
**
****************************************************************************/
#include "qtmailwindow.h"
#include "statusdisplay.h"
#include "writemail.h"
#include <qtopiaipcenvelope.h>
#include <qtopiaapplication.h>
#include <qdatetime.h>
#include <qtimer.h>
#include <QDebug>
#include <QStackedWidget>
QTMailWindow *QTMailWindow::self = 0;
QTMailWindow::QTMailWindow(QWidget *parent, Qt::WFlags fl)
: QMainWindow(parent, fl), noShow(false)
{
qLog(Messaging) << "QTMailWindow ctor begin";
QtopiaApplication::loadTranslations("libqtopiamail");
init();
}
void QTMailWindow::init()
{
self = this;
// Pass in an incorrect parent, a warning
// "QLayout::addChildWidget: EmailClient "client" in wrong parent; "
// "moved to correct parent" will be shown, but this is necessary
// to make the emailClient QMainWindow display.
// This seems to be a QMainWindow in a QStackedWidget bug
emailClient = new EmailClient(this, "client"); // No tr
status = new StatusDisplay;
connect(emailClient, SIGNAL(raiseWidget(QWidget*,QString)),
this, SLOT(raiseWidget(QWidget*,QString)) );
connect(emailClient, SIGNAL(statusVisible(bool)),
status, SLOT(showStatus(bool)) );
connect(emailClient, SIGNAL(updateStatus(QString)),
status, SLOT(displayStatus(QString)) );
connect(emailClient, SIGNAL(updateProgress(uint, uint)),
status, SLOT(displayProgress(uint, uint)) );
connect(emailClient, SIGNAL(clearStatus()),
status, SLOT(clearStatus()) );
views = new QStackedWidget;
views->addWidget(emailClient);
views->setCurrentWidget(emailClient);
QFrame* vbox = new QFrame(this);
vbox->setFrameStyle(QFrame::NoFrame);
QVBoxLayout* vboxLayout = new QVBoxLayout(vbox);
vboxLayout->setContentsMargins( 0, 0, 0, 0 );
vboxLayout->setSpacing( 0 );
vboxLayout->addWidget( views );
vboxLayout->addWidget( status );
setCentralWidget( vbox );
setWindowTitle( emailClient->windowTitle() );
}
QTMailWindow::~QTMailWindow()
{
if (emailClient)
emailClient->cleanExit( true );
qLog(Messaging) << "QTMailWindow dtor end";
}
void QTMailWindow::closeEvent(QCloseEvent *e)
{
if (WriteMail* writeMail = emailClient->mWriteMail) {
if ((views->currentWidget() == writeMail) && (writeMail->hasContent())) {
// We need to save whatever is currently being worked on
writeMail->forcedClosure();
}
}
if (emailClient->isTransmitting()) {
emailClient->closeAfterTransmissionsFinished();
hide();
e->ignore();
} else {
e->accept();
}
}
void QTMailWindow::forceHidden(bool hidden)
{
noShow = hidden;
}
void QTMailWindow::setVisible(bool visible)
{
if (noShow && visible)
return;
QMainWindow::setVisible(visible);
}
void QTMailWindow::setDocument(const QString &_address)
{
emailClient->setDocument(_address);
}
void QTMailWindow::raiseWidget(QWidget *w, const QString &caption)
{
if (!isVisible())
showMaximized();
views->setCurrentWidget(w);
if (!caption.isEmpty())
setWindowTitle( caption );
raise();
activateWindow();
// needed to work with context-help
setObjectName( w->objectName() );
}
QWidget* QTMailWindow::currentWidget() const
{
return views->currentWidget();
}
QTMailWindow* QTMailWindow::singleton()
{
return self;
}
| muromec/qtopia-ezx | src/applications/qtmail/qtmailwindow.cpp | C++ | gpl-2.0 | 4,104 |
/*
Copyright (C) 2009 Markus Michael Geipel, David Garcia Becerra
This file is part of Cuttlefish.
Cuttlefish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ch.ethz.sg.cuttlefish.misc;
import org.apache.commons.collections15.Factory;
/**
* Factory class that creates anonymous vertices
* @author david
*/
public class VertexFactory implements Factory<Vertex> {
public Vertex create() {
return new Vertex();
}
}
| dev-cuttlefish/cuttlefish | src-old/ch/ethz/sg/cuttlefish/misc/VertexFactory.java | Java | gpl-2.0 | 1,036 |
#include "caboutdlg.h"
#include "ui_caboutdlg.h"
CAboutDlg::CAboutDlg(QWidget *parent) :
QDialog(parent),
ui(new Ui::CAboutDlg)
{
ui->setupUi(this);
initWnd();
initWidget();
initAction();
}
CAboutDlg::~CAboutDlg()
{
delete ui;
}
void CAboutDlg::mousePressEvent(QMouseEvent * ev)
{
QMouseEvent *mv = (QMouseEvent*) ev;
if(mv->buttons() & Qt::LeftButton)
{
QRect labelrect = QRect(ui->lb_top->pos() + this->pos(), ui->lb_top->size());
if(labelrect.contains(mv->globalPos()))
{
m_Ptbefore = mv->globalPos();
m_Ptcur = mv->pos();
}
}
}
void CAboutDlg::mouseMoveEvent(QMouseEvent *ev)
{
QMouseEvent *mv = (QMouseEvent*) ev;
QRect labelrect = QRect(ui->lb_top->pos() + this->pos(), ui->lb_top->size());
if(labelrect.contains(mv->globalPos()))
{
this->move(mv->globalX() - m_Ptcur.rx(), mv->globalY() - m_Ptcur.ry());
m_Ptbefore = mv->globalPos();
sleep(0.1);
}
}
void CAboutDlg::initWnd()
{
//drop frame
Qt::WindowFlags flags = Qt::Widget;
flags |= Qt::WindowStaysOnTopHint;
setWindowFlags(flags | Qt::FramelessWindowHint);
//setFixedSize(MAINWNDWIDTH, MAINWNDHEIGH);
QPalette pal;
QPixmap pixmap( QDir::toNativeSeparators
("://resource/pic/back_set.png") );
pal.setBrush(QPalette::Window, QBrush(pixmap));
setPalette(pal);
ui->lb_top->setStyleSheet("#lb_top{border-image:url(:resource/pic/top_bar.png);}");
ui->pb_close->setStyleSheet("#pb_close{border-image:url(:resource/pic/close.png);}");
ui->pb_min->setStyleSheet("#pb_min{border-image:url(:resource/pic/min.png);}");
ui->pb_confirm->setStyleSheet("pb_record_2{border-image:url(:resource/pic/confirm.png);color: white;border-radius: 10px; border: 2px groove gray;border-style: outset;}"
"#pb_record_2:hover{color: green;}");
}
void CAboutDlg::initWidget()
{
}
void CAboutDlg::initAction()
{
connect(ui->pb_close, SIGNAL(clicked()), this, SLOT(close()));
connect(ui->pb_confirm, SIGNAL(clicked()), this, SLOT(close()));
}
| lzz5235/ChatOnline | Client/caboutdlg.cpp | C++ | gpl-2.0 | 2,133 |
<?php
abstract class MP_
{
//// no limit ////
public static function no_abort_limit()
{
if (function_exists('ignore_user_abort')) ignore_user_abort(1);
if (function_exists('set_time_limit')) if( !in_array(ini_get('safe_mode'),array('1', 'On')) ) set_time_limit(0);
}
//// image ////
public static function is_image($file)
{
return (in_array(substr(strtolower(strrchr(strtolower($file), '.')), 1), self::ext_image()));
}
public static function ext_image()
{
return array('jpg', 'jpeg', 'png', 'gif', 'tif', 'bmp');
}
//// url ////
public static function url($url, $url_parms = array(), $wpnonce = false)
{
$url = add_query_arg(array_map ( 'urlencode', $url_parms), $url);
return ($wpnonce) ? wp_nonce_url( $url, $wpnonce ) : $url;
}
//// plugin/add-on ////
public static function plugin_links($links, $file, $basename, $tab)
{
if ($basename != $file) return $links;
$settings_link = "<a href='" . MailPress_settings . "#fragment-$tab'>" . __('Settings') . '</a>';
array_unshift ($links, $settings_link);
return $links;
}
//// form ////
public static function select_option($list, $selected, $echo = true)
{
$x = '';
foreach( $list as $value => $label )
{
$_selected = (!is_array($selected)) ? $selected : ( (in_array($value, $selected)) ? $value : null );
$x .= "<option " . self::selected( (string) $value, (string) $_selected, false, false ) . " value=\"$value\">$label</option>";
}
if (!$echo) return "\n$x\n";
echo "\n$x\n";
}
public static function select_number($start, $max, $selected, $tick = 1, $echo = true)
{
$x = '';
while ($start <= $max)
{
if (intval ($start/$tick) == $start/$tick )
$x .= "<option " . self::selected( (string) $start, (string) $selected, false, false ) . " value='$start'>$start</option>";
$start++;
}
if (!$echo) return "\n$x\n";
echo "\n$x\n";
}
public static function selected( $selected, $current = true, $echo = true)
{
return self::__checked_selected_helper( $selected, $current, $echo, 'selected' );
}
public static function __checked_selected_helper( $helper, $current, $echo, $type)
{
$result = ( $helper == $current) ? " $type='$type'" : '';
if ($echo) echo $result;
return $result;
}
//// functions ////
public static function mp_redirect($r)
{
if (defined('MP_DEBUG_LOG') && !defined('MP_DEBUG_LOG_STOP')) { global $mp_debug_log; if (isset($mp_debug_log)) $mp_debug_log->log(" mp_redirect : >> $r << "); $mp_debug_log->end(true); define ('MP_DEBUG_LOG_STOP', true);}
wp_redirect($r);
self::mp_die();
}
public static function mp_die($r = true)
{
if (defined('MP_DEBUG_LOG') && !defined('MP_DEBUG_LOG_STOP')) { global $mp_debug_log; if (isset($mp_debug_log)) $mp_debug_log->log(" mp_die : >> $r << "); $mp_debug_log->end(true); define ('MP_DEBUG_LOG_STOP', true);}
die($r);
}
public static function print_scripts_l10n_val($val0, $before = "")
{
if (is_array($val0))
{
$eol = "\t\t";
$text = "{\n\t$before";
foreach($val0 as $var => $val)
{
$text .= "$eol$var: " . self::print_scripts_l10n_val($val, "\t" . $before );
$eol = ", \n$before\t\t\t";
}
$text .= "\n\t\t$before}";
}
else
{
$quot = (stripos($val0, '"') === false) ? '"' : "'";
$text = "$quot$val0$quot";
}
return $text;
}
} | fritids/embroideryadvertisers | wp-content/plugins/mailpress/mp-includes/class/MP_.class.php | PHP | gpl-2.0 | 3,427 |
/* $Id: DevSerial.cpp 56292 2015-06-09 14:20:46Z vboxsync $ */
/** @file
* DevSerial - 16550A UART emulation.
* (taken from hw/serial.c 2010/05/15 with modifications)
*/
/*
* Copyright (C) 2006-2015 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
/*
* This code is based on:
*
* QEMU 16550A UART emulation
*
* Copyright (c) 2003-2004 Fabrice Bellard
* Copyright (c) 2008 Citrix Systems, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#define LOG_GROUP LOG_GROUP_DEV_SERIAL
#include <VBox/vmm/pdmdev.h>
#include <iprt/assert.h>
#include <iprt/uuid.h>
#include <iprt/string.h>
#include <iprt/semaphore.h>
#include <iprt/critsect.h>
#include "VBoxDD.h"
#undef VBOX_SERIAL_PCI /* The PCI variant has lots of problems: wrong IRQ line and wrong IO base assigned. */
#ifdef VBOX_SERIAL_PCI
# include <VBox/pci.h>
#endif /* VBOX_SERIAL_PCI */
/*******************************************************************************
* Defined Constants And Macros *
*******************************************************************************/
#define SERIAL_SAVED_STATE_VERSION_16450 3
#define SERIAL_SAVED_STATE_VERSION_MISSING_BITS 4
#define SERIAL_SAVED_STATE_VERSION 5
#define UART_LCR_DLAB 0x80 /* Divisor latch access bit */
#define UART_IER_MSI 0x08 /* Enable Modem status interrupt */
#define UART_IER_RLSI 0x04 /* Enable receiver line status interrupt */
#define UART_IER_THRI 0x02 /* Enable Transmitter holding register int. */
#define UART_IER_RDI 0x01 /* Enable receiver data interrupt */
#define UART_IIR_NO_INT 0x01 /* No interrupts pending */
#define UART_IIR_ID 0x06 /* Mask for the interrupt ID */
#define UART_IIR_MSI 0x00 /* Modem status interrupt */
#define UART_IIR_THRI 0x02 /* Transmitter holding register empty */
#define UART_IIR_RDI 0x04 /* Receiver data interrupt */
#define UART_IIR_RLSI 0x06 /* Receiver line status interrupt */
#define UART_IIR_CTI 0x0C /* Character Timeout Indication */
#define UART_IIR_FENF 0x80 /* Fifo enabled, but not functioning */
#define UART_IIR_FE 0xC0 /* Fifo enabled */
/*
* These are the definitions for the Modem Control Register
*/
#define UART_MCR_LOOP 0x10 /* Enable loopback test mode */
#define UART_MCR_OUT2 0x08 /* Out2 complement */
#define UART_MCR_OUT1 0x04 /* Out1 complement */
#define UART_MCR_RTS 0x02 /* RTS complement */
#define UART_MCR_DTR 0x01 /* DTR complement */
/*
* These are the definitions for the Modem Status Register
*/
#define UART_MSR_DCD 0x80 /* Data Carrier Detect */
#define UART_MSR_RI 0x40 /* Ring Indicator */
#define UART_MSR_DSR 0x20 /* Data Set Ready */
#define UART_MSR_CTS 0x10 /* Clear to Send */
#define UART_MSR_DDCD 0x08 /* Delta DCD */
#define UART_MSR_TERI 0x04 /* Trailing edge ring indicator */
#define UART_MSR_DDSR 0x02 /* Delta DSR */
#define UART_MSR_DCTS 0x01 /* Delta CTS */
#define UART_MSR_ANY_DELTA 0x0F /* Any of the delta bits! */
#define UART_LSR_TEMT 0x40 /* Transmitter empty */
#define UART_LSR_THRE 0x20 /* Transmit-hold-register empty */
#define UART_LSR_BI 0x10 /* Break interrupt indicator */
#define UART_LSR_FE 0x08 /* Frame error indicator */
#define UART_LSR_PE 0x04 /* Parity error indicator */
#define UART_LSR_OE 0x02 /* Overrun error indicator */
#define UART_LSR_DR 0x01 /* Receiver data ready */
#define UART_LSR_INT_ANY 0x1E /* Any of the lsr-interrupt-triggering status bits */
/*
* Interrupt trigger levels.
* The byte-counts are for 16550A - in newer UARTs the byte-count for each ITL is higher.
*/
#define UART_FCR_ITL_1 0x00 /* 1 byte ITL */
#define UART_FCR_ITL_2 0x40 /* 4 bytes ITL */
#define UART_FCR_ITL_3 0x80 /* 8 bytes ITL */
#define UART_FCR_ITL_4 0xC0 /* 14 bytes ITL */
#define UART_FCR_DMS 0x08 /* DMA Mode Select */
#define UART_FCR_XFR 0x04 /* XMIT Fifo Reset */
#define UART_FCR_RFR 0x02 /* RCVR Fifo Reset */
#define UART_FCR_FE 0x01 /* FIFO Enable */
#define UART_FIFO_LENGTH 16 /* 16550A Fifo Length */
#define XMIT_FIFO 0
#define RECV_FIFO 1
#define MIN_XMIT_RETRY 16
#define MAX_XMIT_RETRY_TIME 1 /* max time (in seconds) for retrying the character xmit before dropping it */
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
struct SerialFifo
{
uint8_t data[UART_FIFO_LENGTH];
uint8_t count;
uint8_t itl;
uint8_t tail;
uint8_t head;
};
/**
* Serial device.
*
* @implements PDMIBASE
* @implements PDMICHARPORT
*/
typedef struct SerialState
{
/** Access critical section. */
PDMCRITSECT CritSect;
/** Pointer to the device instance - R3 Ptr. */
PPDMDEVINSR3 pDevInsR3;
/** Pointer to the device instance - R0 Ptr. */
PPDMDEVINSR0 pDevInsR0;
/** Pointer to the device instance - RC Ptr. */
PPDMDEVINSRC pDevInsRC;
/** Alignment. */
RTRCPTR Alignment0;
/** LUN\#0: The base interface. */
PDMIBASE IBase;
/** LUN\#0: The character port interface. */
PDMICHARPORT ICharPort;
/** Pointer to the attached base driver. */
R3PTRTYPE(PPDMIBASE) pDrvBase;
/** Pointer to the attached character driver. */
R3PTRTYPE(PPDMICHARCONNECTOR) pDrvChar;
RTSEMEVENT ReceiveSem;
PTMTIMERR3 fifo_timeout_timer;
PTMTIMERR3 transmit_timerR3;
PTMTIMERR0 transmit_timerR0; /* currently not used */
PTMTIMERRC transmit_timerRC; /* currently not used */
RTRCPTR Alignment1;
SerialFifo recv_fifo;
SerialFifo xmit_fifo;
uint32_t base;
uint16_t divider;
uint16_t Alignment2[1];
uint8_t rbr; /**< receive register */
uint8_t thr; /**< transmit holding register */
uint8_t tsr; /**< transmit shift register */
uint8_t ier; /**< interrupt enable register */
uint8_t iir; /**< interrupt identification register, R/O */
uint8_t lcr; /**< line control register */
uint8_t mcr; /**< modem control register */
uint8_t lsr; /**< line status register, R/O */
uint8_t msr; /**< modem status register, R/O */
uint8_t scr; /**< scratch register */
uint8_t fcr; /**< fifo control register */
uint8_t fcr_vmstate;
/* NOTE: this hidden state is necessary for tx irq generation as
it can be reset while reading iir */
int thr_ipending;
int timeout_ipending;
int irq;
int last_break_enable;
/** Counter for retrying xmit */
int tsr_retry;
int tsr_retry_bound; /**< number of retries before dropping a character */
int tsr_retry_bound_max; /**< maximum possible tsr_retry_bound value that can be set while dynamic bound adjustment */
int tsr_retry_bound_min; /**< minimum possible tsr_retry_bound value that can be set while dynamic bound adjustment */
bool msr_changed;
bool fGCEnabled;
bool fR0Enabled;
bool fYieldOnLSRRead;
bool volatile fRecvWaiting;
bool f16550AEnabled;
bool Alignment3[6];
/** Time it takes to transmit a character */
uint64_t char_transmit_time;
#ifdef VBOX_SERIAL_PCI
PCIDEVICE PciDev;
#endif /* VBOX_SERIAL_PCI */
} DEVSERIAL;
/** Pointer to the serial device state. */
typedef DEVSERIAL *PDEVSERIAL;
#ifndef VBOX_DEVICE_STRUCT_TESTCASE
#ifdef IN_RING3
static int serial_can_receive(PDEVSERIAL pThis);
static void serial_receive(PDEVSERIAL pThis, const uint8_t *buf, int size);
static void fifo_clear(PDEVSERIAL pThis, int fifo)
{
SerialFifo *f = (fifo) ? &pThis->recv_fifo : &pThis->xmit_fifo;
memset(f->data, 0, UART_FIFO_LENGTH);
f->count = 0;
f->head = 0;
f->tail = 0;
}
static int fifo_put(PDEVSERIAL pThis, int fifo, uint8_t chr)
{
SerialFifo *f = (fifo) ? &pThis->recv_fifo : &pThis->xmit_fifo;
/* Receive overruns do not overwrite FIFO contents. */
if (fifo == XMIT_FIFO || f->count < UART_FIFO_LENGTH)
{
f->data[f->head++] = chr;
if (f->head == UART_FIFO_LENGTH)
f->head = 0;
}
if (f->count < UART_FIFO_LENGTH)
f->count++;
else if (fifo == XMIT_FIFO) /* need to at least adjust tail to maintain pipe state consistency */
++f->tail;
else if (fifo == RECV_FIFO)
pThis->lsr |= UART_LSR_OE;
return 1;
}
static uint8_t fifo_get(PDEVSERIAL pThis, int fifo)
{
SerialFifo *f = (fifo) ? &pThis->recv_fifo : &pThis->xmit_fifo;
uint8_t c;
if (f->count == 0)
return 0;
c = f->data[f->tail++];
if (f->tail == UART_FIFO_LENGTH)
f->tail = 0;
f->count--;
return c;
}
static void serial_update_irq(PDEVSERIAL pThis)
{
uint8_t tmp_iir = UART_IIR_NO_INT;
if ( (pThis->ier & UART_IER_RLSI)
&& (pThis->lsr & UART_LSR_INT_ANY)) {
tmp_iir = UART_IIR_RLSI;
} else if ((pThis->ier & UART_IER_RDI) && pThis->timeout_ipending) {
/* Note that(pThis->ier & UART_IER_RDI) can mask this interrupt,
* this is not in the specification but is observed on existing
* hardware. */
tmp_iir = UART_IIR_CTI;
} else if ( (pThis->ier & UART_IER_RDI)
&& (pThis->lsr & UART_LSR_DR)
&& ( !(pThis->fcr & UART_FCR_FE)
|| pThis->recv_fifo.count >= pThis->recv_fifo.itl)) {
tmp_iir = UART_IIR_RDI;
} else if ( (pThis->ier & UART_IER_THRI)
&& pThis->thr_ipending) {
tmp_iir = UART_IIR_THRI;
} else if ( (pThis->ier & UART_IER_MSI)
&& (pThis->msr & UART_MSR_ANY_DELTA)) {
tmp_iir = UART_IIR_MSI;
}
pThis->iir = tmp_iir | (pThis->iir & 0xF0);
/** XXX only call the SetIrq function if the state really changes! */
if (tmp_iir != UART_IIR_NO_INT) {
Log(("serial_update_irq %d 1\n", pThis->irq));
# ifdef VBOX_SERIAL_PCI
PDMDevHlpPCISetIrqNoWait(pThis->CTX_SUFF(pDevIns), 0, 1);
# else /* !VBOX_SERIAL_PCI */
PDMDevHlpISASetIrqNoWait(pThis->CTX_SUFF(pDevIns), pThis->irq, 1);
# endif /* !VBOX_SERIAL_PCI */
} else {
Log(("serial_update_irq %d 0\n", pThis->irq));
# ifdef VBOX_SERIAL_PCI
PDMDevHlpPCISetIrqNoWait(pThis->CTX_SUFF(pDevIns), 0, 0);
# else /* !VBOX_SERIAL_PCI */
PDMDevHlpISASetIrqNoWait(pThis->CTX_SUFF(pDevIns), pThis->irq, 0);
# endif /* !VBOX_SERIAL_PCI */
}
}
static void serial_tsr_retry_update_parameters(PDEVSERIAL pThis, uint64_t tf)
{
pThis->tsr_retry_bound_max = RT_MAX((tf * MAX_XMIT_RETRY_TIME) / pThis->char_transmit_time, MIN_XMIT_RETRY);
pThis->tsr_retry_bound_min = RT_MAX(pThis->tsr_retry_bound_max / (1000 * MAX_XMIT_RETRY_TIME), MIN_XMIT_RETRY);
/* for simplicity just reset to max retry count */
pThis->tsr_retry_bound = pThis->tsr_retry_bound_max;
}
static void serial_tsr_retry_bound_reached(PDEVSERIAL pThis)
{
/* this is most likely means we have some backend connection issues */
/* decrement the retry bound */
pThis->tsr_retry_bound = RT_MAX(pThis->tsr_retry_bound / (10 * MAX_XMIT_RETRY_TIME), pThis->tsr_retry_bound_min);
}
static void serial_tsr_retry_succeeded(PDEVSERIAL pThis)
{
/* success means we have a backend connection working OK,
* set retry bound to its maximum value */
pThis->tsr_retry_bound = pThis->tsr_retry_bound_max;
}
static void serial_update_parameters(PDEVSERIAL pThis)
{
int speed, parity, data_bits, stop_bits, frame_size;
if (pThis->divider == 0)
return;
frame_size = 1;
if (pThis->lcr & 0x08) {
frame_size++;
if (pThis->lcr & 0x10)
parity = 'E';
else
parity = 'O';
} else {
parity = 'N';
}
if (pThis->lcr & 0x04)
stop_bits = 2;
else
stop_bits = 1;
data_bits = (pThis->lcr & 0x03) + 5;
frame_size += data_bits + stop_bits;
speed = 115200 / pThis->divider;
uint64_t tf = TMTimerGetFreq(CTX_SUFF(pThis->transmit_timer));
pThis->char_transmit_time = (tf / speed) * frame_size;
serial_tsr_retry_update_parameters(pThis, tf);
Log(("speed=%d parity=%c data=%d stop=%d\n", speed, parity, data_bits, stop_bits));
if (RT_LIKELY(pThis->pDrvChar))
pThis->pDrvChar->pfnSetParameters(pThis->pDrvChar, speed, parity, data_bits, stop_bits);
}
static void serial_xmit(PDEVSERIAL pThis, bool bRetryXmit)
{
if (pThis->tsr_retry <= 0) {
if (pThis->fcr & UART_FCR_FE) {
pThis->tsr = fifo_get(pThis, XMIT_FIFO);
if (!pThis->xmit_fifo.count)
pThis->lsr |= UART_LSR_THRE;
} else {
pThis->tsr = pThis->thr;
pThis->lsr |= UART_LSR_THRE;
}
}
if (pThis->mcr & UART_MCR_LOOP) {
/* in loopback mode, say that we just received a char */
serial_receive(pThis, &pThis->tsr, 1);
} else if ( RT_LIKELY(pThis->pDrvChar)
&& RT_FAILURE(pThis->pDrvChar->pfnWrite(pThis->pDrvChar, &pThis->tsr, 1))) {
if ((pThis->tsr_retry >= 0) && ((!bRetryXmit) || (pThis->tsr_retry <= pThis->tsr_retry_bound))) {
if (!pThis->tsr_retry)
pThis->tsr_retry = 1; /* make sure the retry state is always set */
else if (bRetryXmit) /* do not increase the retry count if the retry is actually caused by next char write */
pThis->tsr_retry++;
TMTimerSet(CTX_SUFF(pThis->transmit_timer), TMTimerGet(CTX_SUFF(pThis->transmit_timer)) + pThis->char_transmit_time * 4);
return;
} else {
/* drop this character. */
pThis->tsr_retry = 0;
serial_tsr_retry_bound_reached(pThis);
}
}
else {
pThis->tsr_retry = 0;
serial_tsr_retry_succeeded(pThis);
}
if (!(pThis->lsr & UART_LSR_THRE))
TMTimerSet(CTX_SUFF(pThis->transmit_timer),
TMTimerGet(CTX_SUFF(pThis->transmit_timer)) + pThis->char_transmit_time);
if (pThis->lsr & UART_LSR_THRE) {
pThis->lsr |= UART_LSR_TEMT;
pThis->thr_ipending = 1;
serial_update_irq(pThis);
}
}
#endif /* IN_RING3 */
static int serial_ioport_write(PDEVSERIAL pThis, uint32_t addr, uint32_t val)
{
addr &= 7;
#ifndef IN_RING3
NOREF(pThis);
return VINF_IOM_R3_IOPORT_WRITE;
#else
switch(addr) {
default:
case 0:
if (pThis->lcr & UART_LCR_DLAB) {
pThis->divider = (pThis->divider & 0xff00) | val;
serial_update_parameters(pThis);
} else {
pThis->thr = (uint8_t) val;
if (pThis->fcr & UART_FCR_FE) {
fifo_put(pThis, XMIT_FIFO, pThis->thr);
pThis->thr_ipending = 0;
pThis->lsr &= ~UART_LSR_TEMT;
pThis->lsr &= ~UART_LSR_THRE;
serial_update_irq(pThis);
} else {
pThis->thr_ipending = 0;
pThis->lsr &= ~UART_LSR_THRE;
serial_update_irq(pThis);
}
serial_xmit(pThis, false);
}
break;
case 1:
if (pThis->lcr & UART_LCR_DLAB) {
pThis->divider = (pThis->divider & 0x00ff) | (val << 8);
serial_update_parameters(pThis);
} else {
pThis->ier = val & 0x0f;
if (pThis->lsr & UART_LSR_THRE) {
pThis->thr_ipending = 1;
serial_update_irq(pThis);
}
}
break;
case 2:
if (!pThis->f16550AEnabled)
break;
val = val & 0xFF;
if (pThis->fcr == val)
break;
/* Did the enable/disable flag change? If so, make sure FIFOs get flushed */
if ((val ^ pThis->fcr) & UART_FCR_FE)
val |= UART_FCR_XFR | UART_FCR_RFR;
/* FIFO clear */
if (val & UART_FCR_RFR) {
TMTimerStop(pThis->fifo_timeout_timer);
pThis->timeout_ipending = 0;
fifo_clear(pThis, RECV_FIFO);
}
if (val & UART_FCR_XFR) {
fifo_clear(pThis, XMIT_FIFO);
}
if (val & UART_FCR_FE) {
pThis->iir |= UART_IIR_FE;
/* Set RECV_FIFO trigger Level */
switch (val & 0xC0) {
case UART_FCR_ITL_1:
pThis->recv_fifo.itl = 1;
break;
case UART_FCR_ITL_2:
pThis->recv_fifo.itl = 4;
break;
case UART_FCR_ITL_3:
pThis->recv_fifo.itl = 8;
break;
case UART_FCR_ITL_4:
pThis->recv_fifo.itl = 14;
break;
}
} else
pThis->iir &= ~UART_IIR_FE;
/* Set fcr - or at least the bits in it that are supposed to "stick" */
pThis->fcr = val & 0xC9;
serial_update_irq(pThis);
break;
case 3:
{
int break_enable;
pThis->lcr = val;
serial_update_parameters(pThis);
break_enable = (val >> 6) & 1;
if (break_enable != pThis->last_break_enable) {
pThis->last_break_enable = break_enable;
if (RT_LIKELY(pThis->pDrvChar))
{
Log(("serial_ioport_write: Set break %d\n", break_enable));
int rc = pThis->pDrvChar->pfnSetBreak(pThis->pDrvChar, !!break_enable);
AssertRC(rc);
}
}
}
break;
case 4:
pThis->mcr = val & 0x1f;
if (RT_LIKELY(pThis->pDrvChar))
{
int rc = pThis->pDrvChar->pfnSetModemLines(pThis->pDrvChar,
!!(pThis->mcr & UART_MCR_RTS),
!!(pThis->mcr & UART_MCR_DTR));
AssertRC(rc);
}
break;
case 5:
break;
case 6:
break;
case 7:
pThis->scr = val;
break;
}
return VINF_SUCCESS;
#endif
}
static uint32_t serial_ioport_read(PDEVSERIAL pThis, uint32_t addr, int *pRC)
{
uint32_t ret = ~0U;
*pRC = VINF_SUCCESS;
addr &= 7;
switch(addr) {
default:
case 0:
if (pThis->lcr & UART_LCR_DLAB) {
/* DLAB == 1: divisor latch (LS) */
ret = pThis->divider & 0xff;
} else {
#ifndef IN_RING3
*pRC = VINF_IOM_R3_IOPORT_READ;
#else
if (pThis->fcr & UART_FCR_FE) {
ret = fifo_get(pThis, RECV_FIFO);
if (pThis->recv_fifo.count == 0)
pThis->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
else
TMTimerSet(pThis->fifo_timeout_timer,
TMTimerGet(pThis->fifo_timeout_timer) + pThis->char_transmit_time * 4);
pThis->timeout_ipending = 0;
} else {
Log(("serial_io_port_read: read 0x%X\n", pThis->rbr));
ret = pThis->rbr;
pThis->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
}
serial_update_irq(pThis);
if (pThis->fRecvWaiting)
{
pThis->fRecvWaiting = false;
int rc = RTSemEventSignal(pThis->ReceiveSem);
AssertRC(rc);
}
#endif
}
break;
case 1:
if (pThis->lcr & UART_LCR_DLAB) {
/* DLAB == 1: divisor latch (MS) */
ret = (pThis->divider >> 8) & 0xff;
} else {
ret = pThis->ier;
}
break;
case 2:
#ifndef IN_RING3
*pRC = VINF_IOM_R3_IOPORT_READ;
#else
ret = pThis->iir;
if ((ret & UART_IIR_ID) == UART_IIR_THRI) {
pThis->thr_ipending = 0;
serial_update_irq(pThis);
}
/* reset msr changed bit */
pThis->msr_changed = false;
#endif
break;
case 3:
ret = pThis->lcr;
break;
case 4:
ret = pThis->mcr;
break;
case 5:
if ((pThis->lsr & UART_LSR_DR) == 0 && pThis->fYieldOnLSRRead)
{
/* No data available and yielding is enabled, so yield in ring3. */
#ifndef IN_RING3
*pRC = VINF_IOM_R3_IOPORT_READ;
break;
#else
RTThreadYield ();
#endif
}
ret = pThis->lsr;
/* Clear break and overrun interrupts */
if (pThis->lsr & (UART_LSR_BI|UART_LSR_OE)) {
#ifndef IN_RING3
*pRC = VINF_IOM_R3_IOPORT_READ;
#else
pThis->lsr &= ~(UART_LSR_BI|UART_LSR_OE);
serial_update_irq(pThis);
#endif
}
break;
case 6:
if (pThis->mcr & UART_MCR_LOOP) {
/* in loopback, the modem output pins are connected to the
inputs */
ret = (pThis->mcr & 0x0c) << 4;
ret |= (pThis->mcr & 0x02) << 3;
ret |= (pThis->mcr & 0x01) << 5;
} else {
ret = pThis->msr;
/* Clear delta bits & msr int after read, if they were set */
if (pThis->msr & UART_MSR_ANY_DELTA) {
#ifndef IN_RING3
*pRC = VINF_IOM_R3_IOPORT_READ;
#else
pThis->msr &= 0xF0;
serial_update_irq(pThis);
#endif
}
}
break;
case 7:
ret = pThis->scr;
break;
}
return ret;
}
#ifdef IN_RING3
static int serial_can_receive(PDEVSERIAL pThis)
{
if (pThis->fcr & UART_FCR_FE) {
if (pThis->recv_fifo.count < UART_FIFO_LENGTH)
return (pThis->recv_fifo.count <= pThis->recv_fifo.itl)
? pThis->recv_fifo.itl - pThis->recv_fifo.count : 1;
else
return 0;
} else {
return !(pThis->lsr & UART_LSR_DR);
}
}
static void serial_receive(PDEVSERIAL pThis, const uint8_t *buf, int size)
{
if (pThis->fcr & UART_FCR_FE) {
int i;
for (i = 0; i < size; i++) {
fifo_put(pThis, RECV_FIFO, buf[i]);
}
pThis->lsr |= UART_LSR_DR;
/* call the timeout receive callback in 4 char transmit time */
TMTimerSet(pThis->fifo_timeout_timer, TMTimerGet(pThis->fifo_timeout_timer) + pThis->char_transmit_time * 4);
} else {
if (pThis->lsr & UART_LSR_DR)
pThis->lsr |= UART_LSR_OE;
pThis->rbr = buf[0];
pThis->lsr |= UART_LSR_DR;
}
serial_update_irq(pThis);
}
/**
* @interface_method_impl{PDMICHARPORT,pfnNotifyRead}
*/
static DECLCALLBACK(int) serialNotifyRead(PPDMICHARPORT pInterface, const void *pvBuf, size_t *pcbRead)
{
PDEVSERIAL pThis = RT_FROM_MEMBER(pInterface, DEVSERIAL, ICharPort);
const uint8_t *pu8Buf = (const uint8_t*)pvBuf;
size_t cbRead = *pcbRead;
PDMCritSectEnter(&pThis->CritSect, VERR_PERMISSION_DENIED);
for (; cbRead > 0; cbRead--, pu8Buf++)
{
if (!serial_can_receive(pThis))
{
/* If we cannot receive then wait for not more than 250ms. If we still
* cannot receive then the new character will either overwrite rbr
* or it will be dropped at fifo_put(). */
pThis->fRecvWaiting = true;
PDMCritSectLeave(&pThis->CritSect);
int rc = RTSemEventWait(pThis->ReceiveSem, 250);
PDMCritSectEnter(&pThis->CritSect, VERR_PERMISSION_DENIED);
}
serial_receive(pThis, &pu8Buf[0], 1);
}
PDMCritSectLeave(&pThis->CritSect);
return VINF_SUCCESS;
}
/**
* @@interface_method_impl{PDMICHARPORT,pfnNotifyStatusLinesChanged}
*/
static DECLCALLBACK(int) serialNotifyStatusLinesChanged(PPDMICHARPORT pInterface, uint32_t newStatusLines)
{
PDEVSERIAL pThis = RT_FROM_MEMBER(pInterface, DEVSERIAL, ICharPort);
uint8_t newMsr = 0;
Log(("%s: pInterface=%p newStatusLines=%u\n", __FUNCTION__, pInterface, newStatusLines));
PDMCritSectEnter(&pThis->CritSect, VERR_PERMISSION_DENIED);
/* Set new states. */
if (newStatusLines & PDMICHARPORT_STATUS_LINES_DCD)
newMsr |= UART_MSR_DCD;
if (newStatusLines & PDMICHARPORT_STATUS_LINES_RI)
newMsr |= UART_MSR_RI;
if (newStatusLines & PDMICHARPORT_STATUS_LINES_DSR)
newMsr |= UART_MSR_DSR;
if (newStatusLines & PDMICHARPORT_STATUS_LINES_CTS)
newMsr |= UART_MSR_CTS;
/* Compare the old and the new states and set the delta bits accordingly. */
if ((newMsr & UART_MSR_DCD) != (pThis->msr & UART_MSR_DCD))
newMsr |= UART_MSR_DDCD;
if ((newMsr & UART_MSR_RI) != 0 && (pThis->msr & UART_MSR_RI) == 0)
newMsr |= UART_MSR_TERI;
if ((newMsr & UART_MSR_DSR) != (pThis->msr & UART_MSR_DSR))
newMsr |= UART_MSR_DDSR;
if ((newMsr & UART_MSR_CTS) != (pThis->msr & UART_MSR_CTS))
newMsr |= UART_MSR_DCTS;
pThis->msr = newMsr;
pThis->msr_changed = true;
serial_update_irq(pThis);
PDMCritSectLeave(&pThis->CritSect);
return VINF_SUCCESS;
}
/**
* @interface_method_impl{PDMICHARPORT,pfnNotifyBufferFull}
*/
static DECLCALLBACK(int) serialNotifyBufferFull(PPDMICHARPORT pInterface, bool fFull)
{
return VINF_SUCCESS;
}
/**
* @interface_method_impl{PDMICHARPORT,pfnNotifyBreak}
*/
static DECLCALLBACK(int) serialNotifyBreak(PPDMICHARPORT pInterface)
{
PDEVSERIAL pThis = RT_FROM_MEMBER(pInterface, DEVSERIAL, ICharPort);
Log(("%s: pInterface=%p\n", __FUNCTION__, pInterface));
PDMCritSectEnter(&pThis->CritSect, VERR_PERMISSION_DENIED);
pThis->lsr |= UART_LSR_BI;
serial_update_irq(pThis);
PDMCritSectLeave(&pThis->CritSect);
return VINF_SUCCESS;
}
/* -=-=-=-=-=-=-=-=- Timer callbacks -=-=-=-=-=-=-=-=- */
/**
* @callback_method_tmpl{FNTMTIMERDEV, Fifo timer function.}
*/
static DECLCALLBACK(void) serialFifoTimer(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser)
{
PDEVSERIAL pThis = (PDEVSERIAL)pvUser;
Assert(PDMCritSectIsOwner(&pThis->CritSect));
if (pThis->recv_fifo.count)
{
pThis->timeout_ipending = 1;
serial_update_irq(pThis);
}
}
/**
* @callback_method_tmpl{FNTMTIMERDEV, Transmit timer function.}
*
* Just retry to transmit a character.
*/
static DECLCALLBACK(void) serialTransmitTimer(PPDMDEVINS pDevIns, PTMTIMER pTimer, void *pvUser)
{
PDEVSERIAL pThis = (PDEVSERIAL)pvUser;
Assert(PDMCritSectIsOwner(&pThis->CritSect));
serial_xmit(pThis, true);
}
#endif /* IN_RING3 */
/* -=-=-=-=-=-=-=-=- I/O Port Access Handlers -=-=-=-=-=-=-=-=- */
/**
* @callback_method_impl{FNIOMIOPORTOUT}
*/
PDMBOTHCBDECL(int) serialIOPortWrite(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t u32, unsigned cb)
{
PDEVSERIAL pThis = PDMINS_2_DATA(pDevIns, PDEVSERIAL);
int rc;
Assert(PDMCritSectIsOwner(&pThis->CritSect));
if (cb == 1)
{
Log2(("%s: port %#06x val %#04x\n", __FUNCTION__, Port, u32));
rc = serial_ioport_write(pThis, Port, u32);
}
else
{
AssertMsgFailed(("Port=%#x cb=%d u32=%#x\n", Port, cb, u32));
rc = VINF_SUCCESS;
}
return rc;
}
/**
* @callback_method_impl{FNIOMIOPORTIN}
*/
PDMBOTHCBDECL(int) serialIOPortRead(PPDMDEVINS pDevIns, void *pvUser, RTIOPORT Port, uint32_t *pu32, unsigned cb)
{
PDEVSERIAL pThis = PDMINS_2_DATA(pDevIns, PDEVSERIAL);
int rc;
Assert(PDMCritSectIsOwner(&pThis->CritSect));
if (cb == 1)
{
*pu32 = serial_ioport_read(pThis, Port, &rc);
Log2(("%s: port %#06x val %#04x\n", __FUNCTION__, Port, *pu32));
}
else
rc = VERR_IOM_IOPORT_UNUSED;
return rc;
}
#ifdef IN_RING3
/* -=-=-=-=-=-=-=-=- Saved State -=-=-=-=-=-=-=-=- */
/**
* @callback_method_tmpl{FNSSMDEVLIVEEXEC}
*/
static DECLCALLBACK(int) serialLiveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uPass)
{
PDEVSERIAL pThis = PDMINS_2_DATA(pDevIns, PDEVSERIAL);
SSMR3PutS32(pSSM, pThis->irq);
SSMR3PutU32(pSSM, pThis->base);
return VINF_SSM_DONT_CALL_AGAIN;
}
/**
* @callback_method_tmpl{FNSSMDEVSAVEEXEC}
*/
static DECLCALLBACK(int) serialSaveExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM)
{
PDEVSERIAL pThis = PDMINS_2_DATA(pDevIns, PDEVSERIAL);
SSMR3PutU16(pSSM, pThis->divider);
SSMR3PutU8(pSSM, pThis->rbr);
SSMR3PutU8(pSSM, pThis->ier);
SSMR3PutU8(pSSM, pThis->lcr);
SSMR3PutU8(pSSM, pThis->mcr);
SSMR3PutU8(pSSM, pThis->lsr);
SSMR3PutU8(pSSM, pThis->msr);
SSMR3PutU8(pSSM, pThis->scr);
SSMR3PutU8(pSSM, pThis->fcr); /* 16550A */
SSMR3PutS32(pSSM, pThis->thr_ipending);
SSMR3PutS32(pSSM, pThis->irq);
SSMR3PutS32(pSSM, pThis->last_break_enable);
SSMR3PutU32(pSSM, pThis->base);
SSMR3PutBool(pSSM, pThis->msr_changed);
/* Version 5, safe everything that might be of importance. Much better than
missing relevant bits! */
SSMR3PutU8(pSSM, pThis->thr);
SSMR3PutU8(pSSM, pThis->tsr);
SSMR3PutU8(pSSM, pThis->iir);
SSMR3PutS32(pSSM, pThis->timeout_ipending);
TMR3TimerSave(pThis->fifo_timeout_timer, pSSM);
TMR3TimerSave(pThis->transmit_timerR3, pSSM);
SSMR3PutU8(pSSM, pThis->recv_fifo.itl);
SSMR3PutU8(pSSM, pThis->xmit_fifo.itl);
/* Don't store:
* - the content of the FIFO
* - tsr_retry
*/
return SSMR3PutU32(pSSM, ~0); /* sanity/terminator */
}
/**
* @callback_method_tmpl{FNSSMDEVLOADEXEC}
*/
static DECLCALLBACK(int) serialLoadExec(PPDMDEVINS pDevIns, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
{
PDEVSERIAL pThis = PDMINS_2_DATA(pDevIns, PDEVSERIAL);
int32_t iIrq;
uint32_t IOBase;
AssertMsgReturn(uVersion >= SERIAL_SAVED_STATE_VERSION_16450, ("%d\n", uVersion), VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION);
if (uPass != SSM_PASS_FINAL)
{
SSMR3GetS32(pSSM, &iIrq);
int rc = SSMR3GetU32(pSSM, &IOBase);
AssertRCReturn(rc, rc);
}
else
{
if (uVersion == SERIAL_SAVED_STATE_VERSION_16450)
{
pThis->f16550AEnabled = false;
LogRel(("Serial#%d: falling back to 16450 mode from load state\n", pDevIns->iInstance));
}
SSMR3GetU16(pSSM, &pThis->divider);
SSMR3GetU8(pSSM, &pThis->rbr);
SSMR3GetU8(pSSM, &pThis->ier);
SSMR3GetU8(pSSM, &pThis->lcr);
SSMR3GetU8(pSSM, &pThis->mcr);
SSMR3GetU8(pSSM, &pThis->lsr);
SSMR3GetU8(pSSM, &pThis->msr);
SSMR3GetU8(pSSM, &pThis->scr);
if (uVersion > SERIAL_SAVED_STATE_VERSION_16450)
SSMR3GetU8(pSSM, &pThis->fcr);
SSMR3GetS32(pSSM, &pThis->thr_ipending);
SSMR3GetS32(pSSM, &iIrq);
SSMR3GetS32(pSSM, &pThis->last_break_enable);
SSMR3GetU32(pSSM, &IOBase);
SSMR3GetBool(pSSM, &pThis->msr_changed);
if (uVersion > SERIAL_SAVED_STATE_VERSION_MISSING_BITS)
{
SSMR3GetU8(pSSM, &pThis->thr);
SSMR3GetU8(pSSM, &pThis->tsr);
SSMR3GetU8(pSSM, &pThis->iir);
SSMR3GetS32(pSSM, &pThis->timeout_ipending);
TMR3TimerLoad(pThis->fifo_timeout_timer, pSSM);
TMR3TimerLoad(pThis->transmit_timerR3, pSSM);
SSMR3GetU8(pSSM, &pThis->recv_fifo.itl);
SSMR3GetU8(pSSM, &pThis->xmit_fifo.itl);
}
/* the marker. */
uint32_t u32;
int rc = SSMR3GetU32(pSSM, &u32);
if (RT_FAILURE(rc))
return rc;
AssertMsgReturn(u32 == ~0U, ("%#x\n", u32), VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
if ( (pThis->lsr & UART_LSR_DR)
|| pThis->fRecvWaiting)
{
pThis->fRecvWaiting = false;
rc = RTSemEventSignal(pThis->ReceiveSem);
AssertRC(rc);
}
/* this isn't strictly necessary but cannot hurt... */
pThis->pDevInsR3 = pDevIns;
pThis->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
}
/*
* Check the config.
*/
if ( pThis->irq != iIrq
|| pThis->base != IOBase)
return SSMR3SetCfgError(pSSM, RT_SRC_POS,
N_("Config mismatch - saved irq=%#x iobase=%#x; configured irq=%#x iobase=%#x"),
iIrq, IOBase, pThis->irq, pThis->base);
return VINF_SUCCESS;
}
#ifdef VBOX_SERIAL_PCI
/* -=-=-=-=-=-=-=-=- PCI Device Callback(s) -=-=-=-=-=-=-=-=- */
/**
* @callback_method_impl{FNPCIIOREGIONMAP}
*/
static DECLCALLBACK(int) serialIOPortRegionMap(PPCIDEVICE pPciDev, int iRegion, RTGCPHYS GCPhysAddress,
uint32_t cb, PCIADDRESSSPACE enmType)
{
PDEVSERIAL pThis = RT_FROM_MEMBER(pPciDev, DEVSERIAL, PciDev);
int rc = VINF_SUCCESS;
Assert(enmType == PCI_ADDRESS_SPACE_IO);
Assert(iRegion == 0);
Assert(cb == 8);
AssertMsg(RT_ALIGN(GCPhysAddress, 8) == GCPhysAddress, ("Expected 8 byte alignment. GCPhysAddress=%#x\n", GCPhysAddress));
pThis->base = (RTIOPORT)GCPhysAddress;
LogRel(("Serial#%d: mapping I/O at %#06x\n", pThis->pDevIns->iInstance, pThis->base));
/*
* Register our port IO handlers.
*/
rc = PDMDevHlpIOPortRegister(pPciDev->pDevIns, (RTIOPORT)GCPhysAddress, 8, (void *)pThis,
serial_io_write, serial_io_read, NULL, NULL, "SERIAL");
AssertRC(rc);
return rc;
}
#endif /* VBOX_SERIAL_PCI */
/* -=-=-=-=-=-=-=-=- PDMIBASE on LUN#1 -=-=-=-=-=-=-=-=- */
/**
* @interface_method_impl{PDMIBASE, pfnQueryInterface}
*/
static DECLCALLBACK(void *) serialQueryInterface(PPDMIBASE pInterface, const char *pszIID)
{
PDEVSERIAL pThis = RT_FROM_MEMBER(pInterface, DEVSERIAL, IBase);
PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pThis->IBase);
PDMIBASE_RETURN_INTERFACE(pszIID, PDMICHARPORT, &pThis->ICharPort);
return NULL;
}
/* -=-=-=-=-=-=-=-=- PDMDEVREG -=-=-=-=-=-=-=-=- */
/**
* @interface_method_impl{PDMDEVREG, pfnRelocate}
*/
static DECLCALLBACK(void) serialRelocate(PPDMDEVINS pDevIns, RTGCINTPTR offDelta)
{
PDEVSERIAL pThis = PDMINS_2_DATA(pDevIns, PDEVSERIAL);
pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
pThis->transmit_timerRC = TMTimerRCPtr(pThis->transmit_timerR3);
}
/**
* @interface_method_impl{PDMDEVREG, pfnReset}
*/
static DECLCALLBACK(void) serialReset(PPDMDEVINS pDevIns)
{
PDEVSERIAL pThis = PDMINS_2_DATA(pDevIns, PDEVSERIAL);
pThis->rbr = 0;
pThis->ier = 0;
pThis->iir = UART_IIR_NO_INT;
pThis->lcr = 0;
pThis->lsr = UART_LSR_TEMT | UART_LSR_THRE;
pThis->msr = UART_MSR_DCD | UART_MSR_DSR | UART_MSR_CTS;
/* Default to 9600 baud, 1 start bit, 8 data bits, 1 stop bit, no parity. */
pThis->divider = 0x0C;
pThis->mcr = UART_MCR_OUT2;
pThis->scr = 0;
pThis->tsr_retry = 0;
uint64_t tf = TMTimerGetFreq(CTX_SUFF(pThis->transmit_timer));
pThis->char_transmit_time = (tf / 9600) * 10;
serial_tsr_retry_update_parameters(pThis, tf);
fifo_clear(pThis, RECV_FIFO);
fifo_clear(pThis, XMIT_FIFO);
pThis->thr_ipending = 0;
pThis->last_break_enable = 0;
# ifdef VBOX_SERIAL_PCI
PDMDevHlpPCISetIrqNoWait(pThis->CTX_SUFF(pDevIns), 0, 0);
# else /* !VBOX_SERIAL_PCI */
PDMDevHlpISASetIrqNoWait(pThis->CTX_SUFF(pDevIns), pThis->irq, 0);
# endif /* !VBOX_SERIAL_PCI */
}
/**
* @interface_method_impl{PDMDEVREG, pfnDestruct}
*/
static DECLCALLBACK(int) serialDestruct(PPDMDEVINS pDevIns)
{
PDEVSERIAL pThis = PDMINS_2_DATA(pDevIns, PDEVSERIAL);
PDMDEV_CHECK_VERSIONS_RETURN_QUIET(pDevIns);
RTSemEventDestroy(pThis->ReceiveSem);
pThis->ReceiveSem = NIL_RTSEMEVENT;
PDMR3CritSectDelete(&pThis->CritSect);
return VINF_SUCCESS;
}
/**
* @interface_method_impl{PDMDEVREG, pfnConstruct}
*/
static DECLCALLBACK(int) serialConstruct(PPDMDEVINS pDevIns, int iInstance, PCFGMNODE pCfg)
{
PDEVSERIAL pThis = PDMINS_2_DATA(pDevIns, PDEVSERIAL);
int rc;
uint16_t io_base;
uint8_t irq_lvl;
Assert(iInstance < 4);
PDMDEV_CHECK_VERSIONS_RETURN(pDevIns);
/*
* Initialize the instance data.
* (Do this early or the destructor might choke on something!)
*/
pThis->pDevInsR3 = pDevIns;
pThis->pDevInsR0 = PDMDEVINS_2_R0PTR(pDevIns);
pThis->pDevInsRC = PDMDEVINS_2_RCPTR(pDevIns);
pThis->ReceiveSem = NIL_RTSEMEVENT;
/* IBase */
pThis->IBase.pfnQueryInterface = serialQueryInterface;
/* ICharPort */
pThis->ICharPort.pfnNotifyRead = serialNotifyRead;
pThis->ICharPort.pfnNotifyStatusLinesChanged = serialNotifyStatusLinesChanged;
pThis->ICharPort.pfnNotifyBufferFull = serialNotifyBufferFull;
pThis->ICharPort.pfnNotifyBreak = serialNotifyBreak;
#ifdef VBOX_SERIAL_PCI
/* the PCI device */
pThis->PciDev.config[0x00] = 0xee; /* Vendor: ??? */
pThis->PciDev.config[0x01] = 0x80;
pThis->PciDev.config[0x02] = 0x01; /* Device: ??? */
pThis->PciDev.config[0x03] = 0x01;
pThis->PciDev.config[0x04] = PCI_COMMAND_IOACCESS;
pThis->PciDev.config[0x09] = 0x01; /* Programming interface: 16450 */
pThis->PciDev.config[0x0a] = 0x00; /* Subclass: Serial controller */
pThis->PciDev.config[0x0b] = 0x07; /* Class: Communication controller */
pThis->PciDev.config[0x0e] = 0x00; /* Header type: standard */
pThis->PciDev.config[0x3c] = irq_lvl; /* preconfigure IRQ number (0 = autoconfig)*/
pThis->PciDev.config[0x3d] = 1; /* interrupt pin 0 */
#endif /* VBOX_SERIAL_PCI */
/*
* Validate and read the configuration.
*/
if (!CFGMR3AreValuesValid(pCfg, "IRQ\0"
"IOBase\0"
"GCEnabled\0"
"R0Enabled\0"
"YieldOnLSRRead\0"
"Enable16550A\0"
))
{
AssertMsgFailed(("serialConstruct Invalid configuration values\n"));
return VERR_PDM_DEVINS_UNKNOWN_CFG_VALUES;
}
rc = CFGMR3QueryBoolDef(pCfg, "GCEnabled", &pThis->fGCEnabled, true);
if (RT_FAILURE(rc))
return PDMDEV_SET_ERROR(pDevIns, rc,
N_("Configuration error: Failed to get the \"GCEnabled\" value"));
rc = CFGMR3QueryBoolDef(pCfg, "R0Enabled", &pThis->fR0Enabled, true);
if (RT_FAILURE(rc))
return PDMDEV_SET_ERROR(pDevIns, rc,
N_("Configuration error: Failed to get the \"R0Enabled\" value"));
rc = CFGMR3QueryBoolDef(pCfg, "YieldOnLSRRead", &pThis->fYieldOnLSRRead, false);
if (RT_FAILURE(rc))
return PDMDEV_SET_ERROR(pDevIns, rc,
N_("Configuration error: Failed to get the \"YieldOnLSRRead\" value"));
rc = CFGMR3QueryU8(pCfg, "IRQ", &irq_lvl);
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
{
/* Provide sensible defaults. */
if (iInstance == 0)
irq_lvl = 4;
else if (iInstance == 1)
irq_lvl = 3;
else
AssertReleaseFailed(); /* irq_lvl is undefined. */
}
else if (RT_FAILURE(rc))
return PDMDEV_SET_ERROR(pDevIns, rc,
N_("Configuration error: Failed to get the \"IRQ\" value"));
rc = CFGMR3QueryU16(pCfg, "IOBase", &io_base);
if (rc == VERR_CFGM_VALUE_NOT_FOUND)
{
if (iInstance == 0)
io_base = 0x3f8;
else if (iInstance == 1)
io_base = 0x2f8;
else
AssertReleaseFailed(); /* io_base is undefined */
}
else if (RT_FAILURE(rc))
return PDMDEV_SET_ERROR(pDevIns, rc,
N_("Configuration error: Failed to get the \"IOBase\" value"));
Log(("DevSerial: instance %d iobase=%04x irq=%d\n", iInstance, io_base, irq_lvl));
rc = CFGMR3QueryBoolDef(pCfg, "Enable16550A", &pThis->f16550AEnabled, true);
if (RT_FAILURE(rc))
return PDMDEV_SET_ERROR(pDevIns, rc,
N_("Configuration error: Failed to get the \"Enable16550A\" value"));
pThis->irq = irq_lvl;
#ifdef VBOX_SERIAL_PCI
pThis->base = -1;
#else
pThis->base = io_base;
#endif
LogRel(("Serial#%d: emulating %s\n", pDevIns->iInstance, pThis->f16550AEnabled ? "16550A" : "16450"));
/*
* Initialize critical section and the semaphore. Change the default
* critical section to ours so that TM and IOM will enter it before
* calling us.
*
* Note! This must of be done BEFORE creating timers, registering I/O ports
* and other things which might pick up the default CS or end up
* calling back into the device.
*/
rc = PDMDevHlpCritSectInit(pDevIns, &pThis->CritSect, RT_SRC_POS, "Serial#%u", iInstance);
AssertRCReturn(rc, rc);
rc = PDMDevHlpSetDeviceCritSect(pDevIns, &pThis->CritSect);
AssertRCReturn(rc, rc);
rc = RTSemEventCreate(&pThis->ReceiveSem);
AssertRCReturn(rc, rc);
/*
* Create the timers.
*/
rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL, serialFifoTimer, pThis,
TMTIMER_FLAGS_DEFAULT_CRIT_SECT, "Serial Fifo Timer",
&pThis->fifo_timeout_timer);
AssertRCReturn(rc, rc);
rc = PDMDevHlpTMTimerCreate(pDevIns, TMCLOCK_VIRTUAL, serialTransmitTimer, pThis,
TMTIMER_FLAGS_DEFAULT_CRIT_SECT, "Serial Transmit Timer",
&pThis->transmit_timerR3);
AssertRCReturn(rc, rc);
pThis->transmit_timerR0 = TMTimerR0Ptr(pThis->transmit_timerR3);
pThis->transmit_timerRC = TMTimerRCPtr(pThis->transmit_timerR3);
serialReset(pDevIns);
#ifdef VBOX_SERIAL_PCI
/*
* Register the PCI Device and region.
*/
rc = PDMDevHlpPCIRegister(pDevIns, &pThis->PciDev);
if (RT_FAILURE(rc))
return rc;
rc = PDMDevHlpPCIIORegionRegister(pDevIns, 0, 8, PCI_ADDRESS_SPACE_IO, serialIOPortRegionMap);
if (RT_FAILURE(rc))
return rc;
#else /* !VBOX_SERIAL_PCI */
/*
* Register the I/O ports.
*/
pThis->base = io_base;
rc = PDMDevHlpIOPortRegister(pDevIns, io_base, 8, 0,
serialIOPortWrite, serialIOPortRead,
NULL, NULL, "SERIAL");
if (RT_FAILURE(rc))
return rc;
if (pThis->fGCEnabled)
{
rc = PDMDevHlpIOPortRegisterRC(pDevIns, io_base, 8, 0, "serialIOPortWrite",
"serialIOPortRead", NULL, NULL, "Serial");
if (RT_FAILURE(rc))
return rc;
}
if (pThis->fR0Enabled)
{
rc = PDMDevHlpIOPortRegisterR0(pDevIns, io_base, 8, 0, "serialIOPortWrite",
"serialIOPortRead", NULL, NULL, "Serial");
if (RT_FAILURE(rc))
return rc;
}
#endif /* !VBOX_SERIAL_PCI */
/*
* Saved state.
*/
rc = PDMDevHlpSSMRegister3(pDevIns, SERIAL_SAVED_STATE_VERSION, sizeof (*pThis),
serialLiveExec, serialSaveExec, serialLoadExec);
if (RT_FAILURE(rc))
return rc;
/*
* Attach the char driver and get the interfaces.
* For now no run-time changes are supported.
*/
rc = PDMDevHlpDriverAttach(pDevIns, 0, &pThis->IBase, &pThis->pDrvBase, "Serial Char");
if (RT_SUCCESS(rc))
{
pThis->pDrvChar = PDMIBASE_QUERY_INTERFACE(pThis->pDrvBase, PDMICHARCONNECTOR);
if (!pThis->pDrvChar)
{
AssertLogRelMsgFailed(("Configuration error: instance %d has no char interface!\n", iInstance));
return VERR_PDM_MISSING_INTERFACE;
}
/** @todo provide read notification interface!!!! */
}
else if (rc == VERR_PDM_NO_ATTACHED_DRIVER)
{
pThis->pDrvBase = NULL;
pThis->pDrvChar = NULL;
LogRel(("Serial%d: no unit\n", iInstance));
}
else
{
AssertLogRelMsgFailed(("Serial%d: Failed to attach to char driver. rc=%Rrc\n", iInstance, rc));
/* Don't call VMSetError here as we assume that the driver already set an appropriate error */
return rc;
}
return VINF_SUCCESS;
}
/**
* The device registration structure.
*/
const PDMDEVREG g_DeviceSerialPort =
{
/* u32Version */
PDM_DEVREG_VERSION,
/* szName */
"serial",
/* szRCMod */
"VBoxDDRC.rc",
/* szR0Mod */
"VBoxDDR0.r0",
/* pszDescription */
"Serial Communication Port",
/* fFlags */
PDM_DEVREG_FLAGS_DEFAULT_BITS | PDM_DEVREG_FLAGS_RC | PDM_DEVREG_FLAGS_R0,
/* fClass */
PDM_DEVREG_CLASS_SERIAL,
/* cMaxInstances */
UINT32_MAX,
/* cbInstance */
sizeof(DEVSERIAL),
/* pfnConstruct */
serialConstruct,
/* pfnDestruct */
serialDestruct,
/* pfnRelocate */
serialRelocate,
/* pfnMemSetup */
NULL,
/* pfnPowerOn */
NULL,
/* pfnReset */
serialReset,
/* pfnSuspend */
NULL,
/* pfnResume */
NULL,
/* pfnAttach */
NULL,
/* pfnDetach */
NULL,
/* pfnQueryInterface. */
NULL,
/* pfnInitComplete */
NULL,
/* pfnPowerOff */
NULL,
/* pfnSoftReset */
NULL,
/* u32VersionEnd */
PDM_DEVREG_VERSION
};
#endif /* IN_RING3 */
#endif /* !VBOX_DEVICE_STRUCT_TESTCASE */
| carmark/vbox | src/VBox/Devices/Serial/DevSerial.cpp | C++ | gpl-2.0 | 48,595 |
<?php
/**
* @package AcyMailing for Joomla!
* @version 4.9.1
* @author acyba.com
* @copyright (C) 2009-2015 ACYBA S.A.R.L. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><div class="acymailing_module<?php echo $params->get('moduleclass_sfx')?>" id="acymailing_module_<?php echo $formName; ?>">
<?php
if(!empty($mootoolsIntro)) echo '<p class="acymailing_mootoolsintro">'.$mootoolsIntro.'</p>'; ?>
<div class="acymailing_mootoolsbutton">
<?php
$link = "rel=\"{handler: 'iframe', size: {x: ".$params->get('boxwidth',250).", y: ".$params->get('boxheight',200)."}}\" class=\"modal acymailing_togglemodule\"";
$href=acymailing_completeLink('sub&task=display&autofocus=1&formid='.$module->id,true);
?>
<p><a <?php echo $link; ?> id="acymailing_togglemodule_<?php echo $formName; ?>" href="<?php echo $href;?>"><?php echo $mootoolsButton ?></a></p>
</div>
</div>
| proyectoseb/University | modules/mod_acymailing/tmpl/popup.php | PHP | gpl-2.0 | 967 |
<?php
class Stripe_ApiRequestor
{
private $_apiKey;
private $_apiBase;
private static $_preFlight = array();
private static $_blacklistedCerts = array(
'05c0b3643694470a888c6e7feb5c9e24e823dc53',
'5b7dc7fbc98d78bf76d4d4fa6f597a0c901fad5c',
);
public function __construct($apiKey=null, $apiBase=null)
{
$this->_apiKey = $apiKey;
if (!$apiBase) {
$apiBase = Stripe::$apiBase;
}
$this->_apiBase = $apiBase;
}
/**
* @param string|mixed $value A string to UTF8-encode.
*
* @returns string|mixed The UTF8-encoded string, or the object passed in if
* it wasn't a string.
*/
public static function utf8($value)
{
if (is_string($value)
&& mb_detect_encoding($value, "UTF-8", TRUE) != "UTF-8") {
return utf8_encode($value);
} else {
return $value;
}
}
private static function _encodeObjects($d)
{
if ($d instanceof Stripe_ApiResource) {
return self::utf8($d->id);
} else if ($d === true) {
return 'true';
} else if ($d === false) {
return 'false';
} else if (is_array($d)) {
$res = array();
foreach ($d as $k => $v)
$res[$k] = self::_encodeObjects($v);
return $res;
} else {
return self::utf8($d);
}
}
/**
* @param array $arr An map of param keys to values.
* @param string|null $prefix (It doesn't look like we ever use $prefix...)
*
* @returns string A querystring, essentially.
*/
public static function encode($arr, $prefix=null)
{
if (!is_array($arr))
return $arr;
$r = array();
foreach ($arr as $k => $v) {
if (is_null($v))
continue;
if ($prefix && $k && !is_int($k))
$k = $prefix."[".$k."]";
else if ($prefix)
$k = $prefix."[]";
if (is_array($v)) {
$r[] = self::encode($v, $k, true);
} else {
$r[] = urlencode($k)."=".urlencode($v);
}
}
return implode("&", $r);
}
/**
* @param string $method
* @param string $url
* @param array|null $params
* @param array|null $headers
*
* @return array An array whose first element is the response and second
* element is the API key used to make the request.
*/
public function request($method, $url, $params=null, $headers=null)
{
if (!$params) {
$params = array();
}
if (!$headers) {
$headers = array();
}
list($rbody, $rcode, $myApiKey) =
$this->_requestRaw($method, $url, $params, $headers);
$resp = $this->_interpretResponse($rbody, $rcode);
return array($resp, $myApiKey);
}
/**
* @param string $rbody A JSON string.
* @param int $rcode
* @param array $resp
*
* @throws Stripe_InvalidRequestError if the error is caused by the user.
* @throws Stripe_AuthenticationError if the error is caused by a lack of
* permissions.
* @throws Stripe_CardError if the error is the error code is 402 (payment
* required)
* @throws Stripe_ApiError otherwise.
*/
public function handleApiError($rbody, $rcode, $resp)
{
if (!is_array($resp) || !isset($resp['error'])) {
$msg = "Invalid response object from API: $rbody "
."(HTTP response code was $rcode)";
throw new Stripe_ApiError($msg, $rcode, $rbody, $resp);
}
$error = $resp['error'];
$msg = isset($error['message']) ? $error['message'] : null;
$param = isset($error['param']) ? $error['param'] : null;
$code = isset($error['code']) ? $error['code'] : null;
switch ($rcode) {
case 400:
if ($code == 'rate_limit') {
throw new Stripe_RateLimitError(
$msg, $param, $rcode, $rbody, $resp
);
}
case 404:
throw new Stripe_InvalidRequestError(
$msg, $param, $rcode, $rbody, $resp
);
case 401:
throw new Stripe_AuthenticationError($msg, $rcode, $rbody, $resp);
case 402:
throw new Stripe_CardError($msg, $param, $code, $rcode, $rbody, $resp);
default:
throw new Stripe_ApiError($msg, $rcode, $rbody, $resp);
}
}
private function _requestRaw($method, $url, $params, $headers)
{
if (!array_key_exists($this->_apiBase, self::$_preFlight)
|| !self::$_preFlight[$this->_apiBase]) {
self::$_preFlight[$this->_apiBase] = $this->checkSslCert($this->_apiBase);
}
$myApiKey = $this->_apiKey;
if (!$myApiKey) {
$myApiKey = Stripe::$apiKey;
}
if (!$myApiKey) {
$msg = 'No API key provided. (HINT: set your API key using '
. '"Stripe::setApiKey(<API-KEY>)". You can generate API keys from '
. 'the Stripe web interface. See https://stripe.com/api for '
. 'details, or email support@stripe.com if you have any questions.';
throw new Stripe_AuthenticationError($msg);
}
$absUrl = $this->_apiBase.$url;
$params = self::_encodeObjects($params);
$langVersion = phpversion();
$uname = php_uname();
$ua = array(
'bindings_version' => Stripe::VERSION,
'lang' => 'php',
'lang_version' => $langVersion,
'publisher' => 'stripe',
'uname' => $uname,
);
$defaultHeaders = array(
'X-Stripe-Client-User-Agent' => json_encode($ua),
'User-Agent' => 'Stripe/v1 PhpBindings/' . Stripe::VERSION,
'Authorization' => 'Bearer ' . $myApiKey,
);
if (Stripe::$apiVersion) {
$defaultHeaders['Stripe-Version'] = Stripe::$apiVersion;
}
$hasFile = false;
$hasCurlFile = class_exists('CURLFile', false);
foreach ($params as $k => $v) {
if (is_resource($v)) {
$hasFile = true;
$params[$k] = self::_processResourceParam($v, $hasCurlFile);
} else if ($hasCurlFile && $v instanceof CURLFile) {
$hasFile = true;
}
}
if ($hasFile) {
$defaultHeaders['Content-Type'] = 'multipart/form-data';
} else {
$defaultHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
}
$combinedHeaders = array_merge($defaultHeaders, $headers);
$rawHeaders = array();
foreach ($combinedHeaders as $header => $value) {
$rawHeaders[] = $header . ': ' . $value;
}
list($rbody, $rcode) = $this->_curlRequest(
$method,
$absUrl,
$rawHeaders,
$params,
$hasFile
);
return array($rbody, $rcode, $myApiKey);
}
private function _processResourceParam($resource, $hasCurlFile)
{
if (get_resource_type($resource) !== 'stream') {
throw new Stripe_ApiError(
'Attempted to upload a resource that is not a stream'
);
}
$metaData = stream_get_meta_data($resource);
if ($metaData['wrapper_type'] !== 'plainfile') {
throw new Stripe_ApiError(
'Only plainfile resource streams are supported'
);
}
if ($hasCurlFile) {
// We don't have the filename or mimetype, but the API doesn't care
return new CURLFile($metaData['uri']);
} else {
return '@'.$metaData['uri'];
}
}
private function _interpretResponse($rbody, $rcode)
{
try {
$resp = json_decode($rbody, true);
} catch (Exception $e) {
$msg = "Invalid response body from API: $rbody "
. "(HTTP response code was $rcode)";
throw new Stripe_ApiError($msg, $rcode, $rbody);
}
if ($rcode < 200 || $rcode >= 300) {
$this->handleApiError($rbody, $rcode, $resp);
}
return $resp;
}
private function _curlRequest($method, $absUrl, $headers, $params, $hasFile)
{
$curl = curl_init();
$method = strtolower($method);
$opts = array();
if ($method == 'get') {
if ($hasFile) {
throw new Stripe_ApiError(
"Issuing a GET request with a file parameter"
);
}
$opts[CURLOPT_HTTPGET] = 1;
if (count($params) > 0) {
$encoded = self::encode($params);
$absUrl = "$absUrl?$encoded";
}
} else if ($method == 'post') {
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = $hasFile ? $params : self::encode($params);
} else if ($method == 'delete') {
$opts[CURLOPT_CUSTOMREQUEST] = 'DELETE';
if (count($params) > 0) {
$encoded = self::encode($params);
$absUrl = "$absUrl?$encoded";
}
} else {
throw new Stripe_ApiError("Unrecognized method $method");
}
$absUrl = self::utf8($absUrl);
$opts[CURLOPT_URL] = $absUrl;
$opts[CURLOPT_RETURNTRANSFER] = true;
$opts[CURLOPT_CONNECTTIMEOUT] = 30;
$opts[CURLOPT_TIMEOUT] = 80;
$opts[CURLOPT_RETURNTRANSFER] = true;
$opts[CURLOPT_HTTPHEADER] = $headers;
if (!Stripe::$verifySslCerts)
$opts[CURLOPT_SSL_VERIFYPEER] = false;
curl_setopt_array($curl, $opts);
$rbody = curl_exec($curl);
if (!defined('CURLE_SSL_CACERT_BADFILE')) {
define('CURLE_SSL_CACERT_BADFILE', 77); // constant not defined in PHP
}
$errno = curl_errno($curl);
if ($errno == CURLE_SSL_CACERT ||
$errno == CURLE_SSL_PEER_CERTIFICATE ||
$errno == CURLE_SSL_CACERT_BADFILE) {
array_push(
$headers,
'X-Stripe-Client-Info: {"ca":"using Stripe-supplied CA bundle"}'
);
$cert = $this->caBundle();
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CAINFO, $cert);
$rbody = curl_exec($curl);
}
if ($rbody === false) {
$errno = curl_errno($curl);
$message = curl_error($curl);
curl_close($curl);
$this->handleCurlError($errno, $message);
}
$rcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return array($rbody, $rcode);
}
/**
* @param number $errno
* @param string $message
* @throws Stripe_ApiConnectionError
*/
public function handleCurlError($errno, $message)
{
$apiBase = $this->_apiBase;
switch ($errno) {
case CURLE_COULDNT_CONNECT:
case CURLE_COULDNT_RESOLVE_HOST:
case CURLE_OPERATION_TIMEOUTED:
$msg = "Could not connect to Stripe ($apiBase). Please check your "
. "internet connection and try again. If this problem persists, "
. "you should check Stripe's service status at "
. "https://twitter.com/stripestatus, or";
break;
case CURLE_SSL_CACERT:
case CURLE_SSL_PEER_CERTIFICATE:
$msg = "Could not verify Stripe's SSL certificate. Please make sure "
. "that your network is not intercepting certificates. "
. "(Try going to $apiBase in your browser.) "
. "If this problem persists,";
break;
default:
$msg = "Unexpected error communicating with Stripe. "
. "If this problem persists,";
}
$msg .= " let us know at support@stripe.com.";
$msg .= "\n\n(Network error [errno $errno]: $message)";
throw new Stripe_ApiConnectionError($msg);
}
/**
* Preflight the SSL certificate presented by the backend. This isn't 100%
* bulletproof, in that we're not actually validating the transport used to
* communicate with Stripe, merely that the first attempt to does not use a
* revoked certificate.
*
* Unfortunately the interface to OpenSSL doesn't make it easy to check the
* certificate before sending potentially sensitive data on the wire. This
* approach raises the bar for an attacker significantly.
*/
private function checkSslCert($url)
{
if (!function_exists('stream_context_get_params') ||
!function_exists('stream_socket_enable_crypto')) {
error_log(
'Warning: This version of PHP does not support checking SSL '.
'certificates Stripe cannot guarantee that the server has a '.
'certificate which is not blacklisted.'
);
return true;
}
$url = parse_url($url);
$port = isset($url["port"]) ? $url["port"] : 443;
$url = "ssl://{$url["host"]}:{$port}";
$sslContext = stream_context_create(
array('ssl' => array(
'capture_peer_cert' => true,
'verify_peer' => true,
'cafile' => $this->caBundle(),
))
);
$result = stream_socket_client(
$url, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $sslContext
);
if (($errno !== 0 && $errno !== NULL) || $result === false) {
throw new Stripe_ApiConnectionError(
'Could not connect to Stripe (' . $url . '). Please check your '.
'internet connection and try again. If this problem persists, '.
'you should check Stripe\'s service status at '.
'https://twitter.com/stripestatus. Reason was: '.$errstr
);
}
$params = stream_context_get_params($result);
$cert = $params['options']['ssl']['peer_certificate'];
openssl_x509_export($cert, $pemCert);
if (self::isBlackListed($pemCert)) {
throw new Stripe_ApiConnectionError(
'Invalid server certificate. You tried to connect to a server that '.
'has a revoked SSL certificate, which means we cannot securely send '.
'data to that server. Please email support@stripe.com if you need '.
'help connecting to the correct API server.'
);
}
return true;
}
/* Checks if a valid PEM encoded certificate is blacklisted
* @return boolean
*/
public static function isBlackListed($certificate)
{
$certificate = trim($certificate);
$lines = explode("\n", $certificate);
// Kludgily remove the PEM padding
array_shift($lines); array_pop($lines);
$derCert = base64_decode(implode("", $lines));
$fingerprint = sha1($derCert);
return in_array($fingerprint, self::$_blacklistedCerts);
}
private function caBundle()
{
return dirname(__FILE__) . '/../data/ca-certificates.crt';
}
} | vilmark/vilmark_main | wp-content/plugins/pro-sites/pro-sites-files/gateways/gateway-stripe-files/lib/Stripe/ApiRequestor.php | PHP | gpl-2.0 | 13,813 |
class Solution {
public:
bool is_fill(vector<vector<char>>&board, int row, int col, char ch)
{
for(int i = 0; i<9; ++i)
{
if((i!=row && board[i][col]==ch)||(i!=col && board[row][i]==ch))
return false;
}
int left_row, left_col, right_row, right_col;
if(row % 3 ==2)
{
left_row = row-2;
right_row = row;
}
else if(row % 3 ==1)
{
left_row = row-1;
right_row = row+1;
}
else
{
left_row = row;
right_row = row+2;
}
if(col % 3 ==2)
{
right_col = col;
left_col = col-2;
}
else if(col % 3 ==1)
{
left_col = col-1;
right_col = col+1;
}
else
{
left_col = col;
right_col = col + 2;
}
for(int i = left_row; i<=right_row; ++i)
for(int j = left_col; j<=right_col; ++j)
if(i!=row && j!=col && board[i][j]==ch)
return false;
return true;
}
bool isValidSudoku(vector<vector<char> > &board) {
if(board.empty() || board.size()!=9)
return false;
for(int i = 0; i<board.size(); ++i)
{
for(int j = 0; j<board[i].size(); ++j)
{
if(board[i][j]!='.' && !is_fill(board, i, j, board[i][j]))
{
return false;
}
}
}
return true;
}
};
//Solution Two
class Solution {
private:
bool rowArr[9], colArr[9], nineGrid[9];
bool checkRow(vector<vector<char> > &board, int row){
if(rowArr[row])
return true;
vector<bool>vec(10, false);
for(int i = 0; i<9; ++i) {
if(board[row][i]=='.')
continue;
if(vec[board[row][i]-'0'])
return false;
vec[board[row][i]-'0'] = true;
}
rowArr[row] = true;
return true;
}
bool checkCol(vector<vector<char> > &board, int col) {
if(colArr[col])
return true;
vector<bool>vec(10, false);
for(int i = 0; i<9; ++i) {
if(board[i][col]=='.')
continue;
if(vec[board[i][col]-'0'])
return false;
vec[board[i][col]-'0'] = true;
}
colArr[col] = true;
return true;
}
bool checkNineGrid(vector<vector<char> > &board, int row, int col) {
int cnt = (row / 3)*3 + col / 3;
if(nineGrid[cnt])
return true;
vector<bool>vec(10, false);
for(int i = row / 3 * 3; i <= row / 3 * 3 + 2; ++i) {
for(int j = col / 3 * 3; j <= col / 3 * 3 + 2; ++j) {
if(board[i][j]=='.')
continue;
if(vec[board[i][j]-'0'])
return false;
vec[board[i][j]-'0'] = true;
}
}
return true;
}
public:
bool isValidSudoku(vector<vector<char> > &board) {
memset(rowArr, false, sizeof(rowArr));
memset(colArr, false, sizeof(colArr));
memset(nineGrid, false, sizeof(nineGrid));
for(int i = 0; i<9; ++i) {
for(int j = 0; j<9; ++j) {
if(board[i][j]!='.') {
if(!checkRow(board, i) || !checkCol(board, j) || !checkNineGrid(board, i, j))
return false;
}
}
}
return true;
}
};
| kunth/Leetcode | Leetcode_valid-sudoku.cc | C++ | gpl-2.0 | 3,621 |
/*---------------------------------------------------------------------------*\
## #### ###### |
## ## ## | Copyright: ICE Stroemungsfoschungs GmbH
## ## #### |
## ## ## | http://www.ice-sf.at
## #### ###### |
-------------------------------------------------------------------------------
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright held by original author
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is based on OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::faForceEquation
Description
Force a fvMatrix to fixed values in specific places
SourceFiles
faForceEquation.C
Contributors/Copyright:
2011, 2013-2014 Bernhard F.W. Gschaider <bgschaid@ice-sf.at>
SWAK Revision: $Id$
\*---------------------------------------------------------------------------*/
#ifndef faForceEquation_H
#define faForceEquation_H
#include "FaFieldValueExpressionDriver.H"
#include "faMatrix.H"
#include "DynamicList.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
/*---------------------------------------------------------------------------*\
Class faForceEquation Declaration
\*---------------------------------------------------------------------------*/
template<class T>
class faForceEquation
:
protected FaFieldValueExpressionDriver
{
// Private data
faForceEquation(const faForceEquation&);
string valueExpression_;
string maskExpression_;
bool verbose_;
bool getMask(DynamicList<label> &,const word &psi);
public:
// Constructors
//- Construct from a dictionary
faForceEquation
(
const dictionary& ,
const fvMesh&
);
// Destructor
virtual ~faForceEquation();
//- fix equations
void operator()(faMatrix<T> &);
//- where are the equations fixed
tmp<areaScalarField> getMask();
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| Unofficial-Extend-Project-Mirror/openfoam-extend-Breeder1.7-libraries-swak4Foam | Libraries/swakFiniteArea/expressionSource/faForceEquation.H | C++ | gpl-2.0 | 3,071 |
/*
* libretroshare/src/services p3gxscircles.cc
*
* Circles Interface for RetroShare.
*
* Copyright 2012-2012 by Robert Fernie.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "retroshare@lunamutt.com".
*
*/
#include "services/p3gxscircles.h"
#include "serialiser/rsgxscircleitems.h"
#include "retroshare/rsgxsflags.h"
#include "util/rsrandom.h"
#include "util/rsstring.h"
#include "pgp/pgpauxutils.h"
#include <sstream>
#include <stdio.h>
/****
* #define DEBUG_CIRCLES 1
****/
RsGxsCircles *rsGxsCircles = NULL;
/******
*
* GxsCircles are used to limit the spread of Gxs Groups and Messages.
*
* This is done via GxsCircle parameters in GroupMetaData:
* mCircleType (ALL, External, Internal).
* mCircleId.
*
* The Circle Group contains the definition of who is allowed access to the Group.
* and GXS asks this service before forwarding any data.
*
* The CircleGroup contains:
* list of GxsId's
* list of GxsCircleId's (subcircles also allowed).
*
* This service runs a background task to transform the CircleGroups
* into a list of friends/peers who are allowed access.
* These results are cached to provide GXS with quick access to the information.
* This involves:
* - fetching the GroupData via GXS.
* - querying the list of GxsId to see if they are known.
* (NB: this will cause caching of GxsId in p3IdService.
* - recursively loading subcircles to complete Circle definition.
* - saving the result into Cache.
*
* For Phase 1, we will only use the list of GxsIds. No subcircles will be allowed.
* Recursively determining membership via sub-circles is complex and needs more thought.
* The data-types for the full system, however, will be in-place.
*/
#define CIRCLEREQ_CACHELOAD 0x0001
#define CIRCLEREQ_CIRCLE_LIST 0x0002
//#define CIRCLEREQ_PGPHASH 0x0010
//#define CIRCLEREQ_REPUTATION 0x0020
//#define CIRCLEREQ_CACHETEST 0x1000
// Events.
#define CIRCLE_EVENT_LOADIDS 0x0001
#define CIRCLE_EVENT_CACHELOAD 0x0002
#define CIRCLE_EVENT_RELOADIDS 0x0003
#define CIRCLE_EVENT_DUMMYSTART 0x0004
#define CIRCLE_EVENT_DUMMYLOAD 0x0005
#define CIRCLE_EVENT_DUMMYGEN 0x0006
#define CIRCLE_DUMMY_STARTPERIOD 300 // MUST BE LONG ENOUGH FOR IDS TO HAVE BEEN MADE.
#define CIRCLE_DUMMY_GENPERIOD 10
//#define CIRCLE_EVENT_CACHETEST 0x1000
//#define CACHETEST_PERIOD 60
//#define OWNID_RELOAD_DELAY 10
#define GXSID_LOAD_CYCLE 10 // GXSID completes a load in this period.
#define MIN_CIRCLE_LOAD_GAP 5
/********************************************************************************/
/******************* Startup / Tick ******************************************/
/********************************************************************************/
p3GxsCircles::p3GxsCircles(RsGeneralDataService *gds, RsNetworkExchangeService *nes,
p3IdService *identities, PgpAuxUtils *pgpUtils)
: RsGxsCircleExchange(gds, nes, new RsGxsCircleSerialiser(),
RS_SERVICE_GXS_TYPE_GXSCIRCLE, identities, circleAuthenPolicy()),
RsGxsCircles(this), GxsTokenQueue(this), RsTickEvent(),
mIdentities(identities),
mPgpUtils(pgpUtils),
mCircleMtx("p3GxsCircles"),
mCircleCache(DEFAULT_MEM_CACHE_SIZE, "GxsCircleCache")
{
// Kick off Cache Testing, + Others.
//RsTickEvent::schedule_in(CIRCLE_EVENT_CACHETEST, CACHETEST_PERIOD);
RsTickEvent::schedule_now(CIRCLE_EVENT_LOADIDS);
// Dummy Circles.
// RsTickEvent::schedule_in(CIRCLE_EVENT_DUMMYSTART, CIRCLE_DUMMY_STARTPERIOD);
mDummyIdToken = 0;
}
const std::string GXS_CIRCLES_APP_NAME = "gxscircle";
const uint16_t GXS_CIRCLES_APP_MAJOR_VERSION = 1;
const uint16_t GXS_CIRCLES_APP_MINOR_VERSION = 0;
const uint16_t GXS_CIRCLES_MIN_MAJOR_VERSION = 1;
const uint16_t GXS_CIRCLES_MIN_MINOR_VERSION = 0;
RsServiceInfo p3GxsCircles::getServiceInfo()
{
return RsServiceInfo(RS_SERVICE_GXS_TYPE_GXSCIRCLE,
GXS_CIRCLES_APP_NAME,
GXS_CIRCLES_APP_MAJOR_VERSION,
GXS_CIRCLES_APP_MINOR_VERSION,
GXS_CIRCLES_MIN_MAJOR_VERSION,
GXS_CIRCLES_MIN_MINOR_VERSION);
}
uint32_t p3GxsCircles::circleAuthenPolicy()
{
uint32_t policy = 0;
uint8_t flag = 0;
//flag = GXS_SERV::MSG_AUTHEN_ROOT_PUBLISH_SIGN;
//flag = GXS_SERV::MSG_AUTHEN_CHILD_PUBLISH_SIGN;
//flag = GXS_SERV::MSG_AUTHEN_ROOT_AUTHOR_SIGN;
//flag = GXS_SERV::MSG_AUTHEN_CHILD_AUTHOR_SIGN;
RsGenExchange::setAuthenPolicyFlag(flag, policy, RsGenExchange::PUBLIC_GRP_BITS);
RsGenExchange::setAuthenPolicyFlag(flag, policy, RsGenExchange::RESTRICTED_GRP_BITS);
RsGenExchange::setAuthenPolicyFlag(flag, policy, RsGenExchange::PRIVATE_GRP_BITS);
flag = 0;
//flag = GXS_SERV::GRP_OPTION_AUTHEN_AUTHOR_SIGN;
RsGenExchange::setAuthenPolicyFlag(flag, policy, RsGenExchange::GRP_OPTION_BITS);
return policy;
}
void p3GxsCircles::service_tick()
{
RsTickEvent::tick_events();
GxsTokenQueue::checkRequests(); // GxsTokenQueue handles all requests.
return;
}
void p3GxsCircles::notifyChanges(std::vector<RsGxsNotify *> &changes)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::notifyChanges()";
std::cerr << std::endl;
#endif
std::vector<RsGxsNotify *>::iterator it;
for(it = changes.begin(); it != changes.end(); ++it)
{
RsGxsGroupChange *groupChange = dynamic_cast<RsGxsGroupChange *>(*it);
RsGxsMsgChange *msgChange = dynamic_cast<RsGxsMsgChange *>(*it);
if (msgChange && !msgChange->metaChange())
{
#ifdef DEBUG_CIRCLES
std::cerr << " Found Message Change Notification";
std::cerr << std::endl;
#endif
std::map<RsGxsGroupId, std::vector<RsGxsMessageId> > &msgChangeMap = msgChange->msgChangeMap;
std::map<RsGxsGroupId, std::vector<RsGxsMessageId> >::iterator mit;
for(mit = msgChangeMap.begin(); mit != msgChangeMap.end(); ++mit)
{
#ifdef DEBUG_CIRCLES
std::cerr << " Msgs for Group: " << mit->first;
std::cerr << std::endl;
#endif
}
}
/* add groups to ExternalIdList (Might get Personal Circles here until NetChecks in place) */
if (groupChange && !groupChange->metaChange())
{
#ifdef DEBUG_CIRCLES
std::cerr << " Found Group Change Notification";
std::cerr << std::endl;
#endif
std::list<RsGxsGroupId> &groupList = groupChange->mGrpIdList;
std::list<RsGxsGroupId>::iterator git;
for(git = groupList.begin(); git != groupList.end(); ++git)
{
#ifdef DEBUG_CIRCLES
std::cerr << " Incoming Group: " << *git << ". Forcing cache load." << std::endl;
#endif
// for new circles we need to add them to the list.
// we don't know the type of this circle here
// original behavior was to add all ids to the external ids list
addCircleIdToList(RsGxsCircleId(*git), 0);
// reset the cached circle data for this id
{
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
mCircleCache.erase(RsGxsCircleId(*git));
}
}
}
if(groupChange)
for(std::list<RsGxsGroupId>::const_iterator git(groupChange->mGrpIdList.begin());git!=groupChange->mGrpIdList.end();++git)
{
#ifdef DEBUG_CIRCLES
std::cerr << " forcing cache loading for circle " << *git << " in order to trigger subscribe update." << std::endl;
#endif
force_cache_reload(RsGxsCircleId(*git)) ;
}
}
RsGxsIfaceHelper::receiveChanges(changes); // this clear up the vector and delete its elements
}
/********************************************************************************/
/******************* RsCircles Interface ***************************************/
/********************************************************************************/
bool p3GxsCircles:: getCircleDetails(const RsGxsCircleId &id, RsGxsCircleDetails &details)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::getCircleDetails(" << id << ")";
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
{
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
if (mCircleCache.is_cached(id))
{
RsGxsCircleCache &data = mCircleCache.ref(id);
// should also have meta data....
details.mCircleId = id;
details.mCircleName = data.mCircleName;
details.mCircleType = data.mCircleType;
details.mIsExternal = data.mIsExternal;
details.mAllowedAnonPeers = data.mAllowedAnonPeers;
details.mAllowedSignedPeers = data.mAllowedSignedPeers;
details.mAmIAllowed = data.mAmIAllowed ;
return true;
}
}
/* it isn't there - add to public requests */
cache_request_load(id);
return false;
}
bool p3GxsCircles:: getCirclePersonalIdList(std::list<RsGxsCircleId> &circleIds)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::getCircleIdList()";
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
if (circleIds.empty())
{
circleIds = mCirclePersonalIdList;
}
else
{
std::list<RsGxsCircleId>::const_iterator it;
for(it = mCirclePersonalIdList.begin(); it != mCirclePersonalIdList.begin(); ++it)
{
circleIds.push_back(*it);
}
}
return true;
}
bool p3GxsCircles:: getCircleExternalIdList(std::list<RsGxsCircleId> &circleIds)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::getCircleIdList()";
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
if (circleIds.empty())
{
circleIds = mCircleExternalIdList;
}
else
{
std::list<RsGxsCircleId>::const_iterator it;
for(it = mCircleExternalIdList.begin(); it != mCircleExternalIdList.begin(); ++it)
{
circleIds.push_back(*it);
}
}
return true;
}
/********************************************************************************/
/******************* RsGcxs Interface ***************************************/
/********************************************************************************/
bool p3GxsCircles::isLoaded(const RsGxsCircleId &circleId)
{
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
return mCircleCache.is_cached(circleId);
}
bool p3GxsCircles::loadCircle(const RsGxsCircleId &circleId)
{
return cache_request_load(circleId);
}
int p3GxsCircles::canSend(const RsGxsCircleId &circleId, const RsPgpId &id, bool& should_encrypt)
{
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
if (mCircleCache.is_cached(circleId))
{
RsGxsCircleCache &data = mCircleCache.ref(circleId);
should_encrypt = (data.mCircleType == GXS_CIRCLE_TYPE_EXTERNAL);
if (data.isAllowedPeer(id))
return 1;
return 0;
}
return -1;
}
int p3GxsCircles::canReceive(const RsGxsCircleId &circleId, const RsPgpId &id)
{
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
if (mCircleCache.is_cached(circleId))
{
RsGxsCircleCache &data = mCircleCache.ref(circleId);
if (data.isAllowedPeer(id))
{
return 1;
}
return 0;
}
return -1;
}
bool p3GxsCircles::recipients(const RsGxsCircleId &circleId, std::list<RsPgpId>& friendlist)
{
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
if (mCircleCache.is_cached(circleId))
{
RsGxsCircleCache &data = mCircleCache.ref(circleId);
data.getAllowedPeersList(friendlist);
return true;
}
return false;
}
bool p3GxsCircles::isRecipient(const RsGxsCircleId &circleId, const RsGxsId& id)
{
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
if (mCircleCache.is_cached(circleId))
{
const RsGxsCircleCache &data = mCircleCache.ref(circleId);
return data.isAllowedPeer(id);
}
return false;
}
bool p3GxsCircles::recipients(const RsGxsCircleId& circleId, std::list<RsGxsId>& gxs_ids)
{
RsGxsCircleDetails details ;
if(!getCircleDetails(circleId, details))
return false;
for(std::set<RsGxsId>::const_iterator it(details.mAllowedAnonPeers.begin());it!=details.mAllowedAnonPeers.end();++it)
gxs_ids.push_back(*it) ;
for(std::map<RsPgpId,std::set<RsGxsId> >::const_iterator it(details.mAllowedSignedPeers.begin());it!=details.mAllowedSignedPeers.end();++it)
for(std::set<RsGxsId>::const_iterator it2(it->second.begin());it2!=it->second.end();++it2)
gxs_ids.push_back(*it2) ;
return true;
}
/********************************************************************************/
/******************* Get/Set Data ******************************************/
/********************************************************************************/
bool p3GxsCircles::getGroupData(const uint32_t &token, std::vector<RsGxsCircleGroup> &groups)
{
std::vector<RsGxsGrpItem*> grpData;
bool ok = RsGenExchange::getGroupData(token, grpData);
if(ok)
{
std::vector<RsGxsGrpItem*>::iterator vit = grpData.begin();
for(; vit != grpData.end(); ++vit)
{
RsGxsCircleGroupItem* item = dynamic_cast<RsGxsCircleGroupItem*>(*vit);
if (item)
{
RsGxsCircleGroup group;
item->convertTo(group);
// If its cached - add that info (TODO).
groups.push_back(group);
delete(item);
}
else
{
std::cerr << "p3GxsCircles::getGroupData()";
std::cerr << " Not a RsGxsCircleGroupItem, deleting!";
std::cerr << std::endl;
delete *vit;
}
}
}
return ok;
}
/********************************************************************************/
/********************************************************************************/
/********************************************************************************/
void p3GxsCircles::createGroup(uint32_t& token, RsGxsCircleGroup &group)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::createGroup()";
std::cerr << " CircleType: " << (uint32_t) group.mMeta.mCircleType;
std::cerr << " CircleId: " << group.mMeta.mCircleId.toStdString();
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
RsGxsCircleGroupItem* item = new RsGxsCircleGroupItem();
item->convertFrom(group);
RsGenExchange::publishGroup(token, item);
}
void p3GxsCircles::updateGroup(uint32_t &token, RsGxsCircleGroup &group)
{
// note: refresh of circle cache gets triggered in the RsGenExchange::notifyChanges() callback
RsGxsCircleGroupItem* item = new RsGxsCircleGroupItem();
item->convertFrom(group);
RsGenExchange::updateGroup(token, item);
}
RsGenExchange::ServiceCreate_Return p3GxsCircles::service_CreateGroup(RsGxsGrpItem* grpItem, RsTlvSecurityKeySet& /*keySet*/)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::service_CreateGroup()";
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
RsGxsCircleGroupItem *item = dynamic_cast<RsGxsCircleGroupItem *>(grpItem);
if (!item)
{
std::cerr << "p3GxsCircles::service_CreateGroup() ERROR invalid cast";
std::cerr << std::endl;
return SERVICE_CREATE_FAIL;
}
// Now copy the GroupId into the mCircleId, and set the mode.
if (item->meta.mCircleType == GXS_CIRCLE_TYPE_EXT_SELF)
{
item->meta.mCircleType = GXS_CIRCLE_TYPE_EXTERNAL;
item->meta.mCircleId = RsGxsCircleId(item->meta.mGroupId);
}
// the advantage of adding the id to the list now is, that we know the cirlce type at this point
// this is not the case in NotifyChanges()
addCircleIdToList(RsGxsCircleId(item->meta.mGroupId), item->meta.mCircleType);
return SERVICE_CREATE_SUCCESS;
}
/************************************************************************************/
/************************************************************************************/
/************************************************************************************/
/*
* Cache of recently used circles.
*/
RsGxsCircleCache::RsGxsCircleCache()
{
mCircleType = GXS_CIRCLE_TYPE_EXTERNAL;
mIsExternal = true;
mAmIAllowed = false ;
mUpdateTime = 0;
mGroupStatus = 0;
mGroupSubscribeFlags = 0;
return;
}
bool RsGxsCircleCache::loadBaseCircle(const RsGxsCircleGroup &circle)
{
mCircleId = RsGxsCircleId(circle.mMeta.mGroupId);
mCircleName = circle.mMeta.mGroupName;
mUpdateTime = time(NULL);
// mProcessedCircles.insert(mCircleId);
mCircleType = circle.mMeta.mCircleType;
mIsExternal = (mCircleType != GXS_CIRCLE_TYPE_LOCAL);
mGroupStatus = circle.mMeta.mGroupStatus;
mGroupSubscribeFlags = circle.mMeta.mSubscribeFlags;
mAmIAllowed = false ; // by default. Will be computed later.
#ifdef DEBUG_CIRCLES
std::cerr << "RsGxsCircleCache::loadBaseCircle(" << mCircleId << ")";
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
return true;
}
bool RsGxsCircleCache::loadSubCircle(const RsGxsCircleCache &subcircle)
{
/* copy across all the lists */
/* should not be any unprocessed circles or peers */
#ifdef DEBUG_CIRCLES
#endif // DEBUG_CIRCLES
std::cerr << "RsGxsCircleCache::loadSubCircle(" << subcircle.mCircleId << ") TODO";
std::cerr << std::endl;
return true;
}
bool RsGxsCircleCache::getAllowedPeersList(std::list<RsPgpId> &friendlist) const
{
std::map<RsPgpId, std::set<RsGxsId> >::const_iterator it;
for(it = mAllowedSignedPeers.begin(); it != mAllowedSignedPeers.end(); ++it)
{
friendlist.push_back(it->first);
}
return true;
}
bool RsGxsCircleCache::isAllowedPeer(const RsGxsId &id) const
{
if(mUnprocessedPeers.find(id) != mUnprocessedPeers.end())
return true ;
if(mAllowedAnonPeers.find(id) != mAllowedAnonPeers.end())
return true ;
for(std::map<RsPgpId,std::set<RsGxsId> >::const_iterator it = mAllowedSignedPeers.begin();it!=mAllowedSignedPeers.end();++it)
if(it->second.find(id) != it->second.end())
return true ;
return false ;
}
bool RsGxsCircleCache::isAllowedPeer(const RsPgpId &id) const
{
std::map<RsPgpId, std::set<RsGxsId> >::const_iterator it = mAllowedSignedPeers.find(id);
if (it != mAllowedSignedPeers.end())
{
return true;
}
return false;
}
bool RsGxsCircleCache::addAllowedPeer(const RsPgpId &pgpId, const RsGxsId &gxsId)
{
/* created if doesn't exist */
mAllowedSignedPeers[pgpId].insert(gxsId);
return true;
}
bool RsGxsCircleCache::addLocalFriend(const RsPgpId &pgpId)
{
/* empty list as no GxsID associated */
mAllowedSignedPeers.insert(std::make_pair(pgpId,std::set<RsGxsId>()));
return true;
}
/************************************************************************************/
/************************************************************************************/
bool p3GxsCircles::request_CircleIdList()
{
/* trigger request to load missing ids into cache */
std::list<RsGxsGroupId> groupIds;
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::request_CircleIdList()";
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
uint32_t ansType = RS_TOKREQ_ANSTYPE_SUMMARY;
RsTokReqOptions opts;
opts.mReqType = GXS_REQUEST_TYPE_GROUP_META;
uint32_t token = 0;
RsGenExchange::getTokenService()->requestGroupInfo(token, ansType, opts);
GxsTokenQueue::queueRequest(token, CIRCLEREQ_CIRCLE_LIST);
return 1;
}
bool p3GxsCircles::load_CircleIdList(uint32_t token)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::load_CircleIdList() : " << token;
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
std::list<RsGroupMetaData> groups;
bool ok = RsGenExchange::getGroupMeta(token, groups);
if(ok)
{
// Save List
{
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
mCirclePersonalIdList.clear();
mCircleExternalIdList.clear();
}
for(std::list<RsGroupMetaData>::iterator it = groups.begin(); it != groups.end(); ++it)
{
addCircleIdToList(RsGxsCircleId(it->mGroupId), it->mCircleType);
}
}
else
{
std::cerr << "p3GxsCircles::load_CircleIdList() ERROR no data";
std::cerr << std::endl;
return false;
}
return true;
}
/****************************************************************************/
// ID STUFF. \/ \/ \/ \/ \/ \/ \/ :)
/****************************************************************************/
#if 0
/************************************************************************************/
/************************************************************************************/
bool p3GxsCircles::cachetest_getlist()
{
std::cerr << "p3GxsCircles::cachetest_getlist() making request";
std::cerr << std::endl;
uint32_t ansType = RS_TOKREQ_ANSTYPE_LIST;
RsTokReqOptions opts;
opts.mReqType = GXS_REQUEST_TYPE_GROUP_IDS;
uint32_t token = 0;
RsGenExchange::getTokenService()->requestGroupInfo(token, ansType, opts);
GxsTokenQueue::queueRequest(token, CIRCLEREQ_CACHETEST);
// Schedule Next Event.
RsTickEvent::schedule_in(CIRCLE_EVENT_CACHETEST, CACHETEST_PERIOD);
return true;
}
bool p3GxsCircles::cachetest_handlerequest(uint32_t token)
{
std::cerr << "p3GxsCircles::cachetest_handlerequest() token: " << token;
std::cerr << std::endl;
std::list<RsGxsId> grpIds;
bool ok = RsGenExchange::getGroupList(token, grpIds);
if(ok)
{
std::list<RsGxsId>::iterator vit = grpIds.begin();
for(; vit != grpIds.end(); ++vit)
{
/* 5% chance of checking it! */
if (RSRandom::random_f32() < 0.25)
{
std::cerr << "p3GxsCircles::cachetest_request() Testing Id: " << *vit;
std::cerr << std::endl;
/* try the cache! */
if (!haveKey(*vit))
{
std::list<PeerId> nullpeers;
requestKey(*vit, nullpeers);
std::cerr << "p3GxsCircles::cachetest_request() Requested Key Id: " << *vit;
std::cerr << std::endl;
}
else
{
RsTlvSecurityKey seckey;
if (getKey(*vit, seckey))
{
std::cerr << "p3GxsCircles::cachetest_request() Got Key OK Id: " << *vit;
std::cerr << std::endl;
// success!
seckey.print(std::cerr, 10);
std::cerr << std::endl;
}
else
{
std::cerr << "p3GxsCircles::cachetest_request() ERROR no Key for Id: " << *vit;
std::cerr << std::endl;
}
}
/* try private key too! */
if (!havePrivateKey(*vit))
{
requestPrivateKey(*vit);
std::cerr << "p3GxsCircles::cachetest_request() Requested PrivateKey Id: " << *vit;
std::cerr << std::endl;
}
else
{
RsTlvSecurityKey seckey;
if (getPrivateKey(*vit, seckey))
{
// success!
std::cerr << "p3GxsCircles::cachetest_request() Got PrivateKey OK Id: " << *vit;
std::cerr << std::endl;
}
else
{
std::cerr << "p3GxsCircles::cachetest_request() ERROR no PrivateKey for Id: " << *vit;
std::cerr << std::endl;
}
}
}
}
}
else
{
std::cerr << "p3GxsCircles::cache_load_for_token() ERROR no data";
std::cerr << std::endl;
return false;
}
return true;
}
/****************************************************************************/
// ID STUFF. /\ /\ /\ /\ /\ /\ /\ /\ :)
/****************************************************************************/
#endif
/************************************************************************************/
/************************************************************************************/
/************************************************************************************/
// Complicated deal of loading Circles.
bool p3GxsCircles::force_cache_reload(const RsGxsCircleId& id)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::force_cache_reload(): Forcing cache reload of Circle ID " << id << std::endl;
#endif
{
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
#ifdef DEBUG_CIRCLES
std::cerr << " clearing from existing cache entries..." << std::endl;
#endif
std::map<RsGxsCircleId, RsGxsCircleCache>::iterator it = mLoadingCache.find(id);
if (it != mLoadingCache.end())
{
mLoadingCache.erase(it) ;
#ifdef DEBUG_CIRCLES
std::cerr << " removed item from currently loading cache entries..." << std::endl;
#endif
}
mCircleCache.erase(id) ;
}
cache_request_load(id) ;
return true ;
}
bool p3GxsCircles::cache_request_load(const RsGxsCircleId &id)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::cache_request_load(" << id << ")";
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
{
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
/* check its not loaded */
if (mCircleCache.is_cached(id))
return true;
/* check it is not already being loaded */
std::map<RsGxsCircleId, RsGxsCircleCache>::iterator it;
it = mLoadingCache.find(id);
if (it != mLoadingCache.end())
{
// Already loading.
return true;
}
// Put it into the Loading Cache - so we will detect it later.
mLoadingCache[id] = RsGxsCircleCache();
mCacheLoad_ToCache.push_back(id);
}
if (RsTickEvent::event_count(CIRCLE_EVENT_CACHELOAD) > 0)
{
/* its already scheduled */
return true;
}
int32_t age = 0;
if (RsTickEvent::prev_event_ago(CIRCLE_EVENT_CACHELOAD, age))
{
if (age < MIN_CIRCLE_LOAD_GAP)
{
RsTickEvent::schedule_in(CIRCLE_EVENT_CACHELOAD,
MIN_CIRCLE_LOAD_GAP - age);
return true;
}
}
RsTickEvent::schedule_now(CIRCLE_EVENT_CACHELOAD);
return true;
}
bool p3GxsCircles::cache_start_load()
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::cache_start_load()";
std::cerr << std::endl;
#endif // DEBUG_CIRCLESmatch
/* trigger request to load missing ids into cache */
std::list<RsGxsGroupId> groupIds;
{
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
/* now we process the modGroupList -> a map so we can use it easily later, and create id list too */
std::list<RsGxsCircleId>::iterator it;
for(it = mCacheLoad_ToCache.begin(); it != mCacheLoad_ToCache.end(); ++it)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::cache_start_load() GroupId: " << *it;
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
groupIds.push_back(RsGxsGroupId(it->toStdString())); // might need conversion?
}
mCacheLoad_ToCache.clear();
}
if (groupIds.size() > 0)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::cache_start_load() #Groups: " << groupIds.size();
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
uint32_t ansType = RS_TOKREQ_ANSTYPE_DATA;
RsTokReqOptions opts;
opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA;
uint32_t token = 0;
RsGenExchange::getTokenService()->requestGroupInfo(token, ansType, opts, groupIds);
GxsTokenQueue::queueRequest(token, CIRCLEREQ_CACHELOAD);
}
return 1;
}
bool p3GxsCircles::cache_load_for_token(uint32_t token)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::cache_load_for_token() : " << token << std::endl;
#endif // DEBUG_CIRCLES
std::vector<RsGxsGrpItem*> grpData;
bool ok = RsGenExchange::getGroupData(token, grpData);
if(ok)
{
std::vector<RsGxsGrpItem*>::iterator vit = grpData.begin();
for(; vit != grpData.end(); ++vit)
{
RsGxsCircleGroupItem *item = dynamic_cast<RsGxsCircleGroupItem*>(*vit);
if (!item)
{
std::cerr << " Not a RsGxsCircleGroupItem Item, deleting!" << std::endl;
delete(*vit);
continue;
}
RsGxsCircleGroup group;
item->convertTo(group);
#ifdef DEBUG_CIRCLES
std::cerr << " Loaded Id with Meta: " << item->meta << std::endl;
#endif // DEBUG_CIRCLES
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
/* should already have a LoadingCache entry */
RsGxsCircleId id = RsGxsCircleId(item->meta.mGroupId.toStdString());
std::map<RsGxsCircleId, RsGxsCircleCache>::iterator it;
it = mLoadingCache.find(id);
if (it == mLoadingCache.end())
{
std::cerr << "p3GxsCircles::cache_load_for_token() Load ERROR: ";
std::cerr << item->meta;
std::cerr << std::endl;
delete(item);
// ERROR.
continue;
}
RsGxsCircleCache &cache = it->second;
cache.loadBaseCircle(group);
cache.mOriginator = item->meta.mOriginator ;
cache.mAmIAllowed = false;
delete item;
bool isComplete = true;
bool isUnprocessedPeers = false;
if (cache.mIsExternal)
{
#ifdef DEBUG_CIRCLES
std::cerr << " Loading External Circle" << std::endl;
#endif
std::set<RsGxsId> &peers = group.mInvitedMembers;
std::set<RsGxsId>::const_iterator pit;
std::list<RsGxsId> myOwnIds;
if(rsIdentity->getOwnIds(myOwnIds))
{
bool ownIdInCircle = false ;
for(std::list<RsGxsId>::const_iterator it(myOwnIds.begin());it!=myOwnIds.end() && !ownIdInCircle;++it)
ownIdInCircle = ownIdInCircle || (peers.find(*it) != peers.end()) ;
#ifdef DEBUG_CIRCLES
std::cerr << " own ID in circle: " << ownIdInCircle << std::endl;
#endif
cache.mAmIAllowed = ownIdInCircle;
}
else
{
std::cerr << " own ids not loaded yet." << std::endl;
isComplete = false;
isUnprocessedPeers = true;
}
// need to trigger the searches.
for(pit = peers.begin(); pit != peers.end(); ++pit)
{
#ifdef DEBUG_CIRCLES
std::cerr << " Invited Member: " << *pit ;
#endif
/* check cache */
if (mIdentities->haveKey(*pit))
{
/* we can process now! */
RsIdentityDetails details;
if (mIdentities->getIdDetails(*pit, details))
{
if ((details.mFlags & RS_IDENTITY_FLAGS_PGP_LINKED) &&(details.mFlags & RS_IDENTITY_FLAGS_PGP_KNOWN))
{
#ifdef DEBUG_CIRCLES
std::cerr << " Is Known -> AllowedPeer: " << *pit << std::endl;
#endif
cache.addAllowedPeer(details.mPgpId, *pit);
}
else
{
#ifdef DEBUG_CIRCLES
std::cerr << " Is Unknown -> UnknownPeer: " << *pit << std::endl;
#endif
cache.mAllowedAnonPeers.insert(*pit);
}
}
else
{
std::cerr << "p3GxsCircles::cache_load_for_token() ERROR no details: " << *pit;
std::cerr << std::endl;
// ERROR.
}
}
else
{
#ifdef DEBUG_CIRCLES
std::cerr << " Requesting UnprocessedPeer: " << *pit << std::endl;
#endif
std::list<PeerId> peers;
peers.push_back(cache.mOriginator) ;
mIdentities->requestKey(*pit, peers);
/* store in to_process queue. */
cache.mUnprocessedPeers.insert(*pit);
isComplete = false;
isUnprocessedPeers = true;
}
}
#ifdef HANDLE_SUBCIRCLES
#if 0
std::list<RsGxsCircleId> &circles = group.mSubCircles;
std::list<RsGxsCircleId>::const_iterator cit;
for(cit = circles.begin(); cit != circles.end(); ++cit)
{
/* if its cached already -> then its complete. */
if (mCircleCache.is_loaded(*cit))
{
RsGxsCircleCache cachedCircle;
if (mCircleCache.fetch(&cit, cachedCircle))
{
/* copy cached circle into circle */
cache.loadSubCircle(cachedCircle);
}
else
{
/* error */
continue;
}
}
else
{
/* push into secondary processing queues */
std::list<RsGxsCircleId> &proc_circles = mCacheLoad_SubCircle[*cit];
proc_circles.push_back(id);
subCirclesToLoad.push_back(*cit);
isComplete = false;
isUnprocessedCircles = true;
}
}
#endif
#endif
}
else
{
#ifdef DEBUG_CIRCLES
std::cerr << " Loading Personal Circle" << std::endl;
#endif
// LOCAL Load.
std::set<RsPgpId> &peers = group.mLocalFriends;
std::set<RsPgpId>::const_iterator pit;
// need to trigger the searches.
for(pit = peers.begin(); pit != peers.end(); ++pit)
{
#ifdef DEBUG_CIRCLES
std::cerr << " Local Friend: " << *pit << std::endl;
#endif
cache.addLocalFriend(*pit);
}
isComplete = true;
isUnprocessedPeers = false;
}
// we can check for self inclusion in the circle right away, since own ids are always loaded.
// that allows to subscribe/unsubscribe uncomplete circles
checkCircleCacheForAutoSubscribe(cache);
if (isComplete)
{
/* move straight into the cache */
mCircleCache.store(id, cache);
mCircleCache.resize();
/* remove from loading queue */
mLoadingCache.erase(it);
std::cerr << " Loading complete." << std::endl;
}
if (isUnprocessedPeers)
{
std::cerr << " Unprocessed peers. Requesting reload..." << std::endl;
/* schedule event to try reload gxsIds */
RsTickEvent::schedule_in(CIRCLE_EVENT_RELOADIDS, GXSID_LOAD_CYCLE, id.toStdString());
}
}
}
else
{
std::cerr << "p3GxsCircles::cache_load_for_token() ERROR no data";
std::cerr << std::endl;
return false;
}
#ifdef HANDLE_SUBCIRCLES
#if 0
if (!subCirclesToLoad.empty())
{
/* request load of subcircles */
}
#endif
#endif
return true;
}
bool p3GxsCircles::cache_reloadids(const RsGxsCircleId &circleId)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::cache_reloadids()";
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
/* fetch from loadMap */
std::map<RsGxsCircleId, RsGxsCircleCache>::iterator it;
it = mLoadingCache.find(circleId);
if (it == mLoadingCache.end())
{
std::cerr << "p3GxsCircles::cache_reloadids() ERROR Id: " << circleId;
std::cerr << " Not in mLoadingCache Map";
std::cerr << std::endl;
// ERROR
return false;
}
RsGxsCircleCache &cache = it->second;
std::list<RsGxsId> myOwnIds;
if(rsIdentity->getOwnIds(myOwnIds))
{
bool ownIdInCircle = false ;
for(std::list<RsGxsId>::const_iterator it(myOwnIds.begin());it!=myOwnIds.end() && !ownIdInCircle;++it)
ownIdInCircle = ownIdInCircle || cache.isAllowedPeer(*it) ;
cache.mAmIAllowed = ownIdInCircle ;
}
/* try reload Ids */
for(std::set<RsGxsId>::const_iterator pit = cache.mUnprocessedPeers.begin(); pit != cache.mUnprocessedPeers.end(); ++pit)
{
/* check cache */
if (mIdentities->haveKey(*pit))
{
/* we can process now! */
RsIdentityDetails details;
if (mIdentities->getIdDetails(*pit, details))
{
if ((details.mFlags & RS_IDENTITY_FLAGS_PGP_LINKED) &&(details.mFlags & RS_IDENTITY_FLAGS_PGP_KNOWN))
{
cache.addAllowedPeer(details.mPgpId, *pit);
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::cache_reloadids() AllowedPeer: ";
std::cerr << *pit;
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
}
else
{
cache.mAllowedAnonPeers.insert(*pit);
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::cache_reloadids() UnknownPeer: ";
std::cerr << *pit;
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
}
}
else
{
// ERROR.
std::cerr << "p3GxsCircles::cache_reloadids() ERROR ";
std::cerr << " Should haveKey for Id: " << *pit;
std::cerr << std::endl;
}
}
else
{
// UNKNOWN ID.
std::cerr << "p3GxsCircles::cache_reloadids() UNKNOWN Id: ";
std::cerr << *pit;
std::cerr << std::endl;
}
}
// clear unprocessed List.
cache.mUnprocessedPeers.clear();
// If sub-circles are complete too.
#ifdef SUBSCIRCLES
if (cache.mUnprocessedCircles.empty())
{
#endif
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::cache_reloadids() Adding to cache Id: ";
std::cerr << circleId;
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
checkCircleCacheForAutoSubscribe(cache);
// Push to Cache.
mCircleCache.store(circleId, cache);
mCircleCache.resize();
/* remove from loading queue */
mLoadingCache.erase(it);
#ifdef SUBSCIRCLES
}
else
{
std::cerr << "p3GxsCircles::cache_reloadids() WARNING Incomplete Cache Loading: ";
std::cerr << circleId;
std::cerr << std::endl;
}
#endif
return true;
}
/* We need to AutoSubscribe if the Circle is relevent to us */
bool p3GxsCircles::checkCircleCacheForAutoSubscribe(RsGxsCircleCache &cache)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::checkCircleCacheForAutoSubscribe() : "<< cache.mCircleId << std::endl;
#endif
/* if processed already - ignore */
if (!(cache.mGroupStatus & GXS_SERV::GXS_GRP_STATUS_UNPROCESSED))
{
#ifdef DEBUG_CIRCLES
std::cerr << " Already Processed" << std::endl;
#endif
return false;
}
/* if personal - we created ... is subscribed already */
if (!cache.mIsExternal)
{
#ifdef DEBUG_CIRCLES
std::cerr << " Personal Circle. Nothing to do." << std::endl;
#endif
return false;
}
/* if we appear in the group - then autosubscribe, and mark as processed */
const RsPgpId& ownPgpId = mPgpUtils->getPGPOwnId();
bool am_I_allowed = cache.mAmIAllowed || (cache.mAllowedSignedPeers.find(ownPgpId) != cache.mAllowedSignedPeers.end()) ;
if(am_I_allowed)
{
uint32_t token, token2;
if(! (cache.mGroupSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_SUBSCRIBED))
{
#ifdef DEBUG_CIRCLES
/* we are part of this group - subscribe, clear unprocessed flag */
std::cerr << " I'm allowed in this circle => AutoSubscribing!" << std::endl;
#endif
RsGenExchange::subscribeToGroup(token, RsGxsGroupId(cache.mCircleId), true);
}
#ifdef DEBUG_CIRCLES
else
std::cerr << " I'm allowed in this circle, and already subscribed." << std::endl;
#endif
RsGenExchange::setGroupStatusFlags(token2, RsGxsGroupId(cache.mCircleId), 0, GXS_SERV::GXS_GRP_STATUS_UNPROCESSED);
cache.mGroupStatus &= ~GXS_SERV::GXS_GRP_STATUS_UNPROCESSED;
return true;
}
else if (cache.mUnprocessedPeers.empty())
{
/* we know all the peers - we are not part - we can flag as PROCESSED. */
uint32_t token,token2;
RsGenExchange::setGroupStatusFlags(token, RsGxsGroupId(cache.mCircleId.toStdString()), 0, GXS_SERV::GXS_GRP_STATUS_UNPROCESSED);
if(cache.mGroupSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_SUBSCRIBED)
{
RsGenExchange::subscribeToGroup(token2, RsGxsGroupId(cache.mCircleId), false);
#ifdef DEBUG_CIRCLES
std::cerr << " Not part of the group! Let's unsubscribe this circle of unfriendly Napoleons!" << std::endl;
#endif
}
#ifdef DEBUG_CIRCLES
else
std::cerr << " Not part of the group, and not subscribed either." << std::endl;
#endif
cache.mGroupStatus &= ~GXS_SERV::GXS_GRP_STATUS_UNPROCESSED;
return true ;
}
else
{
#ifdef DEBUG_CIRCLES
std::cerr << " Leaving Unprocessed" << std::endl;
#endif
// Don't clear UNPROCESSED - as we might not know all the peers.
// TODO - work out when we flag as PROCESSED.
}
return false;
}
void p3GxsCircles::addCircleIdToList(const RsGxsCircleId &circleId, uint32_t circleType)
{
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
if (circleType == GXS_CIRCLE_TYPE_LOCAL)
{
if(mCirclePersonalIdList.end() == std::find(mCirclePersonalIdList.begin(), mCirclePersonalIdList.end(), circleId)){
mCirclePersonalIdList.push_back(circleId);
}
}
else
{
if(mCircleExternalIdList.end() == std::find(mCircleExternalIdList.begin(), mCircleExternalIdList.end(), circleId)){
mCircleExternalIdList.push_back(circleId);
}
}
}
#ifdef HANDLE_SUBCIRCLES
#if 0
/**** TODO BELOW ****/
bool p3GxsCircles::cache_load_subcircles(uint32_t token)
{
std::cerr << "p3GxsCircles::cache_load_subcircles() : " << token;
std::cerr << std::endl;
std::vector<RsGxsGrpItem*> grpData;
bool ok = RsGenExchange::getGroupData(token, grpData);
if(ok)
{
std::vector<RsGxsGrpItem*>::iterator vit = grpData.begin();
for(; vit != grpData.end(); ++vit)
{
RsGxsIdGroupItem* item = dynamic_cast<RsGxsIdGroupItem*>(*vit);
RsGxsCircleId id = item->meta.mGroupId;
RsGxsCircleGroup group = item->group;
group.mMeta = item->meta;
delete item;
std::cerr << "p3GxsCircles::cache_load_subcircles() Loaded Id with Meta: ";
std::cerr << item->meta;
std::cerr << std::endl;
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
/* stage 2 of loading, load subcircles */
std::map<RsGxsCircleId, std::list<RsGxsCircleId> >::iterator sit;
sit = mCacheLoad_SubCircle.find(id)
if (sit == mCacheLoad_SubCircle.end())
{
/* ERROR */
continue;
}
std::list<RsGxsCircleId> updateCaches = sit->second;
// cleanup while we're here.
mCacheLoad_SubCircle.erase(sit);
/* Now iterate through peers / subcircles, and apply
* - similarly to base load function
*/
RsGxsCircleCache &cache = it->second;
cache.loadBaseCircle(group);
bool isComplete = true;
std::list<RsGxsId> &peers = group.peers;
std::list<RsGxsId>::const_iterator pit;
// need to trigger the searches.
for(pit = peers.begin(); pit != peers.end(); ++pit)
{
/* check cache */
if (mIdentities->is_cached(*pit))
{
/* we can process now! */
RsIdentityDetails details;
if (mIdentities->getDetails(*pit, details))
{
if (details.isPgpKnown)
{
// Problem - could have multiple GxsIds here!
// TODO.
//cache.mAllowedPeers[details.mPgpId] = *pit;
for(uit = updateCaches.begin(); uit != updateCaches.end(); ++uit)
{
/* fetch the cache - and update */
mLoadingCache[id] = RsGxsCircleCache();
std::map<RsGxsCircleId, RsGxsCircleCache>::iterator it;
it = mLoadingCache.find(id);
}
}
else
{
//cache.mUnknownPeers.push_back(*pit);
}
}
else
{
// ERROR.
}
}
else
{
/* store in to_process queue. */
cache.mUnprocessedPeers.push_back(*pit);
if (isComplete)
{
/* store reference to update */
isComplete = false;
mCacheLoad_KeyWait.push_back(id);
}
}
}
std::list<RsGxsCircleId> &circles = group.circles;
std::list<RsGxsCircleId>::const_iterator cit;
for(cit = circles.begin(); cit != circles.end(); ++cit)
{
/* if its cached already -> then its complete. */
if (mCircleCache.is_loaded(*cit))
{
RsGxsCircleCache cachedCircle;
if (mCircleCache.fetch(&cit, cachedCircle))
{
/* copy cached circle into circle */
cache.loadSubCircle(cachedCircle);
}
else
{
/* error */
continue;
}
}
else
{
/* push into secondary processing queues */
std::list<RsGxsCircleId> &proc_circles = mCacheLoad_SubCircle[id];
proc_circles.push_back(id);
subCirclesToLoad.push_back(id);
isComplete = false;
}
}
if (isComplete)
{
/* move straight into the cache */
mCircleCache.store(id, cache);
/* remove from loading queue */
mLoadingCache.erase(it);
}
}
}
else
{
std::cerr << "p3GxsCircles::cache_load_for_token() ERROR no data";
std::cerr << std::endl;
return false;
}
if (!keysToLoad.empty())
{
/* schedule event to try reload gxsIds */
}
if (!subCirclesToLoad.empty())
{
/* request load of subcircles */
}
return true;
}
#endif
#endif
/************************************************************************************/
/************************************************************************************/
/************************************************************************************/
std::string p3GxsCircles::genRandomId()
{
std::string randomId;
for(int i = 0; i < 20; i++)
{
randomId += (char) ('a' + (RSRandom::random_u32() % 26));
}
return randomId;
}
void p3GxsCircles::generateDummyData()
{
// request Id Data...
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::generateDummyData() getting Id List";
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
uint32_t ansType = RS_TOKREQ_ANSTYPE_DATA;
RsTokReqOptions opts;
opts.mReqType = GXS_REQUEST_TYPE_GROUP_DATA;
uint32_t token;
rsIdentity->getTokenService()->requestGroupInfo(token, ansType, opts);
{
RsStackMutex stack(mCircleMtx); /********** STACK LOCKED MTX ******/
mDummyIdToken = token;
}
RsTickEvent::schedule_in(CIRCLE_EVENT_DUMMYLOAD, CIRCLE_DUMMY_GENPERIOD);
}
void p3GxsCircles::checkDummyIdData()
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::checkDummyIdData()";
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
// check the token.
uint32_t status = rsIdentity->getTokenService()->requestStatus(mDummyIdToken);
if ( (RsTokenService::GXS_REQUEST_V2_STATUS_FAILED == status) ||
(RsTokenService::GXS_REQUEST_V2_STATUS_COMPLETE == status) )
{
std::vector<RsGxsIdGroup> ids;
if (!rsIdentity->getGroupData(mDummyIdToken, ids))
{
std::cerr << "p3GxsCircles::checkDummyIdData() ERROR getting data";
std::cerr << std::endl;
/* error */
return;
}
std::vector<RsGxsIdGroup>::iterator it;
for(it = ids.begin(); it != ids.end(); ++it)
{
if (it->mMeta.mGroupFlags & RSGXSID_GROUPFLAG_REALID)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::checkDummyIdData() PgpLinkedId: " << it->mMeta.mGroupId;
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
mDummyPgpLinkedIds.push_back(RsGxsId(it->mMeta.mGroupId.toStdString()));
if (it->mMeta.mSubscribeFlags & GXS_SERV::GROUP_SUBSCRIBE_ADMIN)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::checkDummyIdData() OwnId: " << it->mMeta.mGroupId;
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
mDummyOwnIds.push_back(RsGxsId(it->mMeta.mGroupId.toStdString()));
}
}
else
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::checkDummyIdData() Other Id: " << it->mMeta.mGroupId;
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
}
}
/* schedule the generate events */
#define MAX_CIRCLES 10
for(int i = 0; i < MAX_CIRCLES; i++)
{
RsTickEvent::schedule_in(CIRCLE_EVENT_DUMMYGEN, i * CIRCLE_DUMMY_GENPERIOD);
}
return;
}
// Otherwise - reschedule to come back here.
RsTickEvent::schedule_in(CIRCLE_EVENT_DUMMYLOAD, CIRCLE_DUMMY_GENPERIOD);
return;
}
void p3GxsCircles::generateDummyCircle()
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::generateDummyCircle()";
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
int npgps = mDummyPgpLinkedIds.size();
if(npgps == 0)
return ;
RsGxsCircleGroup group;
std::set<RsGxsId> idset;
// select a random number of them.
#define MAX_PEERS_PER_CIRCLE_GROUP 20
int nIds = 1 + (RSRandom::random_u32() % MAX_PEERS_PER_CIRCLE_GROUP);
for(int i = 0; i < nIds; i++)
{
int selection = (RSRandom::random_u32() % npgps);
std::list<RsGxsId>::iterator it = mDummyPgpLinkedIds.begin();
for(int j = 0; (it != mDummyPgpLinkedIds.end()) && (j < selection); j++, ++it) ;
if (it != mDummyPgpLinkedIds.end())
{
idset.insert(*it);
}
}
/* be sure to add one of our IDs too (otherwise we wouldn't get the group)
*/
{
int selection = (RSRandom::random_u32() % mDummyOwnIds.size());
std::list<RsGxsId>::iterator it = mDummyOwnIds.begin();
mDummyOwnIds.push_back(*it);
for(int j = 0; (it != mDummyOwnIds.end()) && (j < selection); j++, ++it) ;
if (it != mDummyOwnIds.end())
{
idset.insert(*it);
}
}
group.mMeta.mGroupName = genRandomId();
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::generateDummyCircle() Name: " << group.mMeta.mGroupName;
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
std::set<RsGxsId>::iterator it;
for(it = idset.begin(); it != idset.end(); ++it)
{
group.mInvitedMembers.insert(*it);
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::generateDummyCircle() Adding: " << *it;
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
}
uint32_t dummyToken;
createGroup(dummyToken, group);
}
/************************************************************************************/
/************************************************************************************/
/************************************************************************************/
/************************************************************************************/
std::ostream &operator<<(std::ostream &out, const RsGxsCircleGroup &grp)
{
out << "RsGxsCircleGroup: Meta: " << grp.mMeta;
out << "InvitedMembers: ";
out << std::endl;
std::set<RsGxsId>::const_iterator it;
std::set<RsGxsCircleId>::const_iterator sit;
for(it = grp.mInvitedMembers.begin();
it != grp.mInvitedMembers.begin(); ++it)
{
out << "\t" << *it;
out << std::endl;
}
for(sit = grp.mSubCircles.begin();
sit != grp.mSubCircles.begin(); ++sit)
{
out << "\t" << *it;
out << std::endl;
}
return out;
}
std::ostream &operator<<(std::ostream &out, const RsGxsCircleMsg &msg)
{
out << "RsGxsCircleMsg: Meta: " << msg.mMeta;
out << std::endl;
return out;
}
// Overloaded from GxsTokenQueue for Request callbacks.
void p3GxsCircles::handleResponse(uint32_t token, uint32_t req_type)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::handleResponse(" << token << "," << req_type << ")";
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
// stuff.
switch(req_type)
{
case CIRCLEREQ_CIRCLE_LIST:
load_CircleIdList(token);
break;
case CIRCLEREQ_CACHELOAD:
cache_load_for_token(token);
break;
#if 0
case CIRCLEREQ_CACHETEST:
cachetest_handlerequest(token);
break;
#endif
default:
/* error */
std::cerr << "p3GxsCircles::handleResponse() Unknown Request Type: " << req_type;
std::cerr << std::endl;
break;
}
}
// Overloaded from RsTickEvent for Event callbacks.
void p3GxsCircles::handle_event(uint32_t event_type, const std::string &elabel)
{
#ifdef DEBUG_CIRCLES
std::cerr << "p3GxsCircles::handle_event(" << event_type << ")";
std::cerr << std::endl;
#endif // DEBUG_CIRCLES
// stuff.
switch(event_type)
{
case CIRCLE_EVENT_LOADIDS:
request_CircleIdList();
break;
case CIRCLE_EVENT_CACHELOAD:
cache_start_load();
break;
case CIRCLE_EVENT_RELOADIDS:
cache_reloadids(RsGxsCircleId(elabel));
break;
#if 0
case CIRCLE_EVENT_CACHETEST:
cachetest_getlist();
break;
#endif
case CIRCLE_EVENT_DUMMYSTART:
generateDummyData();
break;
case CIRCLE_EVENT_DUMMYLOAD:
checkDummyIdData();
break;
case CIRCLE_EVENT_DUMMYGEN:
generateDummyCircle();
break;
default:
/* error */
std::cerr << "p3GxsCircles::handle_event() Unknown Event Type: " << event_type;
std::cerr << std::endl;
break;
}
}
| zeners/RetroShare | libretroshare/src/services/p3gxscircles.cc | C++ | gpl-2.0 | 51,388 |
<?php
/**
* @file
* Interface CDNBaseInterface.
*/
namespace Drupal\libraries_cdn\Types;
use Drupal\Component\Plugin\PluginInspectionInterface;
/**
* Interface CDNBaseInterface.
*/
interface CDNBaseInterface extends PluginInspectionInterface {
/**
* Check if library is available.
*
* @return bool
* Return TRUE if the library is available, otherwise, FALSE.
*/
public function isAvailable();
/**
* Return all available version(s).
*
* @return array
* Return an array with available versions of the library.
*/
public function getVersions();
/**
* Return all available file(s).
*
* @param array $version
* Filter the returning array with this one.
*
* @return array
* Return an array with available files of the library.
*/
public function getFiles(array $version = array());
/**
* Set the library to work with.
*
* @param string $library
* The library to work with.
*/
public function setLibrary($library);
/**
* Get the library in use.
*
* @return string
* The library name.
*/
public function getLibrary();
/**
* Set a particular URL.
*
* @param string $identifier
* The identifier.
* @param string $url
* The URL.
*/
public function setURL($identifier, $url);
/**
* Get a particular URL.
*
* @return string
* The URL.
*/
public function getURL($identifier);
/**
* Set URLs.
*
* @param array $urls
* An array of URLs for querying the service.
*/
public function setURLs(array $urls = array());
/**
* Get URLs.
*
* @return array
* Return an array of URLs in use for querying the service.
*/
public function getURLs();
/**
* Make an HTTP Request.
*
* TODO: Do not use drupal_http_request.
*
* @param string $url
* The URL.
* @param array $options
* The array of options passed to drupal_http_request.
*/
public function request($url, array $options = array());
/**
* Get library information.
*
* @return array
* Return an array containing information about the library.
*/
public function getInformation();
/**
* Get latest version available of a library.
*
* @return string
* The latest available version of the library.
*/
public function getLatestVersion();
/**
* Perform a search for a library.
*
* @return array
* The resulting array.
*/
public function search($library);
/**
* Check if a file is available locally.
*
* @param string $file
* The file to check.
* @param string $version
* The version to check the file against.
*
* @return bool
* Return TRUE if the file is available, FALSE otherwise.
*/
public function isLocalAvailable($file, $version);
/**
* Get the local file name of a library file.
*
* @param string $file
* The file to check.
* @param string $version
* The version to check the file against.
*
* @return string
* Return the file name.
*/
public function getLocalFileName($file, $version);
/**
* Get the local directory name of a library.
*
* @param string $version
* The version to check the file against.
*
* @return string
* Return the directory name.
*/
public function getLocalDirectoryName($version = NULL);
/**
* Copy a library from the CDN to the local filesystem.
*
* @param array $versions
* The library versions to copy.
*/
public function getLocalCopy(array $versions = array());
}
| newpalmyra/newpalmyra-drupal | sites/all/modules/libraries_cdn/src/Type/CDNBaseInterface.php | PHP | gpl-2.0 | 3,585 |
<?php
/**
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; under version 2
* of the License (non-upgradable).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Copyright (c) 2022 (original work) Open Assessment Technologies SA.
*/
declare(strict_types=1);
namespace oat\tao\helpers\form\Feeder;
use RuntimeException;
use tao_helpers_form_Form;
use tao_helpers_form_Validator;
use tao_helpers_form_FormElement;
interface SanitizerValidationFeederInterface
{
public function addValidator(tao_helpers_form_Validator $validator): self;
public function setForm(tao_helpers_form_Form $form): self;
/**
* @throws RuntimeException
*/
public function addElement(tao_helpers_form_FormElement $element): self;
/**
* @throws RuntimeException
*/
public function addElementByUri(string $elementUri): self;
public function feed(): void;
}
| oat-sa/tao-core | helpers/form/Feeder/SanitizerValidationFeederInterface.php | PHP | gpl-2.0 | 1,434 |
/*
* @brief ajax
*
* @file Group.js
*
* Copyright (C) 2006-2009 Jedox AG
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License (Version 2) as published
* by the Free Software Foundation at http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*
* You may obtain a copy of the License at
*
* <a href="http://www.jedox.com/license_palo_bi_suite.txt">
* http://www.jedox.com/license_palo_bi_suite.txt
* </a>
*
* If you are developing and distributing open source applications under the
* GPL License, then you are free to use Palo under the GPL License. For OEMs,
* ISVs, and VARs who distribute Palo with their products, and do not license
* and distribute their source code under the GPL, Jedox provides a flexible
* OEM Commercial License.
*
* \author
* Drazen Kljajic <drazen.kljajic@develabs.com>
*
* \version
* SVN: $Id: CopyRange.js 4776 2011-03-28 14:25:45Z predragm $
*
*/
Jedox.wss.grid.CopyRange = (function ()
{
// private static fields
// private static methods
// class constructor
return function (selection, startPoint, endPoint)
{
Jedox.wss.grid.CopyRange.parent.constructor.call(this, selection, startPoint, endPoint);
// private fields
// private methods
// public fields
// privileged methods
// constructor code
var that = this,
panesLen = this._panes.length,
htmlEl, htmlElCp;
// Init presentation.
// Add html elements for each line in an range:
for(var clsName = 'formularRangeBorder', i = 3; i >= 0; --i) {
htmlEl = document.createElement('div');
htmlEl.className = clsName;
for (var j = panesLen - 1; j >= 0; j--) {
htmlElCp = j > 0 ? htmlEl.cloneNode(true) : htmlEl;
this._edgeElems[j][i] = htmlElCp;
this._containers[j].appendChild(htmlElCp);
}
}
}
}
)();
// CopyRange extends Range
Jedox.util.extend(Jedox.wss.grid.CopyRange, Jedox.wss.grid.Range);
// public static methods
// public methods
clsRef = Jedox.wss.grid.CopyRange;
clsRef = null; | fschaper/netcell | ui/docroot/ui/wss/base/grid/CopyRange.js | JavaScript | gpl-2.0 | 2,491 |
package com.github.hurdad.storm.forex.bolt;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
public class PercRBolt extends BaseRichBolt {
OutputCollector _collector;
Integer _period;
Map<String, Queue<Double>> _high_queues;
Map<String, Queue<Double>> _low_queues;
public PercRBolt(Integer period) {
_period = period;
}
@Override
public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
_collector = collector;
_high_queues = new HashMap<String, Queue<Double>>();
_low_queues = new HashMap<String, Queue<Double>>();
}
@Override
public void execute(Tuple tuple) {
// input vars
String pair = tuple.getStringByField("pair");
String high = tuple.getStringByField("high");
String low = tuple.getStringByField("low");
String close = tuple.getStringByField("close");
Integer timeslice = tuple.getIntegerByField("timeslice");
// init
if (_high_queues.get(pair) == null)
_high_queues.put(pair, new LinkedList<Double>());
if (_low_queues.get(pair) == null)
_low_queues.put(pair, new LinkedList<Double>());
// pair highs / lows
Queue<Double> highs = _high_queues.get(pair);
Queue<Double> lows = _low_queues.get(pair);
// add to front
highs.add(Double.parseDouble(high));
lows.add(Double.parseDouble(low));
// pop back if too long
if (highs.size() > _period)
highs.poll();
if (lows.size() > _period)
lows.poll();
// have enough data to calc perc r
if (highs.size() == _period) {
// get high
Double h = highs.peek();
// loop highs
for (Double val : highs) {
h = Math.max(val, h);
}
// get low
Double l = lows.peek();
// loop lows
for (Double val : lows) {
l = Math.min(val, l);
}
// calc percent R
Double perc_r = (h - Double.parseDouble(close)) / (h - l) * -100;
// emit
_collector.emit(new Values(pair, timeslice, String.format("%.2f", perc_r)));
}
// save
_high_queues.put(pair, highs);
_low_queues.put(pair, lows);
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("pair", "timeslice", "perc_r"));
}
} | hurdad/storm-forex | src/jvm/com/github/hurdad/storm/forex/bolt/PercRBolt.java | Java | gpl-2.0 | 2,483 |
<?php defined('_JEXEC') or die;
?>
<div class="fwuser_wrap item-page">
<div>
<h2><?php echo JText::_('JOIN AS A MEMBER');?></h2>
</div>
<div>
<p>Thank you for joining as a member. Your details have been successfully submitted and an email confirmation will be sent to you shortly.</p>
</div>
</div> | bundocba/poiserealestate | components/com_fwuser/views/register/tmpl/confirm.php | PHP | gpl-2.0 | 307 |
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* hold PMA\libraries\twig\UtilExtension class
*
* @package PMA\libraries\twig
*/
namespace PMA\libraries\twig;
use Twig_Extension;
use Twig_SimpleFunction;
/**
* Class UtilExtension
*
* @package PMA\libraries\twig
*/
class UtilExtension extends Twig_Extension
{
/**
* Returns a list of functions to add to the existing list.
*
* @return Twig_SimpleFunction[]
*/
public function getFunctions()
{
return array(
new Twig_SimpleFunction(
'Util_escapeMysqlWildcards',
'PMA\libraries\Util::escapeMysqlWildcards'
),
new Twig_SimpleFunction(
'Util_formatSql',
'PMA\libraries\Util::formatSql',
array('is_safe' => array('html'))
),
new Twig_SimpleFunction(
'Util_getDropdown',
'PMA\libraries\Util::getDropdown',
array('is_safe' => array('html'))
),
new Twig_SimpleFunction(
'Util_getHtmlTab',
'PMA\libraries\Util::getHtmlTab',
array('is_safe' => array('html'))
),
new Twig_SimpleFunction(
'Util_getIcon',
'PMA\libraries\Util::getIcon',
array('is_safe' => array('html'))
),
new Twig_SimpleFunction(
'Util_getImage',
'PMA\libraries\Util::getImage',
array('is_safe' => array('html'))
),
new Twig_SimpleFunction(
'Util_getSupportedDatatypes',
'PMA\libraries\Util::getSupportedDatatypes',
array('is_safe' => array('html'))
),
new Twig_SimpleFunction(
'Util_showHint',
'PMA\libraries\Util::showHint',
array('is_safe' => array('html'))
),
new Twig_SimpleFunction(
'Util_showIcons',
'PMA\libraries\Util::showIcons'
),
);
}
}
| udan11/phpmyadmin | libraries/twig/UtilExtension.php | PHP | gpl-2.0 | 2,137 |
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/* @api */
define([
'underscore',
'Magento_Checkout/js/view/payment/default',
'Magento_Payment/js/model/credit-card-validation/credit-card-data',
'Magento_Payment/js/model/credit-card-validation/credit-card-number-validator',
'mage/translate'
], function (_, Component, creditCardData, cardNumberValidator, $t) {
'use strict';
return Component.extend({
defaults: {
creditCardType: '',
creditCardExpYear: '',
creditCardExpMonth: '',
creditCardNumber: '',
creditCardSsStartMonth: '',
creditCardSsStartYear: '',
creditCardSsIssue: '',
creditCardVerificationNumber: '',
selectedCardType: null
},
/** @inheritdoc */
initObservable: function () {
this._super()
.observe([
'creditCardType',
'creditCardExpYear',
'creditCardExpMonth',
'creditCardNumber',
'creditCardVerificationNumber',
'creditCardSsStartMonth',
'creditCardSsStartYear',
'creditCardSsIssue',
'selectedCardType'
]);
return this;
},
/**
* Init component
*/
initialize: function () {
var self = this;
this._super();
//Set credit card number to credit card data object
this.creditCardNumber.subscribe(function (value) {
var result;
self.selectedCardType(null);
if (value === '' || value === null) {
return false;
}
result = cardNumberValidator(value);
if (!result.isPotentiallyValid && !result.isValid) {
return false;
}
if (result.card !== null) {
self.selectedCardType(result.card.type);
creditCardData.creditCard = result.card;
}
if (result.isValid) {
creditCardData.creditCardNumber = value;
self.creditCardType(result.card.type);
}
});
//Set expiration year to credit card data object
this.creditCardExpYear.subscribe(function (value) {
creditCardData.expirationYear = value;
});
//Set expiration month to credit card data object
this.creditCardExpMonth.subscribe(function (value) {
creditCardData.expirationMonth = value;
});
//Set cvv code to credit card data object
this.creditCardVerificationNumber.subscribe(function (value) {
creditCardData.cvvCode = value;
});
},
/**
* Get code
* @returns {String}
*/
getCode: function () {
return 'cc';
},
/**
* Get data
* @returns {Object}
*/
getData: function () {
return {
'method': this.item.method,
'additional_data': {
'cc_cid': this.creditCardVerificationNumber(),
'cc_ss_start_month': this.creditCardSsStartMonth(),
'cc_ss_start_year': this.creditCardSsStartYear(),
'cc_ss_issue': this.creditCardSsIssue(),
'cc_type': this.creditCardType(),
'cc_exp_year': this.creditCardExpYear(),
'cc_exp_month': this.creditCardExpMonth(),
'cc_number': this.creditCardNumber()
}
};
},
/**
* Get list of available credit card types
* @returns {Object}
*/
getCcAvailableTypes: function () {
return window.checkoutConfig.payment.ccform.availableTypes[this.getCode()];
},
/**
* Get payment icons
* @param {String} type
* @returns {Boolean}
*/
getIcons: function (type) {
return window.checkoutConfig.payment.ccform.icons.hasOwnProperty(type) ?
window.checkoutConfig.payment.ccform.icons[type]
: false;
},
/**
* Get list of months
* @returns {Object}
*/
getCcMonths: function () {
return window.checkoutConfig.payment.ccform.months[this.getCode()];
},
/**
* Get list of years
* @returns {Object}
*/
getCcYears: function () {
return window.checkoutConfig.payment.ccform.years[this.getCode()];
},
/**
* Check if current payment has verification
* @returns {Boolean}
*/
hasVerification: function () {
return window.checkoutConfig.payment.ccform.hasVerification[this.getCode()];
},
/**
* @deprecated
* @returns {Boolean}
*/
hasSsCardType: function () {
return window.checkoutConfig.payment.ccform.hasSsCardType[this.getCode()];
},
/**
* Get image url for CVV
* @returns {String}
*/
getCvvImageUrl: function () {
return window.checkoutConfig.payment.ccform.cvvImageUrl[this.getCode()];
},
/**
* Get image for CVV
* @returns {String}
*/
getCvvImageHtml: function () {
return '<img src="' + this.getCvvImageUrl() +
'" alt="' + $t('Card Verification Number Visual Reference') +
'" title="' + $t('Card Verification Number Visual Reference') +
'" />';
},
/**
* @deprecated
* @returns {Object}
*/
getSsStartYears: function () {
return window.checkoutConfig.payment.ccform.ssStartYears[this.getCode()];
},
/**
* Get list of available credit card types values
* @returns {Object}
*/
getCcAvailableTypesValues: function () {
return _.map(this.getCcAvailableTypes(), function (value, key) {
return {
'value': key,
'type': value
};
});
},
/**
* Get list of available month values
* @returns {Object}
*/
getCcMonthsValues: function () {
return _.map(this.getCcMonths(), function (value, key) {
return {
'value': key,
'month': value
};
});
},
/**
* Get list of available year values
* @returns {Object}
*/
getCcYearsValues: function () {
return _.map(this.getCcYears(), function (value, key) {
return {
'value': key,
'year': value
};
});
},
/**
* @deprecated
* @returns {Object}
*/
getSsStartYearsValues: function () {
return _.map(this.getSsStartYears(), function (value, key) {
return {
'value': key,
'year': value
};
});
},
/**
* Is legend available to display
* @returns {Boolean}
*/
isShowLegend: function () {
return false;
},
/**
* Get available credit card type by code
* @param {String} code
* @returns {String}
*/
getCcTypeTitleByCode: function (code) {
var title = '',
keyValue = 'value',
keyType = 'type';
_.each(this.getCcAvailableTypesValues(), function (value) {
if (value[keyValue] === code) {
title = value[keyType];
}
});
return title;
},
/**
* Prepare credit card number to output
* @param {String} number
* @returns {String}
*/
formatDisplayCcNumber: function (number) {
return 'xxxx-' + number.substr(-4);
},
/**
* Get credit card details
* @returns {Array}
*/
getInfo: function () {
return [
{
'name': 'Credit Card Type', value: this.getCcTypeTitleByCode(this.creditCardType())
},
{
'name': 'Credit Card Number', value: this.formatDisplayCcNumber(this.creditCardNumber())
}
];
}
});
});
| kunj1988/Magento2 | app/code/Magento/Payment/view/frontend/web/js/view/payment/cc-form.js | JavaScript | gpl-2.0 | 8,982 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "Linked_List.h"
#include "List.h"
#include "Lhash.h"
#include "crs.h"
#include "winslow.h"
#include "linear_elastic.h"
#include "trimesh.h"
#include "Point.h"
#include "Vector.h"
#include "make_nbrs_HO.h"
#include "subdivision.h"
#include "refine_tri.h"
#include "opt_smooth.h"
#define MIN(x,y) ((x) <= (y) ? (x) : (y))
#define MAX(x,y) ((x) >= (y) ? (x) : (y))
#define ABS(x) ((x) >= 0 ? (x) : -(x))
#define SIGN(a,b) ((b) < 0.0 ? -ABS(a) : ABS(a))
#define freenull(a) {if(a) free(a); a=NULL;}
//Generally, run to cvg of 1.0e-6
int main(int argcs, char* pArgs[])
{
int nn = 0, nblk = 0, nt = 0, nq = 0, nb = 0, nv = 0, nc = 0; //number of nodes, number of blocks, number of triangles, number of quads, number of boundaries, num vars, num const
int nnp, nblkp, ntp, nqp, nbp; //p signifies physical mesh version to be checked against above
//placeholders to read physical mesh info into to check against computational (saves storing in more matrices and wasting memory)
//also, flag for derefining (set to zero for freeing mem) and for remeshing (set to zero for freeing mem) and for reallocing tri within trimesh loop
int trip0, trip1, trip2, quadp0, quadp1, quadp2, quadp3, bsp0, bsp1, nbsp, flagC = 0, remesh = 0, tdim;
int i, j, k, n, m, l, s; //counters
int old_nn; //old number of nodes, needed for freeing memory if operation == 1
const int bdim = 132; //buffer size
char buff[bdim]; //buffer
FILE *fp = NULL; //file pointer to be used for both files
//declare matrices for x,y coords of computational/physical nodes (indexed), triangle conn, quad conn
double **nodec = NULL, **nodep = NULL;
int **tri = NULL, **quad = NULL;
//boundary segments, indexed as boundary number, edge number, node number on edge; number boundary segments per edge
int ***bs = NULL, *nbs = NULL;
//array for each node's values of variables, array for any constants
double **q = NULL, *constants = NULL; //NOTE: These are read from physical mesh ONLY
printf("\n====================================================");
printf("\n Driver for 2-D Winslow/Linear-Elastic Smoother ");
printf("\n====================================================\n");
//be sure both physical and computational are supplied, since connectivity must be identical, while node placement needn't be
if (--argcs < 2)
{
printf("\nYou must specify both a computational mesh and physical mesh file, in that order!");
fflush(stdout);
exit(0);
}
//check to be sure computational mesh file can be opened
if ((fp=fopen(pArgs[argcs],"r")) == 0)
{
printf("\nCouldn't open computational mesh file <%s>\n",pArgs[argcs]);
fflush(stdout);
exit(0);
}
// read number of nodes
fgets(buff,bdim,fp); //skip commment
fgets(buff,bdim,fp); //read nn
sscanf(buff,"%d",&nn);
printf("\nNumber of nodes = %d",nn);
fflush(stdout); //be sure prints to screen
// allocate for computational nodes, using calloc, due to possible realloc
nodec = (double**)calloc(nn,sizeof(double*));
for (i = 0; i < nn; i++)
nodec[i] = (double*)calloc(2,sizeof(double));
// read in coordinates
for (i = 0; i < nn; i++)
{
fgets(buff,bdim,fp); //read node coords to be placed in row of node number (c-indexed)
sscanf(buff,"%lf %lf",&(nodec[i][0]),&(nodec[i][1]));
}
// read number of blocks
fgets(buff,bdim,fp); //skip commment
fgets(buff,bdim,fp); //read nblk
sscanf(buff,"%d",&nblk);
printf("\nNumber of blocks = %d",nblk);
fflush(stdout); //be sure prints to screen
// read number of triangles
fgets(buff,bdim,fp); //skip commment
fgets(buff,bdim,fp); //read nt
sscanf(buff,"%d",&nt);
printf("\nNumber of triangles = %d",nt);
fflush(stdout); //be sure prints to screen
// allocate for triangle connectivity, using calloc, due to possible realloc
tri = (int**)calloc(nt,sizeof(int*));
for (i = 0; i < nt; i++)
tri[i] = (int*)calloc(3,sizeof(int));
// read in triangle connectivity
for (i = 0; i < nt; i++)
{
fgets(buff,bdim,fp); //read ccw nodes for each triangle
sscanf(buff,"%d %d %d",&(tri[i][0]),&(tri[i][1]),&(tri[i][2]));
}
// decrement tri by 1 to make fortran-indexed into c-indexed
for (i = 0; i < nt; i++)
for (j = 0; j < 3; j++)
tri[i][j]--;
// read number of quads
fgets(buff,bdim,fp); //skip commment
fgets(buff,bdim,fp); //read nq
sscanf(buff,"%d",&nq);
printf("\nNumber of quads = %d",nq);
fflush(stdout); //be sure prints to screen
if (nq > 0)
{
// allocate for quad connectivity, using calloc, due to possible realloc
quad = (int**)calloc(nq,sizeof(int*));
for (i = 0; i < nq; i++)
quad[i] = (int*)calloc(4,sizeof(int));
// read in quad connectivity
for (i = 0; i < nq; i++)
{
fgets(buff,bdim,fp); //read ccw nodes for each quad
sscanf(buff,"%d %d %d %d", &(quad[i][0]), &(quad[i][1]), &(quad[i][2]), &(quad[i][3]));
}
// decrement quad by 1 to make fortran-indexed into c-indexed
for (i = 0; i < nq; i++)
for (j = 0; j < 4; j++)
quad[i][j]--;
}
// read number of boundaries
fgets(buff,bdim,fp); //skip commment
fgets(buff,bdim,fp); //read nb
sscanf(buff,"%d",&nb);
printf("\nNumber of boundaries = %d",nb);
fflush(stdout); //be sure prints to screen
// allocate for boundary segment list (first index only...boundary number) and number of segments per boundary, using calloc, due to possible realloc
// 3-D array so contiguous not needed
bs = (int***)calloc(nb,sizeof(int**));
nbs = (int*)calloc(nb,sizeof(int));
// read number of edges per boundary as well as corresponding node numbers in a loop
for (i = 0; i < nb; i ++)
{
//read in number of edges
fgets(buff,bdim,fp); //skip commment
fgets(buff,bdim,fp); //read nbs[i] (i is boundary number)
sscanf(buff,"%d",&(nbs[i]));
printf("\nNumber of edges on boundary %d = %d",i,nbs[i]);
fflush(stdout); //be sure prints to screen
//now, allocate this many edges in the area of bs corresponding to boundary i
bs[i] = (int**)calloc(nbs[i],sizeof(int*));
//now, allocate two spots per edge (for node numbers) in final dimension of bs
for (j = 0; j < nbs[i]; j++)
bs[i][j] = (int*)calloc(2,sizeof(int));
//now, read in node numbers
for (j = 0; j < nbs[i]; j++)
{
fgets(buff,bdim,fp); //read nodes of each edge
sscanf(buff,"%d %d", &(bs[i][j][0]), &(bs[i][j][1]));
}
// now, decrement edges by 1 to make fortran-indexed into c-indexed
for (j = 0; j < nbs[i]; j++)
for (k = 0; k < 2; k++)
bs[i][j][k]--;
}
//we do not need further data from file, so we close and prepare to read physical mesh and compare its connectivity to computational mesh
fclose(fp);
//check to be sure physical mesh file can be opened
if ((fp=fopen(pArgs[--argcs],"r")) == 0)
{
printf("\nCouldn't open physical mesh file <%s>\n",pArgs[argcs]);
exit(0);
}
// read number of nodes
fgets(buff,bdim,fp); //skip commment
fgets(buff,bdim,fp); //read nnp
sscanf(buff,"%d",&nnp);
printf("\nNumber of physical mesh nodes = %d",nnp);
fflush(stdout); //be sure prints to screen
//check for agreement between physical and computational meshes
if (nnp != nn)
{
printf("\nYour physical and computational mesh number of nodes do not agree!");
fflush(stdout);
exit(0);
}
// allocate for physical nodes, using calloc, due to possible realloc
nodep = (double**)calloc(nnp,sizeof(double*));
for (i = 0; i < nnp; i++)
nodep[i] = (double*)calloc(2,sizeof(double));
// read in coordinates
for (i = 0; i < nnp; i++)
{
fgets(buff,bdim,fp); //read node coords to be placed in row of node number (c-indexed)
sscanf(buff,"%lf %lf",&(nodep[i][0]),&(nodep[i][1]));
}
// read number of blocks
fgets(buff,bdim,fp); //skip commment
fgets(buff,bdim,fp); //read nblkp
sscanf(buff,"%d",&nblkp);
printf("\nNumber of physical mesh blocks = %d",nblkp);
fflush(stdout); //be sure prints to screen
//check for agreement between physical and computational meshes
if (nblkp != nblk)
{
printf("\nYour physical and computational mesh number of blocks do not agree!");
fflush(stdout);
exit(0);
}
// read number of triangles
fgets(buff,bdim,fp); //skip commment
fgets(buff,bdim,fp); //read ntp
sscanf(buff,"%d",&ntp);
printf("\nNumber of physical mesh triangles = %d",ntp);
fflush(stdout); //be sure prints to screen
//check for agreement between physical and computational meshes
if (ntp != nt)
{
printf("\nYour physical and computational mesh number of triangles do not agree!");
fflush(stdout);
exit(0);
}
// read in triangle connectivity
for (i = 0; i < ntp; i++)
{
fgets(buff,bdim,fp); //read ccw nodes for each triangle
sscanf(buff,"%d %d %d",&trip0,&trip1,&trip2);
//decrement trip0, trip1, trip2 for comparison in if statement
if (trip0 - 1 != tri[i][0] || trip1 - 1 != tri[i][1] || trip2 - 1 != tri[i][2])
{
printf("\nYour physical and computational mesh triangle connectivities do not agree!");
fflush(stdout);
exit(0);
}
}
// read number of quads
fgets(buff,bdim,fp); //skip commment
fgets(buff,bdim,fp); //read nqp
sscanf(buff,"%d",&nqp);
printf("\nNumber of physical mesh quads = %d",nqp);
fflush(stdout); //be sure prints to screen
//check for agreement between physical and computational meshes
if (nqp != nq)
{
printf("\nYour physical and computational mesh number of quads do not agree!");
fflush(stdout);
exit(0);
}
if (nqp > 0)
{
// read in quad connectivity
for (i = 0; i < nqp; i++)
{
fgets(buff,bdim,fp); //read ccw nodes for each quad, decrement by 1 to make fortran-indexed, c-indexed
sscanf(buff,"%d %d %d %d",&quadp0,&quadp1,&quadp2,&quadp3);
//decrement quadp0, quadp1, quadp2, quadp3 for comparison in if statement
if (quadp0 - 1 != quad[i][0] || quadp1 - 1 != quad[i][1] || quadp2 - 1 != quad[i][2] || quadp3 - 1 != quad[i][3])
{
printf("\nYour physical and computational mesh quad connectivities do not agree!");
fflush(stdout);
exit(0);
}
}
}
// read number of boundaries
fgets(buff,bdim,fp); //skip commment
fgets(buff,bdim,fp); //read nbp
sscanf(buff,"%d",&nbp);
printf("\nNumber of physical mesh boundaries = %d",nbp);
fflush(stdout); //be sure prints to screen
//check for agreement between physical and computational meshes
if (nbp != nb)
{
printf("\nYour physical and computational mesh number of boundaries do not agree!");
fflush(stdout);
exit(0);
}
// read number of edges per boundary as well as corresponding node numbers in a loop
for (i = 0; i < nbp; i ++)
{
//read in number of edges
fgets(buff,bdim,fp); //skip commment
fgets(buff,bdim,fp); //read nbsp
sscanf(buff,"%d", );
printf("\nNumber of edges on boundary %d in physical mesh = %d",i,nbsp);
fflush(stdout); //be sure prints to screen
//check for agreement between physical and computational meshes
if (nbsp != nbs[i])
{
printf("\nYour physical and computational mesh number of edges per boundary do not agree!");
fflush(stdout);
exit(0);
}
//now, read in node numbers, again switching form fortran to c indexing
for (j = 0; j < nbsp; j++)
{
fgets(buff,bdim,fp); //read nodes of each edge
sscanf(buff,"%d %d", &bsp0, &bsp1);
//decrement bs0, bs1 for comparison in if statement
if (bsp0 - 1 != bs[i][j][0] || bsp1 - 1 != bs[i][j][1])
{
printf("\nYour physical and computational mesh boundary edge indices do not agree!");
fflush(stdout);
exit(0);
}
}
}
//NOTE: If using old mesh files without variable info, comment out!
// read number of constants
fgets(buff,bdim,fp); //skip commment
fgets(buff,bdim,fp); //read nc
sscanf(buff,"%d",&nc);
printf("\nNumber of constants = %d",nc);
fflush(stdout); //be sure prints to screen
if (nc > 0)
{
// allocate for constants
constants = (double*)calloc(nc,sizeof(double)); //allocate
// read in constants (we will need to know what each is in order, a priori)
for (i = 0; i < nc; i++)
{
fgets(buff,bdim,fp); //read constant
sscanf(buff,"%lf", &(constants[i]));
}
}
// read number of vars (usually four, but we could code for more if needed)
fgets(buff,bdim,fp); //skip commment
fgets(buff,bdim,fp); //read nv
sscanf(buff,"%d",&nv);
printf("\nNumber of variables per node = %d",nv);
fflush(stdout); //be sure prints to screen
for (i = 0; i < nv; i++)
fgets(buff,bdim,fp); //skip nv commments on what they are named
if (nv > 0 && nv < 5)
{
// allocate for each nodes q values
q = (double**)calloc(nn,sizeof(double*));
for (i = 0; i < nn; i++)
q[i] = (double*)calloc(nv,sizeof(double));
// read in q at each node
for (i = 0; i < nn; i++)
{
fgets(buff,bdim,fp); //read q in order
sscanf(buff,"%lf %lf %lf %lf", &(q[i][0]), &(q[i][1]), &(q[i][2]), &(q[i][3]));
}
}
if (nv > 4)
{
printf("\nThis code is 2-D and thus only set up for density, x-momentum, y-momentum, energy. Exiting....\n");
fflush(stdout);
exit(0);
}
//we do not need further data from file, so we close
fclose(fp);
//now, read in desired output file name
char filename[bdim]; //to hold user input
printf("\nEnter desired name of physical mesh, gnuplot file, without file extension ->");
fgets(buff,bdim,stdin); //read in filename
sscanf(buff,"%s",&filename); //place in variable
int n0, n1, n2; //node indices to keep things clean and save memory access
//read in operation to be done, smoothing/movement or subdivision refinement
int operation = 0; //init to smoothing/mesh movement
printf("\nEnter operation to be done: 0 for smoothing/mesh movement OR 1 for subdivision refinement ->");
fgets(buff,bdim,stdin); //read in operation
sscanf(buff,"%d",&operation); //place in variable
//error checking
if (operation < 0 || operation > 1)
{
printf("\nOperation must be 0 for smoothing/mesh movement or 1 for subdivision refinement. Exiting....");
fflush(stdout);
exit(0);
}
//print out op to be done
if (operation == 0)
{
printf("\nPerforming smoothing/mesh movement. Continuing....");
fflush(stdout);
}
if (operation == 1)
{
printf("\nPerforming subdivision refinement. Continuing....");
fflush(stdout);
}
if (operation == 0)
{
//prepare to read in information about omega, inner iter, outer iter, and convergence level
int iterin = 0, iterout = 0; //number of iterations to perform on solve before recomputing alpha, gamma, beta, gradients/ cutoff iterations to perform if cvg not reached sooner
double omega, cvg; //relaxation factor/ desired level of convergence
int smooth_type; //0 for winslow, 1 for L-E, 2 for optimization based
double poisson = 0.0; //poisson's ratio, init to zero since will only be set if smooth_type = 1
double time, time_slice, alphamax; //read in values used to compute delta t and angle airfoil to be moved through
int bd1, bd2; //holds airfoil boundry numbers (to be moved), C++ indexed
double A, B, C; //forcing function coefficients
int whichff; //decide which forcing function to use
//read in type of smoothing to be done, if L-E, read in poisson's ratio
printf("\nEnter desired type of smoothing: 0 for Winslow, 1 for Linear-Elastic, 2 for optimization-based ->");
fgets(buff,bdim,stdin); //read in smooth_type
sscanf(buff,"%d",&smooth_type); //place in variable
//error checking
if (smooth_type == 0)
{
printf("\nWill perform Winslow Smoothing. Continuing....");
//also, read in inner and outer iterative loop limits here, since L-E only has inner loop
printf("\nEnter number of iterations for inner point-iterative GS-SSOR loop ->");
fgets(buff,bdim,stdin); //read in iterin
sscanf(buff,"%d",&iterin); //place in variable
//error checking
if (iterin <= 0)
{
printf("\nCondition to satisfy: iterin > 0. Exiting....");
fflush(stdout);
exit(0);
}
printf("\nEnter number of iterations for outer point-iterative GS-SSOR loop ->");
fgets(buff,bdim,stdin); //read in iterout
sscanf(buff,"%d",&iterout); //place in variable
//error checking
if (iterout <= 0)
{
printf("\nCondition to satisfy: iterout > 0. Exiting....");
fflush(stdout);
exit(0);
}
//get forcing function constants
printf("\nEnter first degree constant for forcing functions (A) ->");
fgets(buff,bdim,stdin); //read in A
sscanf(buff,"%lf",&A); //place in variable
printf("\nEnter second degree constant for forcing functions (B) ->");
fgets(buff,bdim,stdin); //read in B
sscanf(buff,"%lf",&B); //place in variable
printf("\nEnter general constant for forcing functions (C) (for none, use 0.0) ->");
fgets(buff,bdim,stdin); //read in C
sscanf(buff,"%lf",&C); //place in variable
//get type of forcing function
printf("\nEnter 0 to use pressure, 1 for velocity magnitude, or 2 for mach number ->");
fgets(buff,bdim,stdin); //read in whichff
sscanf(buff,"%d",&whichff); //place in variable
//error checking
if (whichff < 0 || whichff > 2)
{
printf("\nYou must enter 0 to use pressure, 1 for velocity magnitude, or 2 for mach number. Exiting....");
fflush(stdout);
exit(0);
}
}
else if (smooth_type == 1)
{
printf("\nWill perform Linear-Elastic Smoothing. Continuing....");
printf("\nEnter Poisson's Ratio (0.0 < nu < 0.5) ->");
fgets(buff,bdim,stdin); //read in poisson
sscanf(buff,"%lf",&poisson); //place in variable
//error checking
if (poisson <= 0.0 || poisson >= 0.5)
{
printf("\nPoisson's ratio MUST be between 0.0 and 0.5! Exiting....");
fflush(stdout);
exit(0);
}
//read in iterative slove loop limit here (only "inner" loop for L-E)
printf("\nEnter number of iterations for point-iterative GS-SSOR loop ->");
fgets(buff,bdim,stdin); //read in iterin
sscanf(buff,"%d",&iterin); //place in variable
//error checking
if (iterin <= 0)
{
printf("\nCondition to satisfy: iterin > 0. Exiting....");
fflush(stdout);
exit(0);
}
}
else if (smooth_type == 2)
{
printf("\nWill perform Optimization-Based Smoothing. Continuing....");
//read in convergence limit here
printf("\nEnter number of iterations to be performed ->");
fgets(buff,bdim,stdin); //read in iterin
sscanf(buff,"%d",&iterin); //place in variable
//error checking
if (iterin <= 0)
{
printf("\nCondition to satisfy: iterations > 0. Exiting....");
fflush(stdout);
exit(0);
}
}
else
{
printf("\nYou must choose 0 for Winslow, 1 for Linear-Elastic, or 2 for Optimization-Based! Exiting....");
fflush(stdout);
exit(0);
}
//read in info to do moving airfoil
//read in amount of time to move airfoil
printf("\nEnter amount of time to move the airfoil (seconds) ->");
fgets(buff,bdim,stdin); //read in time
sscanf(buff,"%lf",&time); //place in variable
//error checking
if (time <= 0.0)
{
printf("\nPlease use a positive time in seconds greater than 0! Exiting....");
fflush(stdout);
exit(0);
}
//read in number of time slices
printf("\nEnter number of time slices at which to perform smoothing ->");
fgets(buff,bdim,stdin); //read in time_slice
sscanf(buff,"%lf",&time_slice); //place in variable
//error checking
if (time_slice <= 0.0)
{
printf("\nPlease use a positive time slice greater than 0! Exiting....");
fflush(stdout);
exit(0);
}
//read in degrees to be moved through over two cycles from 0 to alphamax
printf("\nEnter degrees to rotate airfoil (per cycle for two cycles) over specified time period ->");
fgets(buff,bdim,stdin); //read in alphamax
sscanf(buff,"%lf",&alphamax); //place in variable
//error checking
//if (alphamax < 0.0 || alphamax >= 360.0)
//{
//printf("\nPlease use a positive angle, between 0 (inclusive) and 360 degrees! Exiting....");
//fflush(stdout);
//exit(0);
//}
//read in two boundaries we wish to move
printf("\nEnter two boundaries that will be moved, C++ indexed, with a space in between ->");
fgets(buff,bdim,stdin); //read in bd1, bd2
sscanf(buff,"%d %d",&bd1,&bd2); //place in variables
//error checking
if (bd1 >= nb)
{
printf("\nBoundary %d does not exist, since nb = %d. Check your indexing! Exiting....",bd1,nb);
fflush(stdout);
exit(0);
}
if (bd2 >= nb)
{
printf("\nBoundary %d does not exist, since nb = %d. Check your indexing! Exiting....",bd2,nb);
fflush(stdout);
exit(0);
}
//only need this info if doing winslow or L-E
if (smooth_type == 0 || smooth_type == 1)
{
//read in omega
printf("\nEnter relaxation factor (omega) ->");
fgets(buff,bdim,stdin); //read in omega
sscanf(buff,"%lf",&omega); //place in variable
//error checking
if (omega <= 0.0 || omega > 1.0)
{
printf("\nCondition to satisfy: 0.0 < omega <= 1.0. Exiting....");
fflush(stdout);
exit(0);
}
}
//read in cvg value (even though doubtful to reach with Opt Based)
printf("\nEnter desired convergence level ->");
fgets(buff,bdim,stdin); //read in cvg
sscanf(buff,"%lf",&cvg); //place in variable
//error checking
if (cvg <= 1.0e-15 || cvg >= 1.0)
{
printf("\nCondition to satisfy: 1.0e-15 < cvg < 1.0. Exiting....");
fflush(stdout);
exit(0);
}
//allocate for Lhash to be passed into routine and filled in
List **hash;
hash = new List*[nn]; //each node has a list of nodes it's attached to
for (i=0; i < nn; i++)
hash[i] = new List(); //make each node's list
//now, create hash table to be passed to compressed row storage routine
Lhash(nn, nt, tri, hash);
//now, we build a node 2 cell connectivity
List **NChash;
//first, initialize node to element hash table
NChash = new List*[nn];
for (i = 0; i < nn; i++)
NChash[i] = new List();
//now, create node to element hash
for (i = 0; i < nt; i++)
for (j = 0; j < 3; j++)
NChash[tri[i][j]]->Check_List(i);
/*char *tester = "nodecellhash.dat";
printf("\nOutput Hash File Filename = <%s>\n",tester);
// Open file for write
if ((fp = fopen(tester,"w")) == 0)
{
printf("\nError opening file <%s>.",tester);
exit(0);
}
for (i=0; i < nn; i++)
{
for (j = 0; j < NChash[i]->max; j++)
{
fprintf(fp,"%d ",NChash[i]->list[j]);
}
fprintf(fp,"\n");
}
fclose(fp);*/
//only do this for winslow, L-E, but declare vars external
int mdim; //number of entries in hash table
int *ia, *ja, *iau; //compressed row storage matrices
double ***mat; //holds 2x2 weight matrices for each node
if (smooth_type == 0 || smooth_type == 1)
{
//now, determine sizes of matrices to be passed into compressed row storage empty and passed out full
mdim = 0;
for (i = 0; i < nn; i++)
{
mdim+=hash[i]->max;
}
//printf("\nmdim = %d",mdim);
//now, allocate for all compressed row storage matrices
ia = (int*)calloc(nn+1,sizeof(int)); //ia will hold index (in ja) of starting point for each node (row) in smoothing matrix (mat)
ja = (int*)calloc(mdim,sizeof(int)); //ja holds entries of hash table in row major order
iau = (int*)calloc(nn,sizeof(int)); //iau holds index (in ja) of the diagonal elements in smoothing matrix (mat)
//now, create compressed row storage version of matrix to be used to do smoothing
crs(nn, mdim, ia, ja, iau, hash);
//after creating compressed row storage, hash is no longer needed and can be deleted to save memory
for (i=0; i < nn; i++)
delete hash[i];
delete[] hash;
//now, allocate for mat (holds 2x2 weight matrices for each node)
mat = (double***)calloc(mdim,sizeof(double**));
for (i = 0; i < mdim; i++)
{
mat[i] = (double**)calloc(2,sizeof(double*));
for (j = 0; j < 2; j++)
{
mat[i][j] = (double*)calloc(2,sizeof(double));
}
}
} //end only winslow, l-e
//now, we need to tag boundary nodes so we don't do linear solve on them (in L-E we also use to create delu and delv)
int *tag;
//create a tag array, interior = 1, boundary = 0
tag = (int*)calloc(nn,sizeof(int));
//initialize to one, and go back and make boundary nodes 0
for (i = 0; i < nn; i++)
tag[i] = 1;
//now, loop through boundary nodes and tag them 0
for (i = 0; i < nb; i++)
for (j = 0; j < nbs[i]; j++)
for (k = 0; k < 2; k++)
tag[bs[i][j][k]] = 0; //retag dups since still just a memory access and not doing so disallows cache coherence
//we need to make gnuplot of original first
//concatenate
strcat(filename,"_00.dat");
printf("\nOutput Plot File Filename = <%s>\n",filename);
// Open file for write
if ((fp = fopen(filename,"w")) == 0)
{
printf("\nError opening file <%s>.",filename);
exit(0);
}
for (i=0; i < nt; i++)
{
n0 = tri[i][0];
n1 = tri[i][1];
n2 = tri[i][2];
fprintf(fp,"%19.10e %19.10e 0.0\n", nodep[n0][0],nodep[n0][1]);
fprintf(fp,"%19.10e %19.10e 0.0\n", nodep[n1][0],nodep[n1][1]);
fprintf(fp,"%19.10e %19.10e 0.0\n", nodep[n2][0],nodep[n2][1]);
fprintf(fp,"%19.10e %19.10e 0.0\n\n",nodep[n0][0],nodep[n0][1]);
}
fclose(fp);
//also, let's make a temp array of nodep, so we can find RMS error between orig physical and final physical (ostensibly in same location)
//notice that winslow should recover while L-E will not recover exactly
double **tnode;
tnode = (double**)calloc(nn,sizeof(double*));
for (i = 0; i < nn; i++)
tnode[i] = (double*)calloc(2,sizeof(double));
//init to orig nodep
for (i = 0; i < nn; i++)
{
tnode[i][0] = nodep[i][0];
tnode[i][1] = nodep[i][1];
}
//now, we prepare to rotate our airfoil with linear elastic or winslow smoothing
//notice how we will use smooth_type to determine when and where we use physical coords or computational coords
//compute delt
double delt = time/time_slice;
//set omega2 (rad/s)
double omega2 = 2.0*M_PI;
//convert degrees to radians
alphamax = (alphamax*M_PI)/180.0;
//determine cg (could have user input, sine 1/4 cord length for symmetric airfoil, but this is nice too)
//however, we only want to do this at the outset, since we want our cg to be the axis of rotation!
//create points to hold high and low extents of domains
//set hi and low oppositely large to assure proper action of MAX and MIN
Point lo = Point(1.0e20,1.0e20);
Point hi = Point(-1.0e20,-1.0e20);
int bd; //this is the generic boundary for our switch
//determine hi and lo points of bd1 and bd2
for (i = 0; i < 2; i++)
{
switch (i)
{
case 0:
bd=bd1;
break;
case 1:
bd=bd2;
break;
default:
printf("\nYour index is being clobbered in the switch checking boundry extents in driver.cpp!\n");
exit(0);
break;
}
//check extents, first for x, then for y
for (j = 0; j < nbs[bd]; j++)
{
// check both ends of each segment
for (k = 0; k < 2; k++)
{
//for winslow, we use computational domain boundaries
if (smooth_type == 0)
{
lo[0] = MIN(lo[0],nodec[bs[bd][j][k]][0]);
hi[0] = MAX(hi[0],nodec[bs[bd][j][k]][0]);
lo[1] = MIN(lo[1],nodec[bs[bd][j][k]][1]);
hi[1] = MAX(hi[1],nodec[bs[bd][j][k]][1]);
}
//for L-E and opt-based, we use physical domain boundaries
if (smooth_type == 1 || smooth_type == 2)
{
lo[0] = MIN(lo[0],nodep[bs[bd][j][k]][0]);
hi[0] = MAX(hi[0],nodep[bs[bd][j][k]][0]);
lo[1] = MIN(lo[1],nodep[bs[bd][j][k]][1]);
hi[1] = MAX(hi[1],nodep[bs[bd][j][k]][1]);
}
}
}
}
//now, take the average of high and low y-coords and one-quarter of the length between x-coords and add to the low x-coord
//init the center of gravity
Point cg = Point (0.0,0.0);
//find abs of distance between two x-vals, since they could be negative
cg[0] = 0.25*(fabs(hi[0] - lo[0])) + lo[0];
//check for precision here, since usually zero
if (fabs((hi[1] + lo[1])/2.0) <= 1.0e-5)
cg[1] = 0.0;
else
cg[1] = (hi[1] + lo[1])/2.0;
//debug...print cg
printf("\nCG = ( %lf , %lf )\n",cg[0],cg[1]);
//again, we only want to tag bd points once, since they will remain the same node numbers throughout the oscillations
//create special tag array to tag points on the boundaries to be moved
int *tag2;
tag2 = (int*)calloc(nn,sizeof(int));
//FOR L-E: now, determine the new boundary which will be put in place of the computational nodes, which are identical to the physical nodes elsewhere and are just placeholders so we can find the deltas
//FOR Winslow: now, determine the new boundary which will be put in place of the computational nodes AND physical nodes
//again switch between boundaries to tag all points that are on the boundary specially, so we only change them ONCE
for (i = 0; i < 2; i++)
{
switch (i)
{
case 0:
bd=bd1;
break;
case 1:
bd=bd2;
break;
default:
printf("\nYour index is being clobbered in the switch checking boundry extents in driver.cpp!\n");
exit(0);
break;
}
//loop through each boundary's nodes
for (j = 0; j < nbs[bd]; j++)
{
// tag point at both ends of each segment, even though there is some redundancy
for (k = 0; k < 2; k++)
{
tag2[bs[bd][j][0]] = 1;
tag2[bs[bd][j][1]] = 1;
}
}
}
//now, we want to perform this smoothing time_slices number of times, so we set up a do loop
double current_time = 0.0; //set initial current_time to 0
int iter_file = 0; //to concatenate with file names to separate them
int dig; //to decide how many spaces to delete before adding new iteration tag
char extension[bdim]; //to add iteration number to string
do
{
current_time += delt; //up current time to keep up with oscillations for do loop and for delalpha formula
iter_file++; //increment to get new filename
double delalpha; //this will be the change in alpha from iteration to iteration
//notice, when computing delalpha, by convention current_time is t+delt, so to get t we use current_time - delt
//also, to get movement in one shot, we need to ignore periodicity
if (time_slice == 1)
delalpha = alphamax;
else
delalpha = alphamax*(sin(omega2*(current_time)) - sin(omega2*(current_time - delt)));
//now, go through tagged nodes and change the nodec/nodep to perturbed boundary
Vector r; //will hold Vector from cg to old nodec
double theta; //will hold angle from midline of airfoil to old nodec with vertex at cg
double rmag; //will hold magnitude of r
for (i = 0; i < nn; i++)
{
if (tag2[i] == 0)
continue; //non boundary node
//we move nodep for winslow smoothing OR optimization based
if (smooth_type == 0 || smooth_type == 2)
{
r = Vector(nodep[i][0] - cg[0], nodep[i][1] - cg[1]); //find r to be used in theta and node changing
theta = atan2(r[1],r[0]); //find angle using atan2 to get right quadrant angle
rmag = r.magnitude(); //find mag of r
//reset nodep
nodep[i][0] = cg[0] + rmag*cos(theta+delalpha);
nodep[i][1] = cg[1] + rmag*sin(theta+delalpha);
}
//we move nodec for L-E smoothing, since we are looking for a delta in our routine and the "new mesh" passed into nodec and nodep each time
if (smooth_type == 1)
{
r = Vector(nodec[i][0] - cg[0], nodec[i][1] - cg[1]); //find r to be used in theta and node changing
theta = atan2(r[1],r[0]); //find angle using atan2 to get right quadrant angle
rmag = r.magnitude(); //find mag of r
//reset nodep
nodec[i][0] = cg[0] + rmag*cos(theta+delalpha);
nodec[i][1] = cg[1] + rmag*sin(theta+delalpha);
}
}
//these will now feed into the linear elastic, winslow, or opt based routine, which pass out new physical coords, do mesh file and create plot
if (smooth_type == 2)
{
//now, pass in tag, node-cell hash, node-node hash, physical nodes and computational nodes (u,v) (second only as storage location for perturbations), tri array, and dimensions into optimization-based smoothing procedure, also we pass in cvg mostly as a token
//also, pass iterations at which to cut off
opt_smooth(nn, nodep, nodec, hash, NChash, nt, tri, iterin, tag, cvg);
}
if (smooth_type == 1)
{
//now, pass in mat, tag, compressed row storage arrays, physical/computational nodes (second only as storage location for perturbed boundaries), tri array, and dimensions into linear-elastic smoothing procedure, where young's modulus computer (inline procedure), weights applied (matrix build procedure), smoothing done (linear solve procedure)
//also, pass cvg value, omega (relaxation factor), iterations at which to cut off if cvg not reached (iterin), and poisson's ratio (held constant)
linear_elastic(nn, nodep, nodec, mdim, mat, ia, ja, iau, nt, tri, iterin, cvg, omega, tag, poisson);
//now, we reset nodec as nodep, since we have moved the mesh and we need the proper delta to create u and v for L-E and nodec is only a placeholder
for (i = 0; i < nn; i++)
{
nodec[i][0] = nodep[i][0];
nodec[i][1] = nodep[i][1];
}
}
if (smooth_type == 0)
{
//now, pass in mat, tag, compressed row storage arrays, physical/computational nodes, tri array, and dimensions into winslow smoothing procedure, where weights applied (matrix build procedure), smoothing done (linear solve procedure)
//also, pass cvg value, omega (relaxation factor), iterations between recompute (iterin), iterations at which to cut off if cvg not reached (iterout)
//poisson passed in but not used to save writing an overloaded version of mat_build
//pass in A, B, C (forcing function coeff), whichff to tell which forcing function to create, and q to create forcing functions
//in case we are pasing in no variables and we want no forcing functions (C = 0)
if (nv == 0)
{
double **q;
q = (double**)calloc(nn,sizeof(double*));
for (i = 0; i < nn; i++)
q[i] = (double*)calloc(4,sizeof(double));
}
winslow(nn, nodep, nodec, mdim, mat, ia, ja, iau, nt, tri, iterin, iterout, cvg, omega, tag, poisson, A, B, C, whichff, q);
//set initial min/max low/high for loop
double minjac = 1.0e20;
double maxjac = -1.0e20;
//set counters for pos and neg jac to zero
int posjac = 0;
int negjac = 0;
//holder for jacobian
double avgjac = 0.0;
//check jacobians to see if smoothing successful
for (i = 0; i < nt; i++)
{
//grab indices
int t0 = tri[i][0];
int t1 = tri[i][1];
int t2 = tri[i][2];
//make points
Point pt0 = Point(nodep[t0][0],nodep[t0][1]);
Point pt1 = Point(nodep[t1][0],nodep[t1][1]);
Point pt2 = Point(nodep[t2][0],nodep[t2][1]);
//make vectors
Vector sd1 = Vector(pt1,pt2);
Vector sd2 = Vector(pt1,pt0);
//compute jacobian
avgjac = sd1 % sd2;
//find min/max
minjac = MIN(minjac,avgjac);
maxjac = MAX(maxjac,avgjac);
//count pos/neg jacobians
if (avgjac >=0)
posjac++;
else
negjac++;
}
//print results
printf("\nMax jacobian = %lf\n",maxjac);
printf("\nMin jacobian = %lf\n",minjac);
printf("\nPositive jacobians = %d\n",posjac);
printf("\nNegative jacobians = %d\n",negjac);
//now, free placeholder mem
if (nv == 0)
{
for (i = 0; i < nn; i++)
free(q[i]);
free(q);
}
}
//now, write out new physical mesh file
//take off _%d%d.dat from old file name and reset to '\0' to re-concatenate _%d%d+1.mesh
//find starting position of extension
i = strlen(filename) - strlen(strstr(filename,".dat"));
//set dig to 3 spaces since we will add zeros to single digit numbers
dig = 3;
//reset to '\0' dig further back to get rid of number and _
filename[i-dig] = '\0';
//reconcatenate
extension[0] = '\0'; //reset extension
dig = 0; //reset dig to zero for another use
if (iter_file/10 == 0) //doing integer math...if less than 10 iterations, we add 0 in front of iter_file
dig = 1;
//now, if dig, we add 0 in front of iter_file
if (dig)
sprintf(extension,"_0%d",iter_file); //we put iteration in extension
else
sprintf(extension,"_%d",iter_file); //we put iteration in extension
strcat(filename,extension); //add extension
strcat(filename,".mesh"); //add file extension
printf("\nOutput Mesh File filename = <%s>\n",filename);
//now, open file for write
if ((fp = fopen(filename,"w")) == 0)
{
printf("\nError opening file <%s>.",filename);
exit(0);
}
//now, fill in each section with current physical info (noting that connectivity from computational mesh still intact)
fprintf(fp,"#Number of grid points\n");
fprintf(fp,"%d\n",nn);
for (i = 0; i < nn; i++)
fprintf(fp,"%16.10e %16.10e\n",nodep[i][0],nodep[i][1]);
fprintf(fp,"#Number of blocks\n");
fprintf(fp,"%d\n",nblk);
//note, tri will need to be re-fortran indexed
fprintf(fp,"#Number of triangles\n");
fprintf(fp,"%d\n",nt);
for (i = 0; i < nt; i++)
fprintf(fp,"%d %d %d\n",tri[i][0]+1,tri[i][1]+1,tri[i][2]+1);
//note, quad will need to be re-fortran indexed
fprintf(fp,"#Number of quads\n");
fprintf(fp,"%d\n",nq);
if (nq > 0)
{
for (i = 0; i < nq; i++)
fprintf(fp,"%d %d %d %d\n",quad[i][0]+1,quad[i][1]+1,quad[i][2]+1,quad[i][3]+1);
}
fprintf(fp,"#Number of boundaries\n");
fprintf(fp,"%d\n",nb);
//note, bs will need to be re-fortran indexed
for (i = 0; i < nb; i++)
{
fprintf(fp,"#Number of edges on boundary %d\n",i);
fprintf(fp,"%d\n",nbs[i]);
for (j = 0; j < nbs[i]; j++)
{
fprintf(fp,"%d %d\n",bs[i][j][0]+1,bs[i][j][1]+1);
}
}
//I WANT SOLVER TO BEGIN FROM SCRATCH!
// write number of constants
fprintf(fp,"#Number of constants\n");
fprintf(fp,"%d\n",nc);
if (nc > 0)
{
// write out constants (we will need to know what each is in order, a priori)
for (i = 0; i < nc; i++)
fprintf(fp,"%lf\n",constants[i]);
}
// write out number of vars (usually four, but we could code for more if needed)
fprintf(fp,"#Number of variables\n");
fprintf(fp,"%d\n",0);
/*//we do not have it set up to read in variable names, so we just write out what we know they are a priori
fprintf(fp,"density\n");
fprintf(fp,"x-momentum\n");
fprintf(fp,"y-momentum\n");
fprintf(fp,"total energy\n");
//now, write out q....hard wired to four vars
if (nv > 0)
{
// write out q
for (i = 0; i < nn; i++)
fprintf(fp,"%16.10e %16.10e %16.10e %16.10e\n",q[i][0],q[i][1],q[i][2],q[i][3]);
}*/
fclose(fp);
//finally, write GNUPLOT file
//take off .mesh from old file name and reset to '\0' to re-concatenate .dat
//find starting position of file extension
i = strlen(filename) - strlen(strstr(filename,".mesh"));
//reset to '\0'
filename[i] = '\0';
//reconcatenate
strcat(filename,".dat");
printf("\nOutput Plot File Filename = <%s>\n",filename);
// Open file for write
if ((fp = fopen(filename,"w")) == 0)
{
printf("\nError opening file <%s>.",filename);
exit(0);
}
for (i=0; i < nt; i++)
{
n0 = tri[i][0];
n1 = tri[i][1];
n2 = tri[i][2];
fprintf(fp,"%19.10e %19.10e 0.0\n", nodep[n0][0],nodep[n0][1]);
fprintf(fp,"%19.10e %19.10e 0.0\n", nodep[n1][0],nodep[n1][1]);
fprintf(fp,"%19.10e %19.10e 0.0\n", nodep[n2][0],nodep[n2][1]);
fprintf(fp,"%19.10e %19.10e 0.0\n\n",nodep[n0][0],nodep[n0][1]);
}
fclose(fp);
} while (current_time < time); //stop once we have done prescribed number of time steps
//finally, let's compute RMSerror between each node of orig and final meshes
double RMSerr = 0.0;
for (i = 0; i < nn; i++)
RMSerr += (nodep[i][0] - tnode[i][0])*(nodep[i][0] - tnode[i][0]) + (nodep[i][1] - tnode[i][1])*(nodep[i][1] - tnode[i][1]);
//compute final RMS remembering that we have 2*nn elements since we have errors in x and y
RMSerr = sqrt(RMSerr/(2*nn));
//print to screen
printf("\nRMSerr between original and final meshes is %16.10e\n",RMSerr);
//free memory, reset to null pointers (for this if block)
if (smooth_type == 0 || smooth_type == 1)
{
freenull(ia);
freenull(ja);
freenull(iau);
freenull(mat);
}
freenull(tag);
freenull(tag2);
freenull(tnode);
for (i = 0; i < nn; i++)
delete NChash[i];
delete[] NChash;
if (smooth_type == 2)
{
//this is done earlier in l-e and winslow, but not until end in opt-based
for (i = 0; i < nn; i++)
delete hash[i];
delete[] hash;
}
}
if (operation == 1)
{
//read in number of functions
int test_funct = 0;
printf("\nEnter number of functions to be tested for refinement ->");
fgets(buff,bdim,stdin); //read in test_funct
sscanf(buff,"%d",&test_funct); //place in variable
//error checking
if (test_funct <= 0 || (test_funct > 1 && nv ==0) || test_funct == 2 || test_funct > 3)
{
printf("\nYou cannot refine based on %d functions with %d variables. Exiting....", test_funct, nv);
fflush(stdout);
exit(0);
}
int ft = 0; //which function to use var toggle
//read in which analytic function is to be used
if (nv == 0)
{
printf("\nEnter 0 to use the circle analytic function or 1 to use the cosine analytic function ->");
fgets(buff,bdim,stdin); //read in ft
sscanf(buff,"%d",&ft); //place in variable
//error checking
if (ft < 0 || ft > 1)
{
printf("\nYou cannot refine based on analytic function number %d. Exiting....", ft);
fflush(stdout);
exit(0);
}
}
//read in which solution based function(s) is/are to be used
if (nv == 4)
{
printf("\nEnter 2 to use the pressure function, 3 to use the velocity magnitude function, 4 to use the mach number function, or 5 to use all three ->");
fgets(buff,bdim,stdin); //read in ft
sscanf(buff,"%d",&ft); //place in variable
//error checking
if (ft < 2 || ft > 5 || (ft == 5 && test_funct != 3))
{
printf("\nYou cannot refine based on function number %d with %d total functions. Exiting....", ft,test_funct);
fflush(stdout);
exit(0);
}
}
//read in type of refinement funct
int funct_type = 0;
printf("\nEnter 0 for gradient-based or 1 for edge-based refinement ->");
fgets(buff,bdim,stdin); //read in funct_type
sscanf(buff,"%d",&funct_type); //place in variable
//error checking
if (funct_type < 0 || funct_type > 1)
{
printf("\nYou must choose 0 or 1 for gradient-based or edge-based refinement. Exiting....");
fflush(stdout);
exit(0);
}
//read in num of std deviations needed to refine
double Cr[3];
for (i = 0; i < test_funct; i++)
{
printf("\nEnter number of standard deviations needed for refining function %d ->",i);
fgets(buff,bdim,stdin); //read in Cr
sscanf(buff,"%lf",&Cr[i]); //place in variable
//error checking
if (Cr[i] <= 0.0)
{
printf("\nYou cannot use %lf std deviations for refining. Exiting....",Cr[i]);
fflush(stdout);
exit(0);
}
}
//read in num of std deviations needed to coarsen
double Cc[3];
for (i = 0; i < test_funct; i++)
{
printf("\nEnter number of standard deviations needed for coarsening function %d ->",i);
fgets(buff,bdim,stdin); //read in Cc
sscanf(buff,"%lf",&Cc[i]); //place in variable
//error checking
if (Cc[i] <= 0.0)
{
printf("\nYou cannot use %lf std deviations for coarsening. Exiting....",Cc[i]);
fflush(stdout);
exit(0);
}
}
//read in power to raise length to for refinement function
double p[3];
for (i = 0; i < test_funct; i++)
{
printf("\nEnter power to raise length to for refinement function %d ->",i);
fgets(buff,bdim,stdin); //read in p
sscanf(buff,"%lf",&p[i]); //place in variable
//error checking
if (p[i] < 1.0)
{
printf("\nYou cannot use %lf as the power in computing the refinement function. Exiting....",p[i]);
fflush(stdout);
exit(0);
}
}
//read in whether or not to retriangulate
remesh = 0;
printf("\nEnter 1 to retriangulate or 0 to leave as is (assuming no coarsening done) ->");
fgets(buff,bdim,stdin); //read in remesh
sscanf(buff,"%d",&remesh); //place in variable
//error checking
if (remesh < 0 || remesh > 1)
{
printf("\nYou must choose 0 for no retriangulation or 1 for a new Dealuney mesh. Exiting....",p);
fflush(stdout);
exit(0);
}
//we must expand tri to higher order connectivity
for (i = 0; i < nt; i++)
{
tri[i] = (int*)realloc((void*)tri[i],6*sizeof(int));
//init all entries to -1
tri[i][3] = tri[i][4] = tri[i][5] = -1;
}
//allocate for node to node hash to be passed into routine and filled in
List **hash;
hash = new List*[nn]; //each node has a list of nodes it's attached to
for (i=0; i < nn; i++)
hash[i] = new List(); //make each node's list
//now, create hash table to be passed to compressed row storage routine
Lhash(nn, nt, tri, hash);
//now, we build a nabor connectivity
//init Linked_Lists
Linked_List **Nhash;
Linked_List *mknbr;
//first, initialize node to element hash table
Nhash = new Linked_List*[nn];
for (i = 0; i < nn; i++)
Nhash[i] = new Linked_List();
//next, initialize list of all triangles (to keep track of nabor making needs in make_nbr)
mknbr = new Linked_List();
//now, insert each tri into mknbr and simultaneously create node to element hash
for (i = 0; i < nt; i++)
{
mknbr->Insert(i); //insert tri into list
for (j = 0; j < 3; j++)
{
n = tri[i][j]; //use n as placeholder for current node index (loop over all three)
Nhash[n]->Insert(i);
}
}
//now, create nabor connectivity to be passed in init to -1 and out full
int **nbr;
nbr = (int**)calloc(nt,sizeof(int*));
for (i = 0; i < nt; i++)
nbr[i] = (int*)calloc(3,sizeof(int));
for (i = 0; i < nt; i++)
nbr[i][0]=nbr[i][1]=nbr[i][2]=-1; //init to -1
//now, we have all our hash tables and we can create nabor connectivity
make_nbrs_HO(mknbr, nn, nt, tri, nbr, Nhash);
//now, we can delete mknbr, since only used for convenience of keeping track in make_nbr
delete mknbr;
//create tag array of boundry info, no need to send nb, nbs, bs to subroutines
int *tag = (int*)calloc(nn,sizeof(int));
//init tag to ones, we need tagged boundaries for both gradients and areas since we deal with closing the contours there differently
for (i = 0; i < nn; i++)
tag[i] = 1;
//1 for interior, 0 for boundary
for (i = 0; i < nb; i++)
{
for (j = 0; j < nbs[i]; j++)
{
for (k = 0; k < 2; k++)
{
if (tag[bs[i][j][k]] == 1)
tag[bs[i][j][k]] = 0; //just to be sure we don't waste time overwriting
}
}
}
//also, before doing coarsening, we define map array to help with deletion
//we also do this here due to the need to realloc
int *map = (int*)calloc(nn,sizeof(int));
//init to -1
for (i = 0; i < nn; i++)
map[i] = -1;
//now, take all boundary nodes and set to 0 (keep)
for (i = 0; i < nn; i++)
if (tag[i] == 0)
map[i] = 0;
//now, we pass info into subdivision routine to compute functions, gradients, determine refinement status
int newnodes = subdivision(q, nv, test_funct, tri, nt, nodep, nn, funct_type, Cr, Cc, p, hash, nbr, tag, map, ft);
//we will eventually use this list to remap to new global node numbers and send only these to trimesh to re-triangulate
//now, we set map of new nodes to zero and realloc map
//also, if there are nodes deleted, we will do that later
map = (int*)realloc((void*)map,newnodes*sizeof(int));
for (i = nn; i < newnodes; i++)
map[i] = 0; //we always keep refined nodes
//now, we want to generate new nodes and realloc nodep
//again, we will get rid of deleted nodes before we send to trimesh
nodep = (double**)realloc((void*)nodep,newnodes*sizeof(double*));
for (i = nn; i < newnodes; i++)
nodep[i] = (double*)calloc(2,sizeof(double));
//now, we loop through triangles and store physical coords of new nodes in nodep
//first, declare some placeholder vars
int nd0, nd1; //node index placeholders
Point p0, p1, p2, pt0, pt1, newpt; //point class placeholders
for (i = 0; i < nt; i++)
{
//use node indices for cleanliness
n0 = tri[i][0];
n1 = tri[i][1];
n2 = tri[i][2];
//create point class placeholders for ease
p0 = Point(nodep[n0][0],nodep[n0][1]);
p1 = Point(nodep[n1][0],nodep[n1][1]);
p2 = Point(nodep[n2][0],nodep[n2][1]);
//now, switch over all three sides to check for new nodes
for (j = 0; j < 3; j++)
{
switch(j)
{
case 0:
pt0 = p0;
pt1 = p1;
break;
case 1:
pt0 = p1;
pt1 = p2;
break;
case 2:
pt0 = p2;
pt1 = p0;
break;
default:
printf("\nYou have a triangle with more than three sides according to the loop counter in driver.cpp!\n");
fflush(stdout);
exit(0);
break;
}
//now, define new point
if ((n = tri[i][j+3]) >= 0)
{
newpt = (pt0 + pt1)/2.0;
nodep[n][0] = newpt[0];
nodep[n][1] = newpt[1];
}
}
}
//now, transfer solution by extending q and using averaging to find q at new points
if (nv > 0)
{
q = (double**)realloc((void*)q,newnodes*sizeof(double*));
for (i = nn; i < newnodes; i++)
q[i] = (double*)calloc(nv,sizeof(double));
//we will use triangle conn to find new q val
for (i = 0; i < nt; i++)
{
//use node indices for cleanliness
n0 = tri[i][0];
n1 = tri[i][1];
n2 = tri[i][2];
//now, switch over all three sides to update q at any new nodes
for (j = 0; j < 3; j++)
{
switch(j)
{
case 0:
nd0 = n0;
nd1 = n1;
break;
case 1:
nd0 = n1;
nd1 = n2;
break;
case 2:
nd0 = n2;
nd1 = n0;
break;
default:
printf("\nYou have a triangle with more than three sides according to the loop counter in driver.cpp!\n");
fflush(stdout);
exit(0);
break;
}
//now, define new q vals
if ((n = tri[i][j+3]) >= 0)
for (k = 0; k < nv; k++)
q[n][k] = (q[nd0][k] + q[nd1][k])/2.0;
}
}
}
//now, reset nn to newnodes and old_nn to orig nn for memory freeing
old_nn = nn;
nn = newnodes;
//now, we need to update boundaries by looping thru bd seg, using node_cell hash to find tri, looking for new node on edge, and reallocing as we go
//linked nodes to read thru linked list (node_cell hash)
Linked_Node *hd0, *hd1;
for (i = 0; i < nb; i++)
{
for (j = 0; j < nbs[i]; j++)
{
//set nodes to look for
n0 = bs[i][j][0];
n1 = bs[i][j][1];
//we don't need to look thru bs with newly created nodes, since they cannot be split
if (n0 >= old_nn || n1 >= old_nn)
continue;
//init m (triangle with bs in it) to -1
m = -1;
// each element in n0's list is a triangle with that node in it
hd0 = Nhash[n0]->head;
//while there are elements that have n0 in them and m not set, keep looking
while (hd0 && m < 0)
{
//cell from n0 Nhash
n = hd0->data;
//now, look to other node on bd seg's Nhash to see if it is also in element n
hd1 = Nhash[n1]->head;
//while there are elements in n1's Nhash and m unset
while (hd1 && m < 0)
{
//if the element in n1's hash matches the element in n0's hash, we have the element that constains bd seg
//set triangle that has both bs nodes as m
if (hd1->data == n)
m = n;
//move to the next element in n1's hash, even if unneeded
hd1 = hd1->next;
}
//move to the next element in n0's hash, even if unneeded
hd0 = hd0->next;
}
//check that a triangle has been found...if not, we have a problem!
if (m < 0)
{
printf("\nBoundary segment %d on boundary %d is NOT in a triangle! Exiting....\n",j,i);
fflush(stdout);
exit(0);
}
//now that we have a triangle that bs is in, look to see if we have a new node on the given side
//run thru a switch
for (s = 0; s < 3; s++)
{
switch(s)
{
case 0:
nd0 = tri[m][0];
nd1 = tri[m][1];
break;
case 1:
nd0 = tri[m][1];
nd1 = tri[m][2];
break;
case 2:
nd0 = tri[m][2];
nd1 = tri[m][0];
break;
default:
printf("\nYou have a triangle with more than three sides according to the loop counter in driver.cpp!\n");
fflush(stdout);
exit(0);
break;
}
//look thru sides, if find side (with new point) then reset bd seg, realloc bs
if (nd0 == n0 && nd1 == n1)
{
if (tri[m][s+3] >= 0)
{
nbs[i]++; //increment number of boundaries
bs[i] = (int**)realloc((void*)bs[i],nbs[i]*sizeof(int*)); //realloc number of bs for bd i
for (k = nbs[i]-1; k < nbs[i]; k++)
bs[i][k] = (int*)calloc(2,sizeof(int)); //add spots for two more indices at end of list
//now, place first half in orig spot and second half in new spot
//be careful to keep ordering straight
bs[i][j][0] = n0;
bs[i][j][1] = tri[m][s+3];
bs[i][nbs[i]-1][0] = tri[m][s+3];
bs[i][nbs[i]-1][1] = n1;
}
}
if (nd0 == n1 && nd1 == n0)
{
printf("\nBoundary segment %d on boundary %d is out of order with triangle side %d on triangle &d!\n",j,i,s,m);
fflush(stdout);
exit(0);
}
}
}
}
//we can free nbr now since we no longer need it, and nt and old_nt will change
for (i = 0; i < nt; i++)
free(nbr[i]);
freenull(nbr);
//now, we count the number of new triangles created so as to realloc tri
//first, we need to set old_nt to current nt (for loop), since nt will be incremented as we go
int old_nt = nt;
//printf("\nold_nt = %d",old_nt);
//fflush(stdout);
//also, let's create a triangle array (original style connectivity) which is hardwired to 4 triangles (most we can get in 2-D)
const int cdim = 4;
int tri_piece[cdim][3]; //no need to free since static alloc
//also, let's create a temp array to hold our current triangles conn
int conn[6]; //no need to free since static alloc
//even if we are going to retriangulate, we do this so that we have a better idea of how many triangles we may have
for (i = 0; i < old_nt; i++)
{
//first, ready the current tri higher order conn to be passed in
for (j = 0; j < 6; j++)
conn[j] = tri[i][j];
//now, reset the tri_piece array
for (j = 0; j < cdim; j++)
for (k = 0; k < 3; k++)
tri_piece[j][k] = 0;
//now, pass into refine tri only to determine new nt (use l as dummy, since if returns 1, no new triangles!)
l = refine_tri(conn, cdim, tri_piece, nodep);
//now, if l > 1, add l - 1 to tri, since we will be deleting the mother triangle each time
if (l > 1)
nt += (l-1);
}
//printf("\nnt = %d",nt);
//fflush(stdout);
//now, we realloc tri
tri = (int**)realloc((void*)tri,nt*sizeof(int*));
for (i = old_nt; i < nt; i++)
tri[i] = (int*)calloc(6,sizeof(int));
//also reset new tri entries 3, 4, 5 to -1
for (i = old_nt; i < nt; i++)
for (j = 3; j < 6; j++)
tri[i][j] = -1;
//we set a flagC to find out if coarsening must occur
flagC = 0;
//now check for coarsening
for (i = 0; i < nn; i++)
{
if (map[i] == -1)
flagC++; //will reuse for realloc
}
//we only do this if remesh set to 0 AND we have NOT coarsened
if (remesh == 0 && !flagC)
{
//now, we add in new triangles
for (i = 0; i < old_nt; i++)
{
//first, ready the current tri higher order conn to be passed in
for (j = 0; j < 6; j++)
conn[j] = tri[i][j];
//now, reset the tri_piece array
for (j = 0; j < cdim; j++)
for (k = 0; k < 3; k++)
tri_piece[j][k] = 0;
//now, pass into refine tri to determine new connectivity (refine_tri gives global nodes)
//l is a dummy var that holds new triangles gen to help loop counter and conditional for adding new tri
l = refine_tri(conn, cdim, tri_piece, nodep);
//now, take tri_piece array and add first triangle into old tri spot, and the rest to the bottom of the list
if (l > 1)
{
//first new triangle goes in old tri spot
for (j = 0; j < 3; j++)
tri[i][j] = tri_piece[0][j];
//now, add the rest of the new triangles to tri starting at old_nt
for (j = 1; j < l; j++)
{
for (k = 0; k < 3; k++)
{
//reset each element in new tri conn to tri_piece passed out from refine_tri
tri[old_nt][k] = tri_piece[j][k];
}
old_nt++; //increment old_nt AFTER adding EACH triangle
}
}
}
}
//finally, reduce conn to lower order no matter what!
for (i = 0; i < nt; i++)
tri[i] = (int*)realloc((void*)tri[i],3*sizeof(int));
// we only bother to remap if we had deletions
if (flagC)
{
//now, we wish to remap the undeleted and refined and boundary nodes
int nodemap = 0; //start numbering at zero
for (i = 0; i < nn; i++)
{
if (map[i] == 0)
{
map[i] = nodemap;
nodemap++;
}
}
//now, we need to remap the physical nodes and realloc
for (i = 0; i < nn; i++)
{
if (map[i] >= 0 && map[i] != i)
{
nodep[map[i]][0] = nodep[i][0]; //move x node back
nodep[map[i]][1] = nodep[i][1]; //move y node back
}
}
//printf("\nnn = %d\n",nn);
//printf("\nflagC = %d\n",flagC);
//now realloc nodep
for (i = (nn-flagC); i < nn; i++)
freenull(nodep[i]);
nodep = (double**)realloc((void*)nodep,(nn-flagC)*sizeof(double*));
//now, we need to remap bs
for (i = 0; i < nb; i++)
for (j = 0; j < nbs[i]; j++)
for (k = 0; k < 2; k++)
bs[i][j][k] = map[bs[i][j][k]];
//now, we need to remap q and realloc
for (i = 0; i < nn; i++)
{
for (j = 0; j < nv; j++)
{
if (map[i] >= 0 && map[i] != i)
{
q[map[i]][j] = q[i][j]; //move q_j node back
}
}
}
//now realloc q
for (i = (nn-flagC); i < nn; i++)
freenull(q[i]);
q = (double**)realloc((void*)q,(nn-flagC)*sizeof(double*));
//reset nn
nn -= flagC;
//printf("\nnew nn = %d\n",nn);
}
//now, we wish to re trimesh if we had deletions or remesh == 1
//note that the trimesh that is passed in is void and will be redone completely and reallocated if necessary
//however, if less triangles are generated, than all entries past nt are garbage, but it is the end of the program and we needn't realloc!
if (remesh == 1 || flagC)
{
//now, we need to place nodep into temp arrays for passing to trimesh
double *x, *y;
x = (double*)calloc(nn,sizeof(double));
y = (double*)calloc(nn,sizeof(double));
for (i = 0; i < nn; i++)
{
x[i] = nodep[i][0];
y[i] = nodep[i][1];
}
// iterative loop to allocate space for triangle indices if more is needed
tdim = -1; //start at -1 to assure goes thru loop
// if we run out of space, trimesh returns -1 and asks to realloc by adding increments on nn
do
{
tdim = trimesh(nn, nt, nb, nbs, bs, x, y, tri);
if (tdim < 0)
{
printf("\nExpanding triangle dimension from %d to %d",nt,nt+nn);
fflush(stdout);
// increment tri array dimension by number of nodes
nt += nn;
//now, we realloc tri..even though the routine will start from scratch
tri = (int**)realloc((void*)tri,nt*sizeof(int*));
for (i = nt-nn; i < nt; i++)
tri[i] = (int*)calloc(3,sizeof(int));
}
} while (tdim < 0);
//nt is already reset for allocation purposes, but we wish to reset it so if we have extra garbage at the end, we don't print it out
nt = tdim;
}
//now, write out new physical mesh file
strcat(filename,".mesh"); //add file extension
printf("\nOutput Mesh File filename = <%s>\n",filename);
//now, open file for write
if ((fp = fopen(filename,"w")) == 0)
{
printf("\nError opening file <%s>.",filename);
exit(0);
}
//now, fill in each section with current physical info (noting that connectivity from computational mesh still intact)
fprintf(fp,"#Number of grid points\n");
fprintf(fp,"%d\n",nn);
for (i = 0; i < nn; i++)
fprintf(fp,"%16.10e %16.10e\n",nodep[i][0],nodep[i][1]);
fprintf(fp,"#Number of blocks\n");
fprintf(fp,"%d\n",nblk);
//note, tri will need to be re-fortran indexed
fprintf(fp,"#Number of triangles\n");
fprintf(fp,"%d\n",nt);
for (i = 0; i < nt; i++)
fprintf(fp,"%d %d %d\n",tri[i][0]+1,tri[i][1]+1,tri[i][2]+1);
//note, quad will need to be re-fortran indexed
fprintf(fp,"#Number of quads\n");
fprintf(fp,"%d\n",nq);
if (nq > 0)
{
for (i = 0; i < nq; i++)
fprintf(fp,"%d %d %d %d\n",quad[i][0]+1,quad[i][1]+1,quad[i][2]+1,quad[i][3]+1);
}
fprintf(fp,"#Number of boundaries\n");
fprintf(fp,"%d\n",nb);
//note, bs will need to be re-fortran indexed
for (i = 0; i < nb; i++)
{
fprintf(fp,"#Number of edges on boundary %d\n",i);
fprintf(fp,"%d\n",nbs[i]);
for (j = 0; j < nbs[i]; j++)
{
fprintf(fp,"%d %d\n",bs[i][j][0]+1,bs[i][j][1]+1);
}
}
// write number of constants
fprintf(fp,"#Number of constants\n");
fprintf(fp,"%d\n",nc);
if (nc > 0)
{
// write out constants (we will need to know what each is in order, a priori)
for (i = 0; i < nc; i++)
fprintf(fp,"%lf\n",constants[i]);
}
// write out number of vars (usually four, but we could code for more if needed)
fprintf(fp,"#Number of variables\n");
fprintf(fp,"%d\n",nv);
//we do not have it set up to read in variable names, so we just write out what we know they are a priori
fprintf(fp,"density\n");
fprintf(fp,"x-momentum\n");
fprintf(fp,"y-momentum\n");
fprintf(fp,"total energy\n");
//now, write out q....hard wired to four vars
if (nv > 0)
{
// write out q
for (i = 0; i < nn; i++)
fprintf(fp,"%16.10e %16.10e %16.10e %16.10e\n",q[i][0],q[i][1],q[i][2],q[i][3]);
}
fclose(fp);
//finally, write GNUPLOT file
//take off .mesh from old file name and reset to '\0' to re-concatenate .dat
//find starting position of file extension
i = strlen(filename) - strlen(strstr(filename,".mesh"));
//reset to '\0'
filename[i] = '\0';
//reconcatenate
strcat(filename,".dat");
printf("\nOutput Plot File Filename = <%s>\n",filename);
// Open file for write
if ((fp = fopen(filename,"w")) == 0)
{
printf("\nError opening file <%s>.",filename);
exit(0);
}
for (i = 0; i < nt; i++)
{
n0 = tri[i][0];
n1 = tri[i][1];
n2 = tri[i][2];
fprintf(fp,"%19.10e %19.10e 0.0\n", nodep[n0][0],nodep[n0][1]);
fprintf(fp,"%19.10e %19.10e 0.0\n", nodep[n1][0],nodep[n1][1]);
fprintf(fp,"%19.10e %19.10e 0.0\n", nodep[n2][0],nodep[n2][1]);
fprintf(fp,"%19.10e %19.10e 0.0\n\n",nodep[n0][0],nodep[n0][1]);
}
fclose(fp);
//free up memory (for this if block)
for (i = 0; i < old_nn; i++)
delete Nhash[i];
delete [] Nhash;
for (i = 0; i < old_nn; i++)
delete hash[i];
delete[] hash;
if (nv > 0)
{
for (i = 0; i < nn; i++)
free(q[i]);
freenull(q);
}
if (nc > 0)
freenull(constants);
}
//free memory, reset to null pointers (for whole program)
//depending on if we smoothed or refined, we need to delete a different amount of nodec
if (operation == 0)
{
for (i = 0; i < nn; i++)
free(nodec[i]);
freenull(nodec);
}
if (operation == 1)
{
for (i = 0; i < old_nn; i++)
free(nodec[i]);
freenull(nodec);
}
for (i = 0; i < nn; i++)
free(nodep[i]);
freenull(nodep);
//if we did retriangulation, we need to be sure to free the right amount of memory, so we use tdim
if (remesh == 1 || flagC)
{
for (i = 0; i < tdim; i++)
free(tri[i]);
freenull(tri);
}
else
{
for (i = 0; i < nt; i++)
free(tri[i]);
freenull(tri);
}
if (nq > 0)
{
for (i = 0; i < nq; i++)
free(quad[i]);
freenull(quad);
}
for (i = 0; i < nb; i++)
for (j = 0; j < nbs[i]; j++)
free(bs[i][j]);
for (i = 0; i < nb; i++)
free(bs[i]);
freenull(bs);
freenull(nbs);
return(0);
}
| vincentbetro/NACA-SIM | mesher/driver.cpp | C++ | gpl-2.0 | 68,578 |
/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
package com.mediatek.bluetooth.opp.adp;
import android.os.Process;
import com.mediatek.bluetooth.opp.mmi.OppLog;
public class OppTaskWorkerThread extends Thread {
private boolean mHasMoreTask = false;
private OppTaskHandler mHandler;
public OppTaskWorkerThread(String name, OppTaskHandler handler) {
super(name + "WorkerThread");
this.mHandler = handler;
}
@Override
public void run() {
OppLog.d("OppTask worker thread start: thread name - " + this.getName());
// need to increase the priority (higher than message-listener thread)
// or the event will be queued in EventQueue
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND - 3);
// loop until be interrupted
while (!this.isInterrupted()) {
try {
// before wait (for new task)
OppLog.d("OppTaskWorkerThread[" + this.getName() + "]: 1. beforeWait()");
if (!this.mHandler.beforeWait()) {
continue;
}
// wait for task
OppLog.d("OppTaskWorkerThread[" + this.getName() + "]: 2. waitNewTask()");
this.waitNewTask();
// after wait (new task arrival)
OppLog.d("OppTaskWorkerThread[" + this.getName() + "]: 3. afterWait()");
this.mHandler.afterWait();
// finish this loop
OppLog.d("OppTaskWorkerThread[" + this.getName() + "]: 4. next loop");
} catch (InterruptedException ex) {
OppLog.i("OppTaskWorkerThread[" + this.getName() + "] interrupted: "
+ ex.getMessage());
break;
}
}
OppLog.d("OppTaskWorkerThread[" + this.getName() + "] stopped.");
}
public synchronized void waitNewTask() throws InterruptedException {
// only wait when no more task
if (!this.mHasMoreTask) {
this.wait();
}
// all tasks will be processed below
this.mHasMoreTask = false;
}
public synchronized void notifyNewTask() {
OppLog.d("notify new task for OppTaskWorkerThread[" + this.getName() + "]");
this.mHasMoreTask = true;
this.notify();
}
}
| rex-xxx/mt6572_x201 | mediatek/packages/apps/Bluetooth/profiles/opp/src/com/mediatek/bluetooth/opp/adp/OppTaskWorkerThread.java | Java | gpl-2.0 | 4,522 |
'use strict';
var angular = require('angular');
var angularMessages = require('angular-messages');
var satellizer = require('satellizer');
var material = require('angular-material');
angular.module('sheltrApp', [
require('angular-ui-router'),
require('./controllers'),
require('./services'),
'ngMaterial',
'ngMessages',
'satellizer',
])
.run([
'$animate',
'$rootScope',
'$state',
'$stateParams',
'$auth',
function($animate, $rootScope, $state, $stateParams, $auth) {
$animate.enabled(true);
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
$rootScope.isAuthenticated = function() {
return $auth.isAuthenticated();
};
},
])
.config([
'$stateProvider',
'$authProvider',
'$urlRouterProvider',
function(
$stateProvider,
$authProvider,
$urlRouterProvider) {
$urlRouterProvider.otherwise('/login');
$authProvider.tokenPrefix = 'sheltr';
$authProvider.loginUrl = '/api/authenticate';
function skipIfLoggedIn($q, $auth) {
var deferred = $q.defer();
if ($auth.isAuthenticated()) {
deferred.reject();
} else {
deferred.resolve();
}
return deferred.promise;
}
function loginRequired($q, $location, $auth) {
var deferred = $q.defer();
if ($auth.isAuthenticated()) {
deferred.resolve();
} else {
$location.path('/login');
}
return deferred.promise;
}
function isAuthorized(permission) {
return function($q, $location, $auth) {
var deferred = $q.defer();
var payload = $auth.getPayload();
if (payload[permission]) {
deferred.resolve();
} else {
$location.path('/');
}
return deferred.promise;
};
}
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'views/login.form.html',
controller: 'LoginController',
resolve: {
skipIfLoggedIn: skipIfLoggedIn,
},
})
.state('logout', {
url: '/logout',
template: null,
controller: 'LogoutController',
resolve: {
loginRequired: loginRequired,
},
})
.state('signup', {
url: '/applicants/new',
templateUrl: 'views/applicant.view.html',
controller: 'SignupController',
resolve: {
loginRequired: loginRequired,
},
})
.state('home', {
url: '/',
templateUrl: 'views/home.html',
controller: 'HomeController',
resolve: {
loginRequired: loginRequired,
},
})
.state('applicant', {
url: '/applicants/:id',
templateUrl: 'views/applicant.view.html',
controller: 'ApplicantController',
resolve: {
loginRequired: loginRequired,
},
})
.state('organization', {
url: '/organization',
templateUrl: 'views/org.view.html',
controller: 'OrgController',
resolve: {
adminRequired: isAuthorized('admin'),
},
});
},
]);
| ChrisMcKenzie/sheltr | public/scripts/app.js | JavaScript | gpl-2.0 | 3,328 |
<?php
/**
* The template for displaying a "No posts found" message
*
* @package WordPress
* @subpackage nuvio_futuremag
* @since Nuvio FutureMag 1.0
*/
?>
<header class="page-header">
<h1 class="page-title"><?php _e( 'Nothing Found', 'nuviofuturemag' ); ?></h1>
</header>
<div class="page-content">
<?php if ( is_home() && current_user_can( 'publish_posts' ) ) : ?>
<p><?php printf( __( 'Ready to publish your first post? <a href="%1$s">Get started here</a>.', 'nuviofuturemag' ), admin_url( 'post-new.php' ) ); ?></p>
<?php elseif ( is_search() ) : ?>
<p><?php _e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'nuviofuturemag' ); ?></p>
<?php get_search_form(); ?>
<?php else : ?>
<p><?php _e( 'It seems we can’t find what you’re looking for. Perhaps searching can help.', 'nuviofuturemag' ); ?></p>
<?php get_search_form(); ?>
<?php endif; ?>
</div><!-- .page-content -->
| elongton/meandmygirls | wp-content/themes/nuviofuturemag-red/content-none.php | PHP | gpl-2.0 | 961 |
package org.totalboumboum.ai.v201112.ais.kayukataskin.v3.criterion;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
import org.totalboumboum.ai.v201112.adapter.agent.AiUtilityCriterionString;
import org.totalboumboum.ai.v201112.adapter.communication.StopRequestException;
import org.totalboumboum.ai.v201112.adapter.data.AiTile;
import org.totalboumboum.ai.v201112.ais.kayukataskin.v3.KayukaTaskin;
/**
* Cette classe est un simple exemple de
* critère chaîne de caractères. Copiez-la, renommez-la, modifiez-la
* pour l'adapter à vos besoin. Notez que le domaine
* de définition est spécifiés dans l'appel au constructeur
* ({@code super(nom,inf,sup)}).
*
* @author Pol Kayuka
* @author Ayça Taşkın
*/
@SuppressWarnings("deprecation")
public class CriterionThird extends AiUtilityCriterionString
{ /** Nom de ce critère */
public static final String NAME = "THIRD";
/** Valeurs du domaine de définition */
public static final String VALUE1 = "une valeur";
/** */
public static final String VALUE2 = "une autre valeur";
/** */
public static final String VALUE3 = "encore une autre";
/** */
public static final String VALUE4 = "et puis une autre";
/** */
public static final String VALUE5 = "et enfin une dernière";
/** Domaine de définition */
public static final Set<String> DOMAIN = new TreeSet<String>(Arrays.asList
( VALUE1,
VALUE2,
VALUE3,
VALUE4,
VALUE5
));
/**
* Crée un nouveau critère entier.
* @param ai
* ?
* @throws StopRequestException
* Au cas où le moteur demande la terminaison de l'agent.
*/
public CriterionThird(KayukaTaskin ai) throws StopRequestException
{ // init nom + bornes du domaine de définition
super(NAME,DOMAIN);
ai.checkInterruption();
// init agent
this.ai = ai;
}
/////////////////////////////////////////////////////////////////
// ARTIFICIAL INTELLIGENCE /////////////////////////////////////
/////////////////////////////////////////////////////////////////
/** */
protected KayukaTaskin ai;
/////////////////////////////////////////////////////////////////
// PROCESS /////////////////////////////////////
/////////////////////////////////////////////////////////////////
@Override
public String processValue(AiTile tile) throws StopRequestException
{ ai.checkInterruption();
String result = VALUE3;
// à compléter par le traitement approprié
return result;
}
}
| vlabatut/totalboumboum | resources/ai/org/totalboumboum/ai/v201112/ais/kayukataskin/v3/criterion/CriterionThird.java | Java | gpl-2.0 | 2,534 |
/*
* java-gnome, a UI library for writing GTK and GNOME programs from Java!
*
* Copyright © 2011 Operational Dynamics Consulting, Pty Ltd and Others
*
* The code in this file, and the program it is a part of, is made available
* to you by its authors as open source software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License version
* 2 ("GPL") as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GPL for more details.
*
* You should have received a copy of the GPL along with this program. If not,
* see http://www.gnu.org/licenses/. The authors of this program may be
* contacted through http://java-gnome.sourceforge.net/.
*
* Linking this library statically or dynamically with other modules is making
* a combined work based on this library. Thus, the terms and conditions of
* the GPL cover the whole combination. As a special exception (the
* "Claspath Exception"), the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module. An independent
* module is a module which is not derived from or based on this library. If
* you modify this library, you may extend the Classpath Exception to your
* version of the library, but you are not obligated to do so. If you do not
* wish to do so, delete this exception statement from your version.
*/
package org.gnome.gtk;
/**
* Manual code allowing us to handle some data returned by GtkStyleContext
* methods.
*
* @author Guillaume Mazoyer
*/
final class GtkStyleContextOverride extends Plumbing
{
static final RegionFlags hasRegion(StyleContext self, String region) {
int result;
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
synchronized (lock) {
result = gtk_style_context_contains_region(pointerOf(self), region);
return (RegionFlags) enumFor(RegionFlags.class, result);
}
}
private static native final int gtk_style_context_contains_region(long self, String region);
static final String[] getClasses(StyleContext self) {
String[] result;
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
synchronized (lock) {
result = gtk_style_context_get_classes(pointerOf(self));
return result;
}
}
private static native final String[] gtk_style_context_get_classes(long self);
static final String[] getRegions(StyleContext self) {
String[] result;
if (self == null) {
throw new IllegalArgumentException("self can't be null");
}
synchronized (lock) {
result = gtk_style_context_get_regions(pointerOf(self));
return result;
}
}
private static native final String[] gtk_style_context_get_regions(long self);
}
| cyberpython/java-gnome | src/bindings/org/gnome/gtk/GtkStyleContextOverride.java | Java | gpl-2.0 | 3,406 |
<?php
/*
* Template Name: Manage Students
* Description: Allows for the creation/deletion of students
*
* Author: Andrey Brushchenko
* Date: 11/18/2013
*/
get_header(); ?>
<?php include_once(get_template_directory() . '/logic/students.php'); ?>
<?php if ($userFeedback): ?>
<div id="action-box"><?php echo $userFeedback; ?></div>
<?php endif; ?>
<!-- Course Selector -->
<?php require_once(get_template_directory() . '/templates/course-selector.php'); ?>
<!-- Single Student Creation Form -->
<div id="create-student-box-top">
<div id='create-student-title'>Create student</div>
<form action="<?php echo site_url('/students/?courseId=' . $courseId) ?>" method="post">
<div id="create-student-field">
<p class="create-student-top">Username</p>
<input class='create-student' type="text" name="inptUserName" required>
</div>
<div id="create-student-field">
<p class="create-student-top">First Name</p>
<input class='create-student' type="text" name="inptFirstName" required>
</div>
<div id="create-student-field">
<p class="create-student-top">Last Name</p>
<input class='create-student' type="text" name="inptLastName" required>
</div>
<div id="create-student-field">
<p class="create-student-top">Email</p>
<input class='create-student' type="text" name="inptEmail" required>
</div>
<div id="create-student-buttons">
<input type="hidden" name="action" value="create">
<input type="submit" value="Create"/>
<a href="<?php echo site_url('/class/') ?>"><button type="button">Cancel</button></a>
</div>
</form>
</div>
<!-- Single Student Creation Form -->
<!-- Student File Upload Form -->
<div id="create-student-box-bottom">
<div id='create-student-title'>Create students via file</div>
<form action="<?php echo get_permalink() . "?courseId={$courseId}" ?>" method="post" enctype="multipart/form-data">
<div id="create-student-field">
<p class="create-student-bottom">Spreadsheet</p>
<input type="file" name="studentdata">
</div>
<div id="create-student-buttons">
<input type="hidden" name="courseId" value="<?php echo $courseId; ?>">
<input type="hidden" name="action" value="csvUpload">
<input type="submit">
<a href="<?php echo site_url('/class/') ?>"><button type="button">Cancel</button></a>
</div>
</form>
</div>
<!-- Student File Upload Form -->
<!-- Student List Display -->
<div id='table'>
<div id='table-title'>Manage enrolled students</div>
<table>
<thead>
<tr>
<th>Login</th>
<th>Name</th>
<th>Display Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php if(false == $hasStudents): ?>
<tr>
<th class="center" colspan="4">This course has no enrolled students</th>
</tr>
<?php else: ?>
<?php foreach($studentList as $student): ?>
<tr>
<th><?php echo $student->user_login; ?></th>
<th><?php echo $student->real_name; ?></th>
<th><?php echo $student->display_name; ?></th>
<th>
<form action="<?php echo site_url('/students/?courseId=') . $courseId; ?>"
method="post">
<select name="action">
<option disabled="disabled" selected>Choose an action</option>
<option value="delete">Delete</option>
<option value="resetPassword">Reset Password</option>
</select>
<input type="hidden" name="studentid" value="<?php echo $student->ID; ?>">
<input type="hidden" name="courseId" value="<?php echo $courseId; ?>">
<input type="submit" value="Confirm"/>
</form>
</th>
</tr>
<?php endforeach; ?>
<tr>
<th colspan="3"><strong>All Students</strong></th>
<th>
<form action="<?php echo site_url('/students/?courseId=') . $courseId; ?>"
method="post">
<select name="action">
<option disabled="disabled" selected>Choose an action</option>
<option value="deleteAll">Delete</option>
<option value="resetAllPasswords">Reset Passwords</option>
</select>
<input type="hidden" name="courseId" value="<?php echo $courseId; ?>">
<input type="submit" value="Confirm"/>
</form>
</th>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
<!-- Student List Display -->
<?php get_footer() ?>
| kelvinhsung/GTCS12 | templates/students.php | PHP | gpl-2.0 | 4,381 |
#include "svmClassifier.hpp"
| moosemaniam/cocobongo | lib/svmClassifier.cpp | C++ | gpl-2.0 | 31 |
<?php
/**
* Envato Theme Upgrader class to extend the WordPress Theme_Upgrader class.
*
* @package Envato WordPress Updater
* @author Arman Mirkazemi, Derek Herman <derek@valendesigns.com>
* @since 1.0
*/
include_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
include_once( 'class-envato-protected-api.php' );
if ( class_exists( 'Theme_Upgrader' ) && ! class_exists( 'Envato_WordPress_Theme_Upgrader' ) ) {
/**
* Envato Wordpress Theme Upgrader class to extend the WordPress Theme_Upgrader class.
*
* @package Envato WordPress Theme Upgrader Library
* @author Derek Herman <derek@valendesigns.com>, Arman Mirkazemi
* @since 1.0
*/
class Envato_WordPress_Theme_Upgrader extends Theme_Upgrader
{
protected $api_key;
protected $username;
protected $api;
protected $installation_feedback;
public function __construct( $username, $api_key )
{
parent::__construct(new Envato_Theme_Installer_Skin($this));
$this->constants();
$this->installation_feedback = array();
$this->username = $username;
$this->api_key = $api_key;
$this->api = &new Envato_Protected_API( $this->username, $this->api_key );
}
/**
* Checks for theme updates on ThemeForest marketplace
*
* @since 1.0
* @access public
*
* @param string Name of the theme. If not set checks for updates for the current theme. Default ''.
* @param bool Allow API calls to be cached. Default true.
* @return object A stdClass object.
*/
public function check_for_theme_update( $theme_name = '', $allow_cache = true )
{
$result = new stdClass();
$purchased_themes = $this->api->wp_list_themes( $allow_cache );
if ( $errors = $this->api->api_errors() )
{
$result->errors = array();
foreach( $errors as $k => $v ) {
array_push( $result->errors , $v);
}
return $result;
}
if ( empty($theme_name) ) {
$theme_name = wp_get_theme();
}
$purchased_themes = $this->filter_purchased_themes_by_name($purchased_themes, $theme_name);
$result->updated_themes = $this->get_updated_themes(wp_get_themes(), $purchased_themes);
$result->updated_themes_count = count($result->updated_themes);
return $result;
}
/**
* Upgrades theme to its latest version
*
* @since 1.0
* @access public
*
* @param string Name of the theme. If not set checks for updates for the current theme. Default ''.
* @param bool Allow API calls to be cached. Default true.
* @return object A stdClass object.
*/
public function upgrade_theme( $theme_name = '', $allow_cache = true )
{
$result = new stdClass();
$result->success = false;
if ( empty($theme_name) ) {
$theme_name = wp_get_theme();
}
$installed_theme = $this->is_theme_installed($theme_name);
if ($installed_theme == null) {
$result->errors = array("'$theme_name' theme is not installed");
return $result;
}
$purchased_themes = $this->api->wp_list_themes( $allow_cache );
$marketplace_theme_data = null;
if ( $errors = $this->api->api_errors() )
{
$result->errors = array();
foreach( $errors as $k => $v ) {
array_push( $result->errors , $v);
}
return $result;
}
foreach( $purchased_themes as $purchased ) {
if ( $this->is_matching_themes( $installed_theme, $purchased ) && $this->is_newer_version_available( $installed_theme['Version'], $purchased->version ) ) {
$marketplace_theme_data = $purchased;
break;
}
}
if ( $marketplace_theme_data == null ) {
$result->errors = array( "There is no update available for '$theme_name'" );
return $result;
}
$result->success = $this->do_upgrade_theme( $installed_theme['Title'], $marketplace_theme_data->item_id);
$result->installation_feedback = $this->installation_feedback;
return $result;
}
/**
* @since 1.0
* @access internal
*
* @return array Void.
*/
public function set_installation_message($message)
{
$this->installation_feedback[] = $message;
}
/**
* @since 1.0
* @access internal
*
* @return array Array.
*/
protected function filter_purchased_themes_by_name( $all_purchased_themes, $theme_name )
{
$result = $all_purchased_themes;
if ( empty($theme_name) )
return $result;
for ( $i = count($result) - 1; $i >= 0; $i-- ) {
$entry = $result[$i];
if ( $entry->theme_name != $theme_name )
unset($result[$i]);
}
return $result;
}
/**
* @since 1.0
* @access internal
*
* @return array Void.
*/
protected function constants()
{
define( 'ETU_MAX_EXECUTION_TIME' , 60 * 5);
}
/**
* @since 1.0
* @access internal
*
* @return array Array.
*/
protected function get_updated_themes($installed_themes, $purchased_themes)
{
$result = array();
if ( count( $purchased_themes ) <= 0 ) {
return $result;
}
foreach( $purchased_themes as $purchased )
{
foreach( $installed_themes as $installed => $installed_theme )
{
if ( $this->is_matching_themes( $installed_theme, $purchased ) && $this->is_newer_version_available( $installed_theme['Version'], $purchased->version ) )
{
$installed_theme['envato-theme'] = $purchased;
array_push($result, $installed_theme);
}
}
}
return $result;
}
/**
* @since 1.0
* @access internal
*
* @return array Boolean.
*/
protected function is_matching_themes($installed_theme, $purchased_theme)
{
return $installed_theme['Title'] == $purchased_theme->theme_name AND $installed_theme['Author Name'] == $purchased_theme->author_name;
}
protected function is_newer_version_available($installed_vesion, $latest_version)
{
return version_compare($installed_vesion, $latest_version, '<');
}
protected function is_theme_installed($theme_name)
{
$installed_themes = wp_get_themes();
foreach($installed_themes as $entry)
{
if (strcmp($entry['Name'], $theme_name) == 0) {
return $entry;
}
}
return null;
}
/**
* @since 1.0
* @access internal
*
* @return array Boolean.
*/
protected function do_upgrade_theme( $installed_theme_name, $marketplace_theme_id )
{
$result = false;
$callback = array( &$this , '_http_request_args' );
add_filter( 'http_request_args', $callback, 10, 1 );
$result = $this->upgrade( $installed_theme_name, $this->api->wp_download( $marketplace_theme_id ) );
remove_filter( 'http_request_args', $callback );
return $result;
}
/**
* @since 1.0
* @access internal
*
* @return array Array.
*/
public function _http_request_args($r)
{
if ((int)ini_get("max_execution_time") < ETU_MAX_EXECUTION_TIME)
{
set_time_limit( ETU_MAX_EXECUTION_TIME );
}
$r['timeout'] = ETU_MAX_EXECUTION_TIME;
return $r;
}
/**
* @since 1.0
* @access internal
*
* @return array Void.
*/
public function upgrade_strings() {
parent::upgrade_strings();
$this->strings['downloading_package'] = __( 'Downloading upgrade package from the Envato API…', 'color-theme-framework' );
}
/**
* @since 1.0
* @access internal
*
* @return array Void.
*/
public function install_strings() {
parent::install_strings();
$this->strings['downloading_package'] = __( 'Downloading install package from the Envato API…', 'color-theme-framework' );
}
/**
* @since 1.0
* @access internal
*
* @return array Boolean.
*/
public function upgrade( $theme, $package ) {
$this->init();
$this->upgrade_strings();
$options = array(
'package' => $package,
'destination' => WP_CONTENT_DIR . '/themes',
'clear_destination' => true,
'clear_working' => true,
'hook_extra' => array(
'theme' => $theme
)
);
$this->run( $options );
if ( ! $this->result || is_wp_error($this->result) )
return $this->result;
return true;
}
}
/**
* Envato Theme Installer Skin class to extend the WordPress Theme_Installer_Skin class.
*
* @package Envato WordPress Theme Upgrader Library
* @author Arman Mirkazemi
* @since 1.0
*/
class Envato_Theme_Installer_Skin extends Theme_Installer_Skin {
protected $envato_theme_updater;
function __construct($envato_theme_updater)
{
parent::__construct();
$this->envato_theme_updater = $envato_theme_updater;
}
/**
* @since 1.0
* @access internal
*
* @return array Void.
*/
function feedback($string)
{
if ( isset( $this->upgrader->strings[$string] ) )
$string = $this->upgrader->strings[$string];
if ( strpos($string, '%') !== false ) {
$args = func_get_args();
$args = array_splice($args, 1);
if ( !empty($args) )
$string = vsprintf($string, $args);
}
if ( empty($string) )
return;
$this->envato_theme_updater->set_installation_message($string);
}
/**
* @since 1.0
* @access internal
*
* @return array Void.
*/
function header(){}
/**
* @since 1.0
* @access internal
*
* @return array Void.
*/
function footer(){}
}
}
| RomainGoncalves/discover-lombok | wp-content/themes/newstrick/envato-wordpress-toolkit-library/class-envato-wordpress-theme-upgrader.php | PHP | gpl-2.0 | 12,262 |
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace GetHabitsAspNet5App.Models.Identity
{
public class GetHabitsIdentity: IdentityDbContext<GetHabitsUser>
{
}
}
| boyarincev/GetHabitsAspNet5 | src/GetHabitsAspNet5App/Models/Identity/GetHabitsIdentity.cs | C# | gpl-2.0 | 281 |
"""
This module instructs the setuptools to setpup this package properly
:copyright: (c) 2016 by Mehdy Khoshnoody.
:license: GPLv3, see LICENSE for more details.
"""
import os
from distutils.core import setup
setup(
name='pyeez',
version='0.1.0',
packages=['pyeez'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
keywords='terminal console',
url='https://github.com/mehdy/pyeez',
license='GPLv3',
author='Mehdy Khoshnoody',
author_email='me@mehdy.net',
description='A micro-framework to create console-based applications like'
'htop, vim and etc'
)
| mehdy/pyeez | setup.py | Python | gpl-2.0 | 1,167 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DoWorkGym.Service")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1194fc48-7428-4160-9d00-75cd74979bc4")]
| mmo80/DoWorkGym | Source/DoWorkGym.Service/Properties/AssemblyInfo.cs | C# | gpl-2.0 | 758 |
/* This file is part of OpenMalaria.
*
* Copyright (C) 2005-2014 Swiss Tropical and Public Health Institute
* Copyright (C) 2005-2014 Liverpool School Of Tropical Medicine
*
* OpenMalaria is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// Note: this file is included by exactly one source (Interventions.cpp)
// and contains definitions as well as declarations.
// The includes here are more for documentation than required.
#include "interventions/Interfaces.hpp"
#include "interventions/InterventionManager.hpp"
#include "util/ModelOptions.h"
#include "Clinical/ESCaseManagement.h"
#include "Clinical/ImmediateOutcomes.h"
#include "Host/Human.h"
#include "Transmission/TransmissionModel.h"
#include "Host/WithinHost/Diagnostic.h"
#include "PkPd/LSTMTreatments.h"
#include "mon/info.h"
#include "util/random.h"
#include <schema/healthSystem.h>
#include <schema/interventions.h>
namespace OM { namespace interventions {
using Host::Human;
using WithinHost::Diagnostic;
using WithinHost::diagnostics;
// ——— HumanIntervention ———
bool componentCmp(const HumanInterventionComponent *a, const HumanInterventionComponent *b){
return a->componentType() < b->componentType();
}
HumanIntervention::HumanIntervention(
const xsd::cxx::tree::sequence<scnXml::Component>& componentList )
{
components.reserve( componentList.size() );
for( auto it = componentList.begin(), end = componentList.end(); it != end; ++it ) {
ComponentId id = InterventionManager::getComponentId( it->getId() );
const HumanInterventionComponent* component = &InterventionManager::getComponent( id );
components.push_back( component );
}
/** Sort components according to a standard order.
*
* The point of this is to make results repeatable even when users change
* the ordering of a list of intervention's components (since getting
* repeatable results out of OpenMalaria is often a headache anyway, we
* might as well at least remove this hurdle).
*
* Note that when multiple interventions are deployed simultaneously, the
* order of their deployments is still dependent on the order in the XML
* file. */
std::stable_sort( components.begin(), components.end(), componentCmp );
}
HumanIntervention::HumanIntervention(
const xsd::cxx::tree::sequence<scnXml::Component>& componentList,
const xsd::cxx::tree::sequence<scnXml::Condition>& conditionList )
{
components.reserve( componentList.size() );
for( auto it = componentList.begin(), end = componentList.end(); it != end; ++it ) {
ComponentId id = InterventionManager::getComponentId( it->getId() );
const HumanInterventionComponent* component = &InterventionManager::getComponent( id );
components.push_back( component );
}
/** Sort components according to a standard order.
*
* The point of this is to make results repeatable even when users change
* the ordering of a list of intervention's components (since getting
* repeatable results out of OpenMalaria is often a headache anyway, we
* might as well at least remove this hurdle).
*
* Note that when multiple interventions are deployed simultaneously, the
* order of their deployments is still dependent on the order in the XML
* file. */
std::stable_sort( components.begin(), components.end(), componentCmp );
for( auto it = conditionList.begin(), end = conditionList.end(); it != end; ++it ) {
double min = it->getMinValue().present() ? it->getMinValue().get() : -numeric_limits<double>::infinity();
double max = it->getMaxValue().present() ? it->getMaxValue().get() : numeric_limits<double>::infinity();
conditions.push_back(mon::setupCondition( it->getMeasure(), min, max, it->getInitialState() ));
}
}
HumanIntervention::HumanIntervention( const xsd::cxx::tree::sequence<scnXml::DTDeploy>& componentList ){
components.reserve( componentList.size() );
for( auto it = componentList.begin(), end = componentList.end(); it != end; ++it ) {
ComponentId id = InterventionManager::getComponentId( it->getComponent() );
const HumanInterventionComponent* component = &InterventionManager::getComponent( id );
components.push_back( component );
}
/** Sort components according to a standard order.
*
* The point of this is to make results repeatable even when users change
* the ordering of a list of intervention's components (since getting
* repeatable results out of OpenMalaria is often a headache anyway, we
* might as well at least remove this hurdle).
*
* Note that when multiple interventions are deployed simultaneously, the
* order of their deployments is still dependent on the order in the XML
* file. */
std::stable_sort( components.begin(), components.end(), componentCmp );
}
void HumanIntervention::deploy( Human& human, mon::Deploy::Method method,
VaccineLimits vaccLimits ) const
{
for( size_t cond : conditions ){
// Abort deployment if any condition is false.
if( !mon::checkCondition(cond) ) return;
}
for( auto it = components.begin(); it != components.end(); ++it ) {
const interventions::HumanInterventionComponent& component = **it;
// we must report first, since it can change cohort and sub-population
// which may affect what deployment does (at least in the case of reporting deployments)
human.reportDeployment( component.id(), component.duration() );
component.deploy( human, method, vaccLimits );
}
}
void HumanIntervention::print_details( std::ostream& out )const{
out << "human:";
for( auto it = components.begin(); it != components.end(); ++it ){
out << '\t' << (*it)->id().id;
}
}
// ——— Utilities ———
TriggeredDeployments::TriggeredDeployments(const scnXml::TriggeredDeployments& elt){
lists.reserve( elt.getDeploy().size() );
for( auto it = elt.getDeploy().begin(), end = elt.getDeploy().end(); it != end; ++it ) {
lists.push_back( SubList( *it ) );
}
}
void TriggeredDeployments::deploy(Human& human,
mon::Deploy::Method method, VaccineLimits vaccLimits) const
{
for( auto it = lists.begin(); it != lists.end(); ++it ){
it->deploy( human, method, vaccLimits );
}
}
TriggeredDeployments::SubList::SubList( const scnXml::TriggeredDeployments::DeployType& elt ) :
HumanIntervention( elt.getComponent() ),
minAge( sim::fromYearsN( elt.getMinAge() ) ),
maxAge( sim::future() ),
coverage( elt.getP() )
{
if( elt.getMaxAge().present() )
maxAge = sim::fromYearsN( elt.getMaxAge().get() );
if( minAge < sim::zero() || maxAge < minAge ){
throw util::xml_scenario_error("triggered intervention must have 0 <= minAge <= maxAge");
}
if( coverage < 0.0 || coverage > 1.0 ){
throw util::xml_scenario_error( "triggered intervention must have 0 <= coverage <= 1" );
}
// Zero coverage: optimise
if( coverage <= 0.0 || minAge >= maxAge ) components.clear();
}
void TriggeredDeployments::SubList::deploy( Host::Human& human,
mon::Deploy::Method method, VaccineLimits vaccLimits )const
{
// This may be used within a time step; in that case we use human age at
// the beginning of the step since this gives the expected result with age
// limits of 0 to 1 time step.
//TODO: why does the above contradict what we do? Is this due to a date being shifted later?
SimTime age = human.age(sim::nowOrTs1());
if( age >= minAge && age < maxAge ){
if( coverage >= 1.0 || human.rng().bernoulli( coverage ) ){
HumanIntervention::deploy( human, method, vaccLimits );
}
}
}
// ——— Derivatives of HumanInterventionComponent ———
class RecruitmentOnlyComponent : public HumanInterventionComponent {
public:
RecruitmentOnlyComponent( ComponentId id ) :
HumanInterventionComponent(id)
{}
virtual ~RecruitmentOnlyComponent() {}
/// Reports to monitoring, nothing else
virtual void deploy( Host::Human& human, mon::Deploy::Method method, VaccineLimits ) const{
mon::reportEventMHD( mon::MHD_RECRUIT, human, method );
}
virtual Component::Type componentType() const{
return Component::RECRUIT_ONLY;
}
virtual void print_details( std::ostream& out )const{
out << id().id << "\tRecruit only";
}
};
class ScreenComponent : public HumanInterventionComponent {
public:
ScreenComponent( ComponentId id, const scnXml::Screen& elt ) :
HumanInterventionComponent(id),
diagnostic(diagnostics::get(elt.getDiagnostic())),
positive( elt.getPositive() ),
negative( elt.getNegative() )
{}
void deploy( Human& human, mon::Deploy::Method method, VaccineLimits vaccLimits ) const{
mon::reportEventMHD( mon::MHD_SCREEN, human, method );
if( human.withinHostModel->diagnosticResult(human.rng(), diagnostic) ){
positive.deploy( human, method, vaccLimits );
}else{
negative.deploy( human, method, vaccLimits );
}
}
virtual Component::Type componentType() const{ return Component::SCREEN; }
virtual void print_details( std::ostream& out )const{
out << id().id << "\tScreen";
}
private:
const Diagnostic& diagnostic;
HumanIntervention positive, negative;
};
/// Simple treatment: no PK/PD, just remove parasites
class TreatSimpleComponent : public HumanInterventionComponent {
public:
TreatSimpleComponent( ComponentId id, const scnXml::DTTreatSimple& elt ) :
HumanInterventionComponent(id)
{
//NOTE: this code is currently identical to that in CMDTTreatSimple
try{
SimTime durL = UnitParse::readShortDuration( elt.getDurationLiver(), UnitParse::NONE ),
durB = UnitParse::readShortDuration( elt.getDurationBlood(), UnitParse::NONE );
SimTime neg1 = -sim::oneTS();
if( durL < neg1 || durB < neg1 ){
throw util::xml_scenario_error( "treatSimple: cannot have durationBlood or durationLiver less than -1" );
}
if( util::ModelOptions::option( util::VIVAX_SIMPLE_MODEL ) ){
if( durL != sim::zero() || durB != neg1 )
throw util::unimplemented_exception( "vivax model only supports timestepsLiver=0, timestepsBlood=-1" );
// Actually, the model ignores these parameters; we just don't want somebody thinking it doesn't.
}
timeLiver = durL;
timeBlood = durB;
}catch( const util::format_error& e ){
throw util::xml_scenario_error( string("treatSimple: ").append(e.message()) );
}
}
void deploy( Human& human, mon::Deploy::Method method, VaccineLimits ) const{
mon::reportEventMHD( mon::MHD_TREAT, human, method );
human.withinHostModel->treatSimple( human, timeLiver, timeBlood );
}
virtual Component::Type componentType() const{ return Component::TREAT_SIMPLE; }
virtual void print_details( std::ostream& out )const{
out << id().id << "\ttreatSimple";
}
private:
SimTime timeLiver, timeBlood;
};
//NOTE: this is similar to CMDTTreatPKPD, but supporting only a single "treatment"
class TreatPKPDComponent : public HumanInterventionComponent {
public:
TreatPKPDComponent( ComponentId id, const scnXml::DTTreatPKPD& elt ) :
HumanInterventionComponent(id),
schedule(PkPd::LSTMTreatments::findSchedule(elt.getSchedule())),
dosage(PkPd::LSTMTreatments::findDosages(elt.getDosage())),
delay_d(elt.getDelay_h() / 24.0 /* convert to days */)
{
}
void deploy( Human& human, mon::Deploy::Method method, VaccineLimits ) const{
mon::reportEventMHD( mon::MHD_TREAT, human, method );
double age = sim::inYears(human.age(sim::nowOrTs1()));
human.withinHostModel->treatPkPd( schedule, dosage, age, delay_d );
}
virtual Component::Type componentType() const{ return Component::TREAT_PKPD; }
virtual void print_details( std::ostream& out )const{
out << id().id << "\ttreatPKPD";
}
private:
size_t schedule; // index of the schedule
size_t dosage; // name of the dosage table
double delay_d; // delay in days
};
class DecisionTreeComponent : public HumanInterventionComponent {
public:
DecisionTreeComponent( ComponentId id, const scnXml::DecisionTree& elt ) :
HumanInterventionComponent(id),
tree(Clinical::CMDecisionTree::create(elt, false))
{}
void deploy( Human& human, mon::Deploy::Method method, VaccineLimits )const{
Clinical::CMDTOut out = tree.exec( Clinical::CMHostData(human,
sim::inYears(human.age(sim::nowOrTs1())),
Clinical::Episode::NONE /*parameter not needed*/) );
if( out.treated ){
mon::reportEventMHD( mon::MHD_TREAT, human, method );
}
if( out.screened ){
mon::reportEventMHD( mon::MHD_SCREEN, human, method );
}
}
virtual Component::Type componentType() const{ return Component::CM_DT; }
virtual void print_details( std::ostream& out )const{
out << id().id << "\tDecision tree";
}
private:
const Clinical::CMDecisionTree& tree;
};
class ClearImmunityComponent : public HumanInterventionComponent {
public:
ClearImmunityComponent( ComponentId id ) :
HumanInterventionComponent(id) {}
void deploy( Human& human, mon::Deploy::Method method, VaccineLimits )const{
human.clearImmunity();
//NOTE: not reported
}
virtual Component::Type componentType() const{ return Component::CLEAR_IMMUNITY; }
virtual void print_details( std::ostream& out )const{
out << id().id << "\tclear immunity";
}
};
} }
| SwissTPH/openmalaria | model/interventions/HumanInterventionComponents.hpp | C++ | gpl-2.0 | 14,760 |
var searchData=
[
['y',['y',['../group___accelerometer_service.html#a58008ae111afcb60b47419541c48aa91',1,'AccelData::y()'],['../group___graphics_types.html#a94afc39fa39df567b9e78702d1f07b3e',1,'GPoint::y()']]],
['year_5funit',['YEAR_UNIT',['../group___wall_time.html#gga0423d00e0eb199de523a92031b5a1107a652f00ea2c629930a32a684f9d8c876d',1,'pebble.h']]]
];
| sdeyerle/pebble_fun | PebbleSDK-2.0-BETA7/Documentation/pebble-api-reference/search/all_79.js | JavaScript | gpl-2.0 | 360 |
package world.render;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import org.lwjgl.opengl.GL11;
import core.Renderer;
import core.Updater;
import effects.Effect;
import effects.particles.ParticleEffect;
import effects.particles.ParticleEmitter;
import item.Nametag;
import main.Main;
import main.Res;
import menu.Settings;
import render.Animator;
import render.Framebuffer;
import render.Render;
import render.VAO;
import things.Thing;
import util.Color;
import util.math.Vec;
import world.World;
import world.data.WorldData;
import world.window.BackgroundWindow;
import world.window.TerrainWindow;
import world.window.ThingWindow;
public class WorldPainter implements Updater, Renderer{
private WorldData world;
//tracking
private EffectManager effects;
private List<Thing> selected = new ArrayList<>();
//rendering
private VAO completeWindow;
private Framebuffer landscapeBuffer;
private TerrainWindow terrain;
private BackgroundWindow background;
private ThingWindow things;
//others
Animator death = new Animator(Res.death, () -> {}, false);
public WorldPainter(WorldData l, ThingWindow things, TerrainWindow landscape, BackgroundWindow background) {
this.world = l;
World.world.window = this;
this.things = things;
this.terrain = landscape;
this.background = background;
landscapeBuffer = new Framebuffer("Landscape", Main.SIZE.w, Main.SIZE.h);
this.completeWindow = Render.quadInScreen(-Main.HALFSIZE.w, Main.HALFSIZE.h, Main.HALFSIZE.w, -Main.HALFSIZE.h);
GL11.glClearColor(0, 0, 0, 0);
GL11.glClearStencil(0);
effects = new EffectManager();
addEffect(new Nametag());
l.getWeather().addEffects();
}
public Vec toWorldPos(Vec windowPos) {
windowPos.shift(-Main.HALFSIZE.w, -Main.HALFSIZE.h);
windowPos.scale(1/Settings.getDouble("ZOOM"));
windowPos.shift(-Render.offsetX, -Render.offsetY);
return windowPos;
}
public void select(Thing t) {
selected.add(t);
t.selected = true;
t.switchedSelected = true;
}
public void deselect(Thing t) {
selected.remove(t);
t.selected = false;
t.switchedSelected = true;
}
public int selectionSize() {
return selected.size();
}
public Thing getSelection(int i) {
return selected.get(i);
}
public boolean update(final double delta){
// delta *= Settings.timeScale;
effects.update(delta);
if(world.isGameOver()) {
death.update(delta);
}
return false;
}
Vec lastAvatarPos = new Vec(), avatarPos = new Vec(), offset = new Vec();
public void updateTransform(double interpolationShift) {
Render.scaleX = (float)(Settings.getDouble("ZOOM")/Main.HALFSIZE.w);
Render.scaleY = (float)(Settings.getDouble("ZOOM")/Main.HALFSIZE.h);
lastAvatarPos.set(Main.world.engine.lastAvatarPosition).set(Main.world.avatar.pos);
avatarPos.set(Main.world.avatar.pos);
offset.set(avatarPos).shift(avatarPos.shift(lastAvatarPos, -1), interpolationShift);
Render.offsetX = (float)-offset.x;
Render.offsetY = (float)-offset.y;
}
public void draw(double interpolationShift){
// if(Core.updatedToLong) {
// for(int i = 0; i < Main.world.engine.timeIndex; i++) {
// System.out.println(Main.world.engine.lastTimes[0][i] + " " + Main.world.engine.lastTimes[1][i] + " " + Main.world.engine.lastTimes[2][i] + " " + Main.world.engine.lastTimes[3][i]);
// }
// }
// Main.world.engine.timeIndex = 0;
updateTransform(interpolationShift);
background.renderBackground();
landscapeBuffer.bind();
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
terrain.renderLandscape();
Framebuffer.bindNone();
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glAlphaFunc(GL11.GL_GREATER, 0.4f);
GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ZERO);
Render.drawSingleQuad(completeWindow, Color.WHITE, landscapeBuffer.getTex(), 0, 0, 1f/Main.HALFSIZE.w, 1f/Main.HALFSIZE.h, true, 0);
things.renderThings();
GL11.glDisable(GL11.GL_ALPHA_TEST);
GL11.glDisable(GL11.GL_DEPTH_TEST);
terrain.renderWater();
//Outlines of living things
things.renderOutlines();
//auras
// renderAuras();
//draw the darkness which is crouching out of the earth
if(Settings.getBoolean("DARKNESS")){
background.renderDarkness();
}
//
//draw bounding boxes of all things and their anchor points
if(Settings.getBoolean("SHOW_BOUNDING_BOX")){
things.renderBoundingBoxes();
}
//effects
ParticleEmitter.offset.set(Render.offsetX, Render.offsetY);
ParticleEffect.wind.set((Main.input.getMousePos(Main.WINDOW).x - Main.HALFSIZE.w)*60f/Main.HALFSIZE.w, 0);
effects.forEach(Effect::render);
//quests
world.forEachQuest((aq) -> aq.render());
if(world.isGameOver()) {
Render.drawSingleQuad(completeWindow, Color.BLACK, null, 0, 0, 1f/Main.HALFSIZE.w, 1f/Main.HALFSIZE.h, false, 0);
GL11.glEnable(GL11.GL_ALPHA_TEST);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
death.bindTex();
death.quad.render(new Vec(), Render.scaleX);
GL11.glDisable(GL11.GL_ALPHA_TEST);
}
}
public void forEachEffect(Consumer<Effect> cons) {
effects.forEach(cons);
}
public void addEffect(Effect effect){
effects.addEffect(effect);
}
public void removeEffect(Effect effect) {
effects.removeEffect(effect);
}
public static String getDayTime() {
return "evening";
}
public String debugName() {
return "World Window";
}
}
| Marghytis/SarahsWorld | SarahsWorld/src/world/render/WorldPainter.java | Java | gpl-2.0 | 5,672 |
/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest09197")
public class BenchmarkTest09197 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = "";
java.util.Enumeration<String> headers = request.getHeaders("foo");
if (headers.hasMoreElements()) {
param = headers.nextElement(); // just grab first element
}
String bar = new Test().doSomething(param);
java.io.FileOutputStream fos = new java.io.FileOutputStream(org.owasp.benchmark.helpers.Utils.testfileDir + bar, false);
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
// Chain a bunch of propagators in sequence
String a92930 = param; //assign
StringBuilder b92930 = new StringBuilder(a92930); // stick in stringbuilder
b92930.append(" SafeStuff"); // append some safe content
b92930.replace(b92930.length()-"Chars".length(),b92930.length(),"Chars"); //replace some of the end content
java.util.HashMap<String,Object> map92930 = new java.util.HashMap<String,Object>();
map92930.put("key92930", b92930.toString()); // put in a collection
String c92930 = (String)map92930.get("key92930"); // get it back out
String d92930 = c92930.substring(0,c92930.length()-1); // extract most of it
String e92930 = new String( new sun.misc.BASE64Decoder().decodeBuffer(
new sun.misc.BASE64Encoder().encode( d92930.getBytes() ) )); // B64 encode and decode it
String f92930 = e92930.split(" ")[0]; // split it on a space
org.owasp.benchmark.helpers.ThingInterface thing = org.owasp.benchmark.helpers.ThingFactory.createThing();
String bar = thing.doSomething(f92930); // reflection
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest09197.java | Java | gpl-2.0 | 3,130 |
/*************************************************************************
> File Name: random.cpp
> Author: qiaoyihan
> Email: yihqiao@126
> Created Time: Sun May 15 11:20:00 2016
************************************************************************/
#include<iostream>
#include<string>
#include<cstdlib>
#include<ctime>
using std::cout;
using std::endl;
using std::string;
int main()
{
std::srand(std::time(0)); // use current time as seed for random generator
cout << std::rand() % 3 << endl;
return 0;
}
| Evanqiao/LeetCode-qyh | 53_MaximumSubarray/random.cpp | C++ | gpl-2.0 | 536 |
// Copyright (c) 2015 Riccardo Miccini. All rights reserved.
#include "XBeeHandler.h"
#include "XBee.h"
#include <SoftwareSerial.h>
uint8_t payload[] = {0, 0};
uint8_t cmdNI[] = {'N', 'I'};
XBeeHandler::XBeeHandler(uint8_t statusLed, uint8_t errorLed, uint8_t dataLed, uint8_t rxPin, uint8_t txPin) {
setDebugLeds(statusLed, errorLed, dataLed);
setDebugSerial(rxPin, txPin);
selectDebug(DEBUG_BOTH);
init();
}
XBeeHandler::XBeeHandler(uint8_t statusLed, uint8_t errorLed, uint8_t dataLed) {
setDebugLeds(statusLed, errorLed, dataLed);
detachDebugLSerial();
selectDebug(DEBUG_LEDS);
init();
}
XBeeHandler::XBeeHandler(uint8_t rxPin, uint8_t txPin) {
detachDebugLeds();
setDebugSerial(rxPin, txPin);
selectDebug(DEBUG_SERIAL);
init();
}
XBeeHandler::XBeeHandler() {
detachDebugLeds();
detachDebugLSerial();
selectDebug(DEBUG_NONE);
init();
}
XBeeHandler::~XBeeHandler() {
delete _serial;
delete[] _data;
}
void XBeeHandler::selectDebug(DebugType type) {
switch (type) {
case DEBUG_NONE: _debugSerial = false; _debugLeds = false; break;
case DEBUG_SERIAL: _debugSerial = true; _debugLeds = false; break;
case DEBUG_LEDS: _debugSerial = false; _debugLeds = true; break;
case DEBUG_BOTH: _debugSerial = true; _debugLeds = true; break;
default: break;
}
}
void XBeeHandler::setDebugSerial(uint8_t rxPin, uint8_t txPin) {
_serial = new SoftwareSerial(rxPin, txPin);
_serial->begin(9600);
_serial->println("Serial debug is ON!");
_debugSerial = true;
}
void XBeeHandler::setDebugLeds(uint8_t statusLed, uint8_t errorLed, uint8_t dataLed) {
_statusLed = statusLed;
_errorLed = errorLed;
_dataLed = dataLed;
_debugLeds = true;
}
void XBeeHandler::detachDebugLeds() {
_statusLed = 0;
_errorLed = 0;
_dataLed = 0;
_debugLeds = false;
}
void XBeeHandler::detachDebugLSerial() {
if (_debugSerial) {delete _serial;}
_debugSerial = false;
}
void XBeeHandler::begin() {
if (_debugLeds) {
pinMode(_statusLed, OUTPUT);
pinMode(_errorLed, OUTPUT);
pinMode(_dataLed, OUTPUT);
flashLed(STATUSLED, 3, 50);
}
Serial.begin(9600);
_xbee.begin(Serial);
}
void XBeeHandler::update() {
if (CheckPacketsOld()) {
HandleResponse(_response);
}
}
uint8_t XBeeHandler::discover(XBeeNode list[], uint8_t maxNodes) {
uint8_t cmdNT[] = {'N', 'T'};
uint8_t cmdND[] = {'N', 'D'};
uint16_t timeOut = 0;
uint8_t numNodes = 0;
if (_debugSerial) _serial->println("### Discovering nodes..");
if (_debugSerial) _serial->println("# Sending NT request..");
_atCommandReq.setCommand(cmdNT);
_xbee.send(_atCommandReq);
while (!CheckPackets(5000)) {}
HandleResponse(_response);
timeOut = _data[0]*100;
if (_debugSerial) _serial->print("# Timeout: ");
if (_debugSerial) _serial->println(timeOut, DEC);
if (_debugSerial) _serial->println("# Sending ND request..");
_atCommandReq.setCommand(cmdND);
_xbee.send(_atCommandReq);
uint16_t startTime = millis();
uint16_t endTime = 0;
while ((endTime-startTime) <= 5000) { // timeOut
if (CheckPacketsOld()) {
HandleResponse(_response);
for (int i = 0; i < _dataLen; i++) {
if (_debugSerial) _serial->print(_data[i], HEX);
if (_debugSerial) _serial->print(" ");
}
if (_debugSerial) _serial->println();
}
}
return numNodes;
}
boolean XBeeHandler::CheckPacketsOld() {
boolean packetFound = false;
_xbee.readPacket();
_response = _xbee.getResponse();
if (_response.isAvailable()) {
packetFound = true;
} else if (_response.isError()) {
if (_debugLeds) flashLed(ERRORLED, 1, 25);
if (_debugSerial) _serial->print("::CheckPackets - Command returned error code: ");
if (_debugSerial) _serial->println(_response.getErrorCode(), HEX);
}
return packetFound;
}
boolean XBeeHandler::CheckPackets(uint16_t time) {
boolean packetFound = false;
if (_xbee.readPacket(time)) {
_response = _xbee.getResponse();
packetFound = true;
} else {
if (_response.isError()) {
if (_debugLeds) flashLed(ERRORLED, 1, 25);
if (_debugSerial) _serial->print("::CheckPackets - Command returned error code: ");
if (_debugSerial) _serial->println(_response.getErrorCode(), HEX);
} else {
if (_debugLeds) flashLed(ERRORLED, 1, 25);
if (_debugSerial) _serial->println("::CheckPackets - No response from the module.");
}
}
return packetFound;
}
void XBeeHandler::HandleZBRxResponse(XBeeResponse &resp) {
resp.getZBRxResponse(_zbRxResp);
if (_zbRxResp.getOption() == ZB_PACKET_ACKNOWLEDGED) {
flashLed(STATUSLED, 10, 10);
} else {
flashLed(ERRORLED, 2, 20);
}
}
void XBeeHandler::HandleModemStatusResponse(XBeeResponse &resp) {
resp.getModemStatusResponse(_modemStatusResp);
if (_modemStatusResp.getStatus() == ASSOCIATED) {
flashLed(STATUSLED, 10, 10);
} else if (_modemStatusResp.getStatus() == DISASSOCIATED) {
flashLed(ERRORLED, 10, 10);
} else {
flashLed(STATUSLED, 5, 10);
}
}
void XBeeHandler::HandleRemoteAtCommandResponse(XBeeResponse &resp) {
resp.getRemoteAtCommandResponse(_remoteAtCommandResp);
if (_remoteAtCommandResp.isOk()) {
flashLed(STATUSLED, 10, 10);
if (_remoteAtCommandResp.getValueLength() > 0) {
delete[] _data;
_data = _remoteAtCommandResp.getValue();
_dataLen = _remoteAtCommandResp.getValueLength();
_dataEmpty = false;
// for (int i = 0; i < _remoteAtCommandResp.getValueLength(); i++) {
// _serial->print(static_cast<char>(_remoteAtCommandResp.getValue()[i]));
// }
// _serial->println("");
}
} else {
if (_debugLeds) flashLed(ERRORLED, 1, 25);
if (_debugSerial) _serial->print("::HandleRemoteAtCommandResponse - Command returned error code: ");
if (_debugSerial) _serial->println(_remoteAtCommandResp.getStatus(), HEX);
}
}
void XBeeHandler::HandleAtCommandResponse(XBeeResponse &resp) {
resp.getAtCommandResponse(_atCommandResp);
if (_atCommandResp.isOk()) {
flashLed(STATUSLED, 10, 10);
if (_atCommandResp.getValueLength() > 0) {
delete[] _data;
_data = _atCommandResp.getValue();
_dataLen = _atCommandResp.getValueLength();
_dataEmpty = false;
// for (int i = 0; i < _atCommandResp.getValueLength(); i++) {
// _serial->print(static_cast<char>(_atCommandResp.getValue()[i]));
// }
// _serial->println("");
}
} else {
if (_debugLeds) flashLed(ERRORLED, 1, 25);
if (_debugSerial) _serial->print("::HandleAtCommandResponse - Command returned error code: ");
if (_debugSerial) _serial->println(_atCommandResp.getStatus(), HEX);
}
}
void XBeeHandler::HandleUnknown(XBeeResponse &resp) {
if (_debugLeds) flashLed(ERRORLED, 1, 25);
if (_debugSerial) _serial->print("::HandleUnknown - Unknown ApiID: 0x");
if (_debugSerial) _serial->println(resp.getApiId(), HEX);
}
void XBeeHandler::HandleResponse(XBeeResponse &resp) {
uint8_t apiId = resp.getApiId();
switch (apiId) {
case ZB_RX_RESPONSE: HandleZBRxResponse(resp); break;
case MODEM_STATUS_RESPONSE: HandleModemStatusResponse(resp); break;
case REMOTE_AT_COMMAND_RESPONSE: HandleRemoteAtCommandResponse(resp); break;
case AT_COMMAND_RESPONSE: HandleAtCommandResponse(resp); break;
default: break;
}
}
void XBeeHandler::flashLed(LedType type, int times, int wait) {
uint8_t types[] = {_statusLed, _dataLed, _errorLed};
uint8_t pin = types[type];
for (int i = 0; i < times; i++) {
digitalWrite(pin, HIGH);
delay(wait);
digitalWrite(pin, LOW);
if (i + 1 < times) {
delay(wait);
}
}
}
void XBeeHandler::init() {
_xbee = XBee();
_addr = RemoteAtCommandRequest::broadcastAddress64;
_zbTxReq = ZBTxRequest();
_atCommandReq = AtCommandRequest();
_remoteAtCommandReq = RemoteAtCommandRequest();
_response = XBeeResponse();
_zbTxStatusResp = ZBTxStatusResponse();
_zbRxResp = ZBRxResponse();
_modemStatusResp = ModemStatusResponse();
_atCommandResp = AtCommandResponse();
_remoteAtCommandResp = RemoteAtCommandResponse();
_data = new uint8_t[MAX_PAYLOAD];
}
| miccio-dk/SustainView | Arduino/xbee2web/XBeeHandler.cpp | C++ | gpl-2.0 | 8,225 |
/**
* Created by reuben on 10/11/14.
*/
"use strict";
angular.module('crookedFireApp.filters', []).filter('tabsFilter', function () {
return function (tabs, roles) {
var arr = [];
//load public tabs
for (var i = 0; i < tabs.length; i++) {
for (var j = 0; j < tabs[i].roles.length; j++) {
if (tabs[i].roles[j] === '') {
arr.push(tabs[i]);
j = tabs[i].roles.length;
}
if (roles && roles[tabs[i].roles[j]]) {
arr.push(tabs[i]);
j = tabs[i].roles.length;
}
}
}
return arr;
};
});
| Gaurav2Github/MyCrookedFireBase | app/scripts/filters/navigation.fltr.js | JavaScript | gpl-2.0 | 698 |
/*
First Missing Positive
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
*/
#include <iostream>
using namespace std;
class Solution
{
public:
int firstMissingPositive(int A[], int n)
{
// swap A[i] to the appropriate position in the array if sorted
// ignore zero and negative numbers
for (int i = 0; i < n; i++) {
// A[i] != i + 1 means A[i] is not in the right position
// as array start from 0, so A[0] = 1
// A[i] != A[A[i] - 1], this is for duplicate numbers
// if it is in the right place, exit while
while (A[i] > 0 && A[i] <= n && A[i] != i + 1 && A[i] != A[A[i] - 1]) {
swap(A[i], A[A[i] - 1]);
}
}
// find the first miss match: A[i] != i + 1
int i;
for (i = 0; i < n; i++) {
if (A[i] != i + 1)
break;
}
return i + 1;
}
};
int main(int argc, char *argv[])
{
Solution sol;
int a1[] = { 1, 2, 0 };
int a2[] = { 3, 4, -1, 1 };
int a3[] = { 1, 1 }; // bug, duplicate numbers
cout << sol.firstMissingPositive(a1, sizeof(a1) / sizeof(int)) << endl;
cout << sol.firstMissingPositive(a2, sizeof(a2) / sizeof(int)) << endl;
cout << sol.firstMissingPositive(a3, sizeof(a3) / sizeof(int)) << endl;
return 0;
}
| wjin/algorithm | leetcode/first_missing_positive.cpp | C++ | gpl-2.0 | 1,515 |
/*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.nodes.graphbuilderconf;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Method;
import org.graalvm.compiler.debug.GraalError;
import org.graalvm.compiler.nodes.Invoke;
import org.graalvm.compiler.nodes.ValueNode;
import org.graalvm.compiler.nodes.type.StampTool;
import jdk.vm.ci.meta.MetaAccessProvider;
import jdk.vm.ci.meta.ResolvedJavaMethod;
/**
* Plugin for handling a specific method invocation.
*/
public interface InvocationPlugin extends GraphBuilderPlugin {
/**
* The receiver in a non-static method. The class literal for this interface must be used with
* {@link InvocationPlugins#put(InvocationPlugin, boolean, boolean, boolean, Class, String, Class...)}
* to denote the receiver argument for such a non-static method.
*/
public interface Receiver {
/**
* Gets the receiver value, null checking it first if necessary.
*
* @return the receiver value with a {@linkplain StampTool#isPointerNonNull(ValueNode)
* non-null} stamp
*/
default ValueNode get() {
return get(true);
}
/**
* Gets the receiver value, optionally null checking it first if necessary.
*/
ValueNode get(boolean performNullCheck);
/**
* Determines if the receiver is constant.
*/
default boolean isConstant() {
return false;
}
}
/**
* Determines if this plugin is for a method with a polymorphic signature (e.g.
* {@link MethodHandle#invokeExact(Object...)}).
*/
default boolean isSignaturePolymorphic() {
return false;
}
/**
* Determines if this plugin can only be used when inlining the method is it associated with.
* That is, this plugin cannot be used when the associated method is the compilation root.
*/
default boolean inlineOnly() {
return isSignaturePolymorphic();
}
/**
* Handles invocation of a signature polymorphic method.
*
* @param receiver access to the receiver, {@code null} if {@code targetMethod} is static
* @param argsIncludingReceiver all arguments to the invocation include the raw receiver in
* position 0 if {@code targetMethod} is not static
* @see #execute
*/
default boolean applyPolymorphic(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode... argsIncludingReceiver) {
return defaultHandler(b, targetMethod, receiver, argsIncludingReceiver);
}
/**
* @see #execute
*/
default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver) {
return defaultHandler(b, targetMethod, receiver);
}
/**
* @see #execute
*/
default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode arg) {
return defaultHandler(b, targetMethod, receiver, arg);
}
/**
* @see #execute
*/
default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode arg1, ValueNode arg2) {
return defaultHandler(b, targetMethod, receiver, arg1, arg2);
}
/**
* @see #execute
*/
default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode arg1, ValueNode arg2, ValueNode arg3) {
return defaultHandler(b, targetMethod, receiver, arg1, arg2, arg3);
}
/**
* @see #execute
*/
default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode arg1, ValueNode arg2, ValueNode arg3, ValueNode arg4) {
return defaultHandler(b, targetMethod, receiver, arg1, arg2, arg3, arg4);
}
/**
* @see #execute
*/
default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode arg1, ValueNode arg2, ValueNode arg3, ValueNode arg4, ValueNode arg5) {
return defaultHandler(b, targetMethod, receiver, arg1, arg2, arg3, arg4, arg5);
}
/**
* @see #execute
*/
default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode arg1, ValueNode arg2, ValueNode arg3, ValueNode arg4, ValueNode arg5,
ValueNode arg6) {
return defaultHandler(b, targetMethod, receiver, arg1, arg2, arg3, arg4, arg5, arg6);
}
/**
* @see #execute
*/
default boolean apply(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode arg1, ValueNode arg2, ValueNode arg3, ValueNode arg4, ValueNode arg5,
ValueNode arg6, ValueNode arg7) {
return defaultHandler(b, targetMethod, receiver, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
}
/**
* Executes this plugin against a set of invocation arguments.
*
* The default implementation in {@link InvocationPlugin} dispatches to the {@code apply(...)}
* method that matches the number of arguments or to {@link #applyPolymorphic} if {@code plugin}
* is {@linkplain #isSignaturePolymorphic() signature polymorphic}.
*
* @param targetMethod the method for which this plugin is being applied
* @param receiver access to the receiver, {@code null} if {@code targetMethod} is static
* @param argsIncludingReceiver all arguments to the invocation include the receiver in position
* 0 if {@code targetMethod} is not static
* @return {@code true} if this plugin handled the invocation of {@code targetMethod}
* {@code false} if the graph builder should process the invoke further (e.g., by
* inlining it or creating an {@link Invoke} node). A plugin that does not handle an
* invocation must not modify the graph being constructed.
*/
default boolean execute(GraphBuilderContext b, ResolvedJavaMethod targetMethod, InvocationPlugin.Receiver receiver, ValueNode[] argsIncludingReceiver) {
if (isSignaturePolymorphic()) {
return applyPolymorphic(b, targetMethod, receiver, argsIncludingReceiver);
} else if (receiver != null) {
assert !targetMethod.isStatic();
assert argsIncludingReceiver.length > 0;
if (argsIncludingReceiver.length == 1) {
return apply(b, targetMethod, receiver);
} else if (argsIncludingReceiver.length == 2) {
return apply(b, targetMethod, receiver, argsIncludingReceiver[1]);
} else if (argsIncludingReceiver.length == 3) {
return apply(b, targetMethod, receiver, argsIncludingReceiver[1], argsIncludingReceiver[2]);
} else if (argsIncludingReceiver.length == 4) {
return apply(b, targetMethod, receiver, argsIncludingReceiver[1], argsIncludingReceiver[2], argsIncludingReceiver[3]);
} else if (argsIncludingReceiver.length == 5) {
return apply(b, targetMethod, receiver, argsIncludingReceiver[1], argsIncludingReceiver[2], argsIncludingReceiver[3], argsIncludingReceiver[4]);
} else {
return defaultHandler(b, targetMethod, receiver, argsIncludingReceiver);
}
} else {
assert targetMethod.isStatic();
if (argsIncludingReceiver.length == 0) {
return apply(b, targetMethod, null);
} else if (argsIncludingReceiver.length == 1) {
return apply(b, targetMethod, null, argsIncludingReceiver[0]);
} else if (argsIncludingReceiver.length == 2) {
return apply(b, targetMethod, null, argsIncludingReceiver[0], argsIncludingReceiver[1]);
} else if (argsIncludingReceiver.length == 3) {
return apply(b, targetMethod, null, argsIncludingReceiver[0], argsIncludingReceiver[1], argsIncludingReceiver[2]);
} else if (argsIncludingReceiver.length == 4) {
return apply(b, targetMethod, null, argsIncludingReceiver[0], argsIncludingReceiver[1], argsIncludingReceiver[2], argsIncludingReceiver[3]);
} else if (argsIncludingReceiver.length == 5) {
return apply(b, targetMethod, null, argsIncludingReceiver[0], argsIncludingReceiver[1], argsIncludingReceiver[2], argsIncludingReceiver[3], argsIncludingReceiver[4]);
} else if (argsIncludingReceiver.length == 6) {
return apply(b, targetMethod, null, argsIncludingReceiver[0], argsIncludingReceiver[1], argsIncludingReceiver[2], argsIncludingReceiver[3], argsIncludingReceiver[4],
argsIncludingReceiver[5]);
} else if (argsIncludingReceiver.length == 7) {
return apply(b, targetMethod, null, argsIncludingReceiver[0], argsIncludingReceiver[1], argsIncludingReceiver[2], argsIncludingReceiver[3], argsIncludingReceiver[4],
argsIncludingReceiver[5], argsIncludingReceiver[6]);
} else {
return defaultHandler(b, targetMethod, receiver, argsIncludingReceiver);
}
}
}
/**
* Handles an invocation when a specific {@code apply} method is not available.
*/
default boolean defaultHandler(@SuppressWarnings("unused") GraphBuilderContext b, ResolvedJavaMethod targetMethod, @SuppressWarnings("unused") InvocationPlugin.Receiver receiver,
ValueNode... args) {
throw new GraalError("Invocation plugin for %s does not handle invocations with %d arguments", targetMethod.format("%H.%n(%p)"), args.length);
}
default StackTraceElement getApplySourceLocation(MetaAccessProvider metaAccess) {
Class<?> c = getClass();
for (Method m : c.getDeclaredMethods()) {
if (m.getName().equals("apply")) {
return metaAccess.lookupJavaMethod(m).asStackTraceElement(0);
} else if (m.getName().equals("defaultHandler")) {
return metaAccess.lookupJavaMethod(m).asStackTraceElement(0);
}
}
throw new GraalError("could not find method named \"apply\" or \"defaultHandler\" in " + c.getName());
}
}
| mcberg2016/graal-core2 | graal/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/graphbuilderconf/InvocationPlugin.java | Java | gpl-2.0 | 11,476 |
/*
* Copyright 2006-2021 The MZmine Development Team
*
* This file is part of MZmine.
*
* MZmine is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* MZmine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with MZmine; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
package io.github.mzmine.modules.dataprocessing.filter_scanfilters.mean;
import java.awt.Window;
import io.github.mzmine.modules.dataprocessing.filter_scanfilters.ScanFilterSetupDialog;
import io.github.mzmine.parameters.UserParameter;
import io.github.mzmine.parameters.impl.SimpleParameterSet;
import io.github.mzmine.parameters.parametertypes.DoubleParameter;
import io.github.mzmine.util.ExitCode;
public class MeanFilterParameters extends SimpleParameterSet {
public static final DoubleParameter oneSidedWindowLength =
new DoubleParameter("Window length", "One-sided length of the smoothing window");
public MeanFilterParameters() {
super(new UserParameter[] {oneSidedWindowLength});
}
public ExitCode showSetupDialog(boolean valueCheckRequired) {
ScanFilterSetupDialog dialog =
new ScanFilterSetupDialog(valueCheckRequired, this, MeanFilter.class);
dialog.showAndWait();
return dialog.getExitCode();
}
}
| mzmine/mzmine3 | src/main/java/io/github/mzmine/modules/dataprocessing/filter_scanfilters/mean/MeanFilterParameters.java | Java | gpl-2.0 | 1,741 |