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 |
|---|---|---|---|---|---|
/*
* Copyright (C) 2003-2006 Gabest
* http://www.gabest.org
*
* 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, 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 GNU Make; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#include "stdafx.h"
#include <math.h>
#include <time.h>
#include "DirectVobSubFilter.h"
#include "TextInputPin.h"
#include "DirectVobSubPropPage.h"
#include "VSFilter.h"
#include "systray.h"
#include "../../../DSUtil/MediaTypes.h"
#include "../../../SubPic/SimpleSubPicProviderImpl.h"
#include "../../../SubPic/PooledSubPic.h"
#include "../../../subpic/SimpleSubPicWrapper.h"
#include <initguid.h>
#include "..\..\..\..\include\moreuuids.h"
#include <d3d9.h>
#include <dxva2api.h>
#include "CAutoTiming.h"
#define MAX_SUBPIC_QUEUE_LENGTH 1
///////////////////////////////////////////////////////////////////////////
/*removeme*/
bool g_RegOK = true;//false; // doesn't work with the dvd graph builder
#include "valami.cpp"
#ifdef __DO_LOG
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
#endif
using namespace DirectVobSubXyOptions;
////////////////////////////////////////////////////////////////////////////
//
// Constructor
//
CDirectVobSubFilter::CDirectVobSubFilter(LPUNKNOWN punk, HRESULT* phr, const GUID& clsid)
: CBaseVideoFilter(NAME("CDirectVobSubFilter"), punk, phr, clsid)
, m_nSubtitleId(-1)
, m_fMSMpeg4Fix(false)
, m_fps(25)
{
DbgLog((LOG_TRACE, 3, _T("CDirectVobSubFilter::CDirectVobSubFilter")));
// and then, anywhere you need it:
AFX_MANAGE_STATE(AfxGetStaticModuleState());
ZeroObj4OSD();
theApp.WriteProfileString(ResStr(IDS_R_DEFTEXTPATHES), _T("Hint"), _T("The first three are fixed, but you can add more up to ten entries."));
theApp.WriteProfileString(ResStr(IDS_R_DEFTEXTPATHES), _T("Path0"), _T("."));
theApp.WriteProfileString(ResStr(IDS_R_DEFTEXTPATHES), _T("Path1"), _T("c:\\subtitles"));
theApp.WriteProfileString(ResStr(IDS_R_DEFTEXTPATHES), _T("Path2"), _T(".\\subtitles"));
m_fLoading = true;
m_hSystrayThread = 0;
m_tbid.hSystrayWnd = NULL;
m_tbid.graph = NULL;
m_tbid.fRunOnce = false;
m_tbid.fShowIcon = (theApp.m_AppName.Find(_T("zplayer"), 0) < 0 || !!theApp.GetProfileInt(ResStr(IDS_R_GENERAL), ResStr(IDS_RG_ENABLEZPICON), 0));
HRESULT hr = S_OK;
m_pTextInput.Add(new CTextInputPin(this, m_pLock, &m_csSubLock, &hr));
ASSERT(SUCCEEDED(hr));
m_frd.ThreadStartedEvent.Create(0, FALSE, FALSE, 0);
m_frd.EndThreadEvent.Create(0, FALSE, FALSE, 0);
m_frd.RefreshEvent.Create(0, FALSE, FALSE, 0);
CAMThread::Create();
WaitForSingleObject(m_frd.ThreadStartedEvent, INFINITE);
memset(&m_CurrentVIH2, 0, sizeof(VIDEOINFOHEADER2));
m_donot_follow_upstream_preferred_order = !m_xy_bool_opt[BOOL_FOLLOW_UPSTREAM_PREFERRED_ORDER];
m_time_alphablt = m_time_rasterization = 0;
m_video_yuv_matrix_decided_by_sub = ColorConvTable::NONE;
m_video_yuv_range_decided_by_sub = ColorConvTable::RANGE_NONE;
}
CDirectVobSubFilter::~CDirectVobSubFilter()
{
CAutoLock cAutoLock(&m_csQueueLock);
if (m_simple_provider) {
DbgLog((LOG_TRACE, 3, "~CDirectVobSubFilter::Invalidate"));
m_simple_provider->Invalidate();
}
m_simple_provider = NULL;
DeleteObj4OSD();
for (size_t i = 0; i < m_pTextInput.GetCount(); i++) {
delete m_pTextInput[i];
}
m_frd.EndThreadEvent.Set();
CAMThread::Close();
DbgLog((LOG_TRACE, 3, _T("CDirectVobSubFilter::~CDirectVobSubFilter")));
//Trace(_T("CDirectVobSubFilter::~CDirectVobSubFilter"));
//ReleaseTracer;
}
STDMETHODIMP CDirectVobSubFilter::NonDelegatingQueryInterface(REFIID riid, void** ppv)
{
CheckPointer(ppv, E_POINTER);
return
QI(IDirectVobSub)
QI(IDirectVobSub2)
QI(IDirectVobSubXy)
QI(IFilterVersion)
QI(ISpecifyPropertyPages)
QI(IAMStreamSelect)
__super::NonDelegatingQueryInterface(riid, ppv);
}
// CBaseVideoFilter
void CDirectVobSubFilter::GetOutputSize(int& w, int& h, int& arx, int& ary)
{
CSize s(w, h), os = s;
AdjustFrameSize(s);
w = s.cx;
h = s.cy;
if (w != os.cx) {
while (arx < 100) { arx *= 10, ary *= 10; }
arx = arx * w / os.cx;
}
if (h != os.cy) {
while (ary < 100) { arx *= 10, ary *= 10; }
ary = ary * h / os.cy;
}
}
HRESULT CDirectVobSubFilter::TryNotCopy(IMediaSample* pIn, const CMediaType& mt, const BITMAPINFOHEADER& bihIn)
{
CSize sub(m_w, m_h);
CSize in(bihIn.biWidth, bihIn.biHeight);
BYTE* pDataIn = NULL;
if (FAILED(pIn->GetPointer(&pDataIn)) || !pDataIn) {
return S_FALSE;
}
if (sub == in) {
m_spd.bits = pDataIn;
} else {
m_spd.bits = static_cast<BYTE*>(m_pTempPicBuff);
bool fYV12 = (mt.subtype == MEDIASUBTYPE_YV12 || mt.subtype == MEDIASUBTYPE_I420 || mt.subtype == MEDIASUBTYPE_IYUV);
bool fNV12 = (mt.subtype == MEDIASUBTYPE_NV12 || mt.subtype == MEDIASUBTYPE_NV21);
bool fP010 = (mt.subtype == MEDIASUBTYPE_P010 || mt.subtype == MEDIASUBTYPE_P016);
int bpp = fP010 ? 16 : (fYV12 || fNV12) ? 8 : bihIn.biBitCount;
DWORD black = fP010 ? 0x10001000 : (fYV12 || fNV12) ? 0x10101010 : (bihIn.biCompression == '2YUY') ? 0x80108010 : 0;
if (FAILED(Copy((BYTE*)m_pTempPicBuff, pDataIn, sub, in, bpp, mt.subtype, black))) {
return E_FAIL;
}
if (fYV12) {
BYTE* pSubV = (BYTE*)m_pTempPicBuff + (sub.cx * bpp >> 3) * sub.cy;
BYTE* pInV = pDataIn + (in.cx * bpp >> 3) * in.cy;
sub.cx >>= 1;
sub.cy >>= 1;
in.cx >>= 1;
in.cy >>= 1;
BYTE* pSubU = pSubV + (sub.cx * bpp >> 3) * sub.cy;
BYTE* pInU = pInV + (in.cx * bpp >> 3) * in.cy;
if (FAILED(Copy(pSubV, pInV, sub, in, bpp, mt.subtype, 0x80808080))) {
return E_FAIL;
}
if (FAILED(Copy(pSubU, pInU, sub, in, bpp, mt.subtype, 0x80808080))) {
return E_FAIL;
}
} else if (fP010) {
BYTE* pSubUV = (BYTE*)m_pTempPicBuff + (sub.cx * bpp >> 3) * sub.cy;
BYTE* pInUV = pDataIn + (in.cx * bpp >> 3) * in.cy;
sub.cy >>= 1;
in.cy >>= 1;
if (FAILED(Copy(pSubUV, pInUV, sub, in, bpp, mt.subtype, 0x80008000))) {
return E_FAIL;
}
} else if (fNV12) {
BYTE* pSubUV = (BYTE*)m_pTempPicBuff + (sub.cx * bpp >> 3) * sub.cy;
BYTE* pInUV = pDataIn + (in.cx * bpp >> 3) * in.cy;
sub.cy >>= 1;
in.cy >>= 1;
if (FAILED(Copy(pSubUV, pInUV, sub, in, bpp, mt.subtype, 0x80808080))) {
return E_FAIL;
}
}
}
return S_OK;
}
HRESULT CDirectVobSubFilter::Transform(IMediaSample* pIn)
{
XY_LOG_ONCE(0, _T("CDirectVobSubFilter::Transform"));
HRESULT hr;
REFERENCE_TIME rtStart, rtStop;
if (SUCCEEDED(pIn->GetTime(&rtStart, &rtStop))) {
double dRate = m_pInput->CurrentRate();
m_tPrev = m_pInput->CurrentStartTime() + dRate * rtStart;
REFERENCE_TIME rtAvgTimePerFrame = rtStop - rtStart;
if (CComQIPtr<ISubClock2> pSC2 = m_pSubClock) {
REFERENCE_TIME rt;
if (S_OK == pSC2->GetAvgTimePerFrame(&rt)) {
rtAvgTimePerFrame = rt;
}
}
m_fps = 10000000.0 / rtAvgTimePerFrame / dRate;
}
//
{
CAutoLock cAutoLock(&m_csQueueLock);
if (m_simple_provider) {
m_simple_provider->SetTime(CalcCurrentTime());
m_simple_provider->SetFPS(m_fps);
}
}
//
const CMediaType& mt = m_pInput->CurrentMediaType();
BITMAPINFOHEADER bihIn;
ExtractBIH(&mt, &bihIn);
hr = TryNotCopy(pIn, mt, bihIn);
if (hr != S_OK) {
//fix me: log error
return hr;
}
//
SubPicDesc spd = m_spd;
CComPtr<IMediaSample2> pOut;
BYTE* pDataOut = NULL;
if (FAILED(hr = GetDeliveryBuffer(spd.w, spd.h, (IMediaSample**)&pOut))
|| FAILED(hr = pOut->GetPointer(&pDataOut))) {
return hr;
}
pOut->SetTime(&rtStart, &rtStop);
pOut->SetMediaTime(NULL, NULL);
pOut->SetDiscontinuity(pIn->IsDiscontinuity() == S_OK);
pOut->SetSyncPoint(pIn->IsSyncPoint() == S_OK);
pOut->SetPreroll(pIn->IsPreroll() == S_OK);
AM_SAMPLE2_PROPERTIES inputProps;
if (SUCCEEDED(((IMediaSample2*)pIn)->GetProperties(sizeof(inputProps), (BYTE*)&inputProps))) {
AM_SAMPLE2_PROPERTIES outProps;
if (SUCCEEDED(pOut->GetProperties(sizeof(outProps), (BYTE*)&outProps))) {
outProps.dwTypeSpecificFlags = inputProps.dwTypeSpecificFlags;
pOut->SetProperties(sizeof(outProps), (BYTE*)&outProps);
}
}
//
BITMAPINFOHEADER bihOut;
ExtractBIH(&m_pOutput->CurrentMediaType(), &bihOut);
bool fInputFlipped = bihIn.biHeight >= 0 && bihIn.biCompression <= 3;
bool fOutputFlipped = bihOut.biHeight >= 0 && bihOut.biCompression <= 3;
bool fFlip = fInputFlipped != fOutputFlipped;
if (m_fFlipPicture) { fFlip = !fFlip; }
if (m_fMSMpeg4Fix) { fFlip = !fFlip; }
bool fFlipSub = fOutputFlipped;
if (m_fFlipSubtitles) { fFlipSub = !fFlipSub; }
//
{
CAutoLock cAutoLock(&m_csQueueLock);
if (m_simple_provider) {
CComPtr<ISimpleSubPic> pSubPic;
//int timeStamp1 = GetTickCount();
bool lookupResult = m_simple_provider->LookupSubPic(CalcCurrentTime(), &pSubPic);
//int timeStamp2 = GetTickCount();
//m_time_rasterization += timeStamp2-timeStamp1;
if (lookupResult && pSubPic) {
if (fFlip ^ fFlipSub) {
spd.h = -spd.h;
}
pSubPic->AlphaBlt(&spd);
DbgLog((LOG_TRACE, 3, "AlphaBlt time:%lu", (ULONG)(CalcCurrentTime() / 10000)));
}
}
}
CopyBuffer(pDataOut, (BYTE*)spd.bits, spd.w, abs(spd.h) * (fFlip ? -1 : 1), spd.pitch, mt.subtype);
PrintMessages(pDataOut);
return m_pOutput->Deliver(pOut);
}
// CBaseFilter
CBasePin* CDirectVobSubFilter::GetPin(int n)
{
if (n < __super::GetPinCount()) {
return __super::GetPin(n);
}
n -= __super::GetPinCount();
if (n >= 0 && n < m_pTextInput.GetCount()) {
return m_pTextInput[n];
}
n -= m_pTextInput.GetCount();
return NULL;
}
int CDirectVobSubFilter::GetPinCount()
{
return __super::GetPinCount() + m_pTextInput.GetCount();
}
HRESULT CDirectVobSubFilter::JoinFilterGraph(IFilterGraph* pGraph, LPCWSTR pName)
{
if (pGraph) {
AFX_MANAGE_STATE(AfxGetStaticModuleState());
if (!theApp.GetProfileInt(ResStr(IDS_R_GENERAL), ResStr(IDS_RG_SEENDIVXWARNING), 0)) {
unsigned __int64 ver = GetFileVersion(_T("divx_c32.ax"));
if (((ver >> 48) & 0xffff) == 4 && ((ver >> 32) & 0xffff) == 2) {
DWORD dwVersion = GetVersion();
DWORD dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
DWORD dwWindowsMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
if (dwVersion < 0x80000000 && dwWindowsMajorVersion >= 5) {
AfxMessageBox(IDS_DIVX_WARNING);
theApp.WriteProfileInt(ResStr(IDS_R_GENERAL), ResStr(IDS_RG_SEENDIVXWARNING), 1);
}
}
}
/*removeme*/
if (!g_RegOK) {
DllRegisterServer();
g_RegOK = true;
}
} else {
if (m_hSystrayThread) {
SendMessage(m_tbid.hSystrayWnd, WM_CLOSE, 0, 0);
if (WaitForSingleObject(m_hSystrayThread, 10000) != WAIT_OBJECT_0) {
DbgLog((LOG_TRACE, 0, _T("CALL THE AMBULANCE!!!")));
TerminateThread(m_hSystrayThread, (DWORD) - 1);
}
m_hSystrayThread = 0;
}
}
return __super::JoinFilterGraph(pGraph, pName);
}
STDMETHODIMP CDirectVobSubFilter::QueryFilterInfo(FILTER_INFO* pInfo)
{
CheckPointer(pInfo, E_POINTER);
ValidateReadWritePtr(pInfo, sizeof(FILTER_INFO));
if (!get_Forced()) {
return __super::QueryFilterInfo(pInfo);
}
wcscpy(pInfo->achName, L"DirectVobSub (forced auto-loading version)");
if (pInfo->pGraph = m_pGraph) { m_pGraph->AddRef(); }
return S_OK;
}
// CTransformFilter
HRESULT CDirectVobSubFilter::SetMediaType(PIN_DIRECTION dir, const CMediaType* pmt)
{
HRESULT hr = __super::SetMediaType(dir, pmt);
if (FAILED(hr)) { return hr; }
if (dir == PINDIR_INPUT) {
CAutoLock cAutoLock(&m_csReceive);
REFERENCE_TIME atpf =
pmt->formattype == FORMAT_VideoInfo ? ((VIDEOINFOHEADER*)pmt->Format())->AvgTimePerFrame :
pmt->formattype == FORMAT_VideoInfo2 ? ((VIDEOINFOHEADER2*)pmt->Format())->AvgTimePerFrame :
0;
m_fps = atpf ? 10000000.0 / atpf : 25;
if (pmt->formattype == FORMAT_VideoInfo2) {
m_CurrentVIH2 = *(VIDEOINFOHEADER2*)pmt->Format();
}
DbgLog((LOG_TRACE, 3, "SetMediaType => InitSubPicQueue"));
InitSubPicQueue();
} else if (dir == PINDIR_OUTPUT) {
}
return hr;
}
HRESULT CDirectVobSubFilter::CheckConnect(PIN_DIRECTION dir, IPin* pPin)
{
if (dir == PINDIR_INPUT) {
} else if (dir == PINDIR_OUTPUT) {
/*removeme*/
if (HmGyanusVagyTeNekem(pPin)) { return (E_FAIL); }
}
return __super::CheckConnect(dir, pPin);
}
HRESULT CDirectVobSubFilter::CompleteConnect(PIN_DIRECTION dir, IPin* pReceivePin)
{
bool reconnected = false;
if (dir == PINDIR_INPUT) {
DbgLog((LOG_TRACE, 3, TEXT("connect input")));
DumpGraph(m_pGraph, 0);
CComPtr<IBaseFilter> pFilter;
// needed when we have a decoder with a version number of 3.x
if (SUCCEEDED(m_pGraph->FindFilterByName(L"DivX MPEG-4 DVD Video Decompressor ", &pFilter))
&& (GetFileVersion(_T("divx_c32.ax")) >> 48) <= 4
|| SUCCEEDED(m_pGraph->FindFilterByName(L"Microcrap MPEG-4 Video Decompressor", &pFilter))
|| SUCCEEDED(m_pGraph->FindFilterByName(L"Microsoft MPEG-4 Video Decompressor", &pFilter))
&& (GetFileVersion(_T("mpg4ds32.ax")) >> 48) <= 3) {
m_fMSMpeg4Fix = true;
}
} else if (dir == PINDIR_OUTPUT) {
DbgLog((LOG_TRACE, 3, TEXT("connect output")));
DumpGraph(m_pGraph, 0);
const CMediaType* mtIn = &(m_pInput->CurrentMediaType());
const CMediaType* mtOut = &(m_pOutput->CurrentMediaType());
CMediaType desiredMt;
int position = 0;
HRESULT hr;
bool can_reconnect = false;
bool can_transform = (CheckTransform(mtIn, mtOut) == S_OK);
if (mtIn->subtype != mtOut->subtype) {
position = GetOutputSubtypePosition(mtOut->subtype);
if (position >= 0) {
hr = GetMediaType(position, &desiredMt);
if (hr != S_OK) {
DbgLog((LOG_ERROR, 3, TEXT("Unexpected error when GetMediaType, position:%d"), position));
} else {
hr = CheckTransform(&desiredMt, mtOut);
if (hr != S_OK) {
DbgLog((LOG_TRACE, 3, TEXT("Transform not accept:")));
DisplayType(0, &desiredMt);
DisplayType(0, mtOut);
} else {
hr = m_pInput->GetConnected()->QueryAccept(&desiredMt);
if (hr != S_OK) {
DbgLog((LOG_TRACE, 3, TEXT("Upstream not accept:")));
DisplayType(0, &desiredMt);
} else {
can_reconnect = true;
DbgLog((LOG_ERROR, 3, TEXT("Can use the same subtype!")));
}
}
}
} else {
DbgLog((LOG_ERROR, 3, TEXT("Cannot use the same subtype!")));
}
}
if (can_reconnect) {
if (SUCCEEDED(ReconnectPin(m_pInput, &desiredMt))) {
reconnected = true;
//m_pInput->SetMediaType(&desiredMt);
DbgLog((LOG_TRACE, 3, TEXT("reconnected succeed!")));
} else {
//log
return E_FAIL;
}
} else if (!can_transform) {
DbgLog((LOG_TRACE, 3, TEXT("Failed to agree reconnect type!")));
if (m_pInput->IsConnected()) {
m_pInput->GetConnected()->Disconnect();
m_pInput->Disconnect();
}
if (m_pOutput->IsConnected()) {
m_pOutput->GetConnected()->Disconnect();
m_pOutput->Disconnect();
}
return VFW_E_TYPE_NOT_ACCEPTED;
}
}
if (!reconnected && m_pOutput->IsConnected()) {
if (!m_hSystrayThread && !m_xy_bool_opt[BOOL_HIDE_TRAY_ICON]) {
m_tbid.graph = m_pGraph;
m_tbid.dvs = static_cast<IDirectVobSub*>(this);
DWORD tid;
m_hSystrayThread = CreateThread(0, 0, SystrayThreadProc, &m_tbid, 0, &tid);
}
m_pInput->SetMediaType(&m_pInput->CurrentMediaType());
}
HRESULT hr = __super::CompleteConnect(dir, pReceivePin);
DbgLog((LOG_TRACE, 3, TEXT("connect fininshed!")));
DumpGraph(m_pGraph, 0);
return hr;
}
HRESULT CDirectVobSubFilter::BreakConnect(PIN_DIRECTION dir)
{
if (dir == PINDIR_INPUT) {
if (m_pInput->IsConnected()) {
m_inputFmtCount = -1;
m_outputFmtCount = -1;
}
//if(m_pOutput->IsConnected())
//{
// m_pOutput->GetConnected()->Disconnect();
// m_pOutput->Disconnect();
//}
} else if (dir == PINDIR_OUTPUT) {
if (m_pOutput->IsConnected()) {
m_outputFmtCount = -1;
}
// not really needed, but may free up a little memory
CAutoLock cAutoLock(&m_csQueueLock);
m_simple_provider = NULL;
}
return __super::BreakConnect(dir);
}
HRESULT CDirectVobSubFilter::StartStreaming()
{
/* WARNING: calls to m_pGraph member functions from within this function will generate deadlock with Haali
* Video Renderer in MPC. Reason is that CAutoLock's variables in IFilterGraph functions are overriden by
* CFGManager class.
*/
m_fLoading = false;
DbgLog((LOG_TRACE, 3, "StartStreaming => InitSubPicQueue"));
InitSubPicQueue();
m_tbid.fRunOnce = true;
put_MediaFPS(m_fMediaFPSEnabled, m_MediaFPS);
return __super::StartStreaming();
}
HRESULT CDirectVobSubFilter::StopStreaming()
{
InvalidateSubtitle();
//xy Timing
//FILE * timingFile = fopen("C:\\vsfilter_timing.txt", "at");
//fprintf(timingFile, "%s:%ld %s:%ld\n", "m_time_alphablt", m_time_alphablt, "m_time_rasterization", m_time_rasterization);
//fclose(timingFile);
return __super::StopStreaming();
}
HRESULT CDirectVobSubFilter::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate)
{
m_tPrev = tStart;
return __super::NewSegment(tStart, tStop, dRate);
}
//
REFERENCE_TIME CDirectVobSubFilter::CalcCurrentTime()
{
REFERENCE_TIME rt = m_pSubClock ? m_pSubClock->GetTime() : m_tPrev;
return (rt - 10000i64 * m_SubtitleDelay) * m_SubtitleSpeedMul / m_SubtitleSpeedDiv; // no, it won't overflow if we use normal parameters (__int64 is enough for about 2000 hours if we multiply it by the max: 65536 as m_SubtitleSpeedMul)
}
void CDirectVobSubFilter::InitSubPicQueue()
{
CAutoLock cAutoLock(&m_csQueueLock);
CacheManager::GetPathDataMruCache()->SetMaxItemNum(m_xy_int_opt[INT_PATH_DATA_CACHE_MAX_ITEM_NUM]);
CacheManager::GetScanLineData2MruCache()->SetMaxItemNum(m_xy_int_opt[INT_SCAN_LINE_DATA_CACHE_MAX_ITEM_NUM]);
CacheManager::GetOverlayNoBlurMruCache()->SetMaxItemNum(m_xy_int_opt[INT_OVERLAY_NO_BLUR_CACHE_MAX_ITEM_NUM]);
CacheManager::GetOverlayMruCache()->SetMaxItemNum(m_xy_int_opt[INT_OVERLAY_CACHE_MAX_ITEM_NUM]);
XyFwGroupedDrawItemsHashKey::GetCacher()->SetMaxItemNum(m_xy_int_opt[INT_BITMAP_MRU_CACHE_ITEM_NUM]);
CacheManager::GetBitmapMruCache()->SetMaxItemNum(m_xy_int_opt[INT_BITMAP_MRU_CACHE_ITEM_NUM]);
CacheManager::GetClipperAlphaMaskMruCache()->SetMaxItemNum(m_xy_int_opt[INT_CLIPPER_MRU_CACHE_ITEM_NUM]);
CacheManager::GetTextInfoCache()->SetMaxItemNum(m_xy_int_opt[INT_TEXT_INFO_CACHE_ITEM_NUM]);
CacheManager::GetAssTagListMruCache()->SetMaxItemNum(m_xy_int_opt[INT_ASS_TAG_LIST_CACHE_ITEM_NUM]);
SubpixelPositionControler::GetGlobalControler().SetSubpixelLevel(static_cast<SubpixelPositionControler::SUBPIXEL_LEVEL>(m_xy_int_opt[INT_SUBPIXEL_POS_LEVEL]));
m_simple_provider = NULL;
const GUID& subtype = m_pInput->CurrentMediaType().subtype;
BITMAPINFOHEADER bihIn;
ExtractBIH(&m_pInput->CurrentMediaType(), &bihIn);
m_spd.type = -1;
if (subtype == MEDIASUBTYPE_YV12) { m_spd.type = MSP_YV12; }
else if (subtype == MEDIASUBTYPE_P010) { m_spd.type = MSP_P010; }
else if (subtype == MEDIASUBTYPE_P016) { m_spd.type = MSP_P016; }
else if (subtype == MEDIASUBTYPE_I420 || subtype == MEDIASUBTYPE_IYUV) { m_spd.type = MSP_IYUV; }
else if (subtype == MEDIASUBTYPE_YUY2) { m_spd.type = MSP_YUY2; }
else if (subtype == MEDIASUBTYPE_RGB32) { m_spd.type = MSP_RGB32; }
else if (subtype == MEDIASUBTYPE_RGB24) { m_spd.type = MSP_RGB24; }
else if (subtype == MEDIASUBTYPE_RGB565) { m_spd.type = MSP_RGB16; }
else if (subtype == MEDIASUBTYPE_RGB555) { m_spd.type = MSP_RGB15; }
else if (subtype == MEDIASUBTYPE_NV12) { m_spd.type = MSP_NV12; }
else if (subtype == MEDIASUBTYPE_NV21) { m_spd.type = MSP_NV21; }
else if (subtype == MEDIASUBTYPE_AYUV) { m_spd.type = MSP_AYUV; }
m_spd.w = m_w;
m_spd.h = m_h;
m_spd.bpp = (m_spd.type == MSP_P010 || m_spd.type == MSP_P016) ? 16 :
(m_spd.type == MSP_YV12 || m_spd.type == MSP_IYUV || m_spd.type == MSP_NV12 || m_spd.type == MSP_NV21) ? 8 : bihIn.biBitCount;
m_spd.pitch = m_spd.w * m_spd.bpp >> 3;
m_pTempPicBuff.Free();
if (m_spd.type == MSP_YV12 || m_spd.type == MSP_IYUV || m_spd.type == MSP_NV12 || m_spd.type == MSP_NV21) {
m_pTempPicBuff.Allocate(4 * m_spd.pitch * m_spd.h); //fix me: can be smaller
} else if (m_spd.type == MSP_P010 || m_spd.type == MSP_P016) {
m_pTempPicBuff.Allocate(m_spd.pitch * m_spd.h + m_spd.pitch * m_spd.h / 2);
} else {
m_pTempPicBuff.Allocate(m_spd.pitch * m_spd.h);
}
m_spd.bits = (void*)m_pTempPicBuff;
CSize video(bihIn.biWidth, bihIn.biHeight), window = video;
if (AdjustFrameSize(window)) { video += video; }
ASSERT(window == CSize(m_w, m_h));
CRect video_rect(CPoint((window.cx - video.cx) / 2, (window.cy - video.cy) / 2), video);
HRESULT hr = S_OK;
//m_pSubPicQueue = m_fDoPreBuffering
// ? (ISubPicQueue*)new CSubPicQueue(MAX_SUBPIC_QUEUE_LENGTH, pSubPicAllocator, &hr)
// : (ISubPicQueue*)new CSubPicQueueNoThread(pSubPicAllocator, &hr);
m_simple_provider = new SimpleSubPicProvider2(m_spd.type, CSize(m_w, m_h), window, video_rect, this, &hr);
if (FAILED(hr)) { m_simple_provider = NULL; }
XySetSize(DirectVobSubXyOptions::SIZE_ORIGINAL_VIDEO, CSize(m_w, m_h));
UpdateSubtitle(false);
InitObj4OSD();
}
bool CDirectVobSubFilter::AdjustFrameSize(CSize& s)
{
int horizontal, vertical, resx2, resx2minw, resx2minh;
get_ExtendPicture(&horizontal, &vertical, &resx2, &resx2minw, &resx2minh);
bool fRet = (resx2 == 1) || (resx2 == 2 && s.cx * s.cy <= resx2minw * resx2minh);
if (fRet) {
s.cx <<= 1;
s.cy <<= 1;
}
int h;
switch (vertical & 0x7f) {
case 1:
h = s.cx * 9 / 16;
if (s.cy < h || !!(vertical & 0x80)) { s.cy = (h + 3) & ~3; }
break;
case 2:
h = s.cx * 3 / 4;
if (s.cy < h || !!(vertical & 0x80)) { s.cy = (h + 3) & ~3; }
break;
case 3:
h = 480;
if (s.cy < h || !!(vertical & 0x80)) { s.cy = (h + 3) & ~3; }
break;
case 4:
h = 576;
if (s.cy < h || !!(vertical & 0x80)) { s.cy = (h + 3) & ~3; }
break;
}
if (horizontal == 1) {
s.cx = (s.cx + 31) & ~31;
s.cy = (s.cy + 1) & ~1;
}
return (fRet);
}
STDMETHODIMP CDirectVobSubFilter::Count(DWORD* pcStreams)
{
if (!pcStreams) { return E_POINTER; }
*pcStreams = 0;
int nLangs = 0;
if (SUCCEEDED(get_LanguageCount(&nLangs))) {
(*pcStreams) += nLangs;
}
(*pcStreams) += 2; // enable ... disable
(*pcStreams) += 2; // normal flipped
return S_OK;
}
#define MAXPREFLANGS 5
int CDirectVobSubFilter::FindPreferedLanguage(bool fHideToo)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
int nLangs;
get_LanguageCount(&nLangs);
if (nLangs <= 0) { return (0); }
for (int i = 0; i < MAXPREFLANGS; i++) {
CString tmp;
tmp.Format(IDS_RL_LANG, i);
CString lang = theApp.GetProfileString(ResStr(IDS_R_PREFLANGS), tmp);
if (!lang.IsEmpty()) {
for (int ret = 0; ret < nLangs; ret++) {
CString l;
WCHAR* pName = NULL;
get_LanguageName(ret, &pName);
l = pName;
CoTaskMemFree(pName);
if (!l.CompareNoCase(lang)) { return (ret); }
}
}
}
return (0);
}
void CDirectVobSubFilter::UpdatePreferedLanguages(CString l)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
CString langs[MAXPREFLANGS + 1];
int i = 0, j = 0, k = -1;
for (; i < MAXPREFLANGS; i++) {
CString tmp;
tmp.Format(IDS_RL_LANG, i);
langs[j] = theApp.GetProfileString(ResStr(IDS_R_PREFLANGS), tmp);
if (!langs[j].IsEmpty()) {
if (!langs[j].CompareNoCase(l)) { k = j; }
j++;
}
}
if (k == -1) {
langs[k = j] = l;
j++;
}
// move the selected to the top of the list
while (k > 0) {
CString tmp = langs[k];
langs[k] = langs[k - 1];
langs[k - 1] = tmp;
k--;
}
// move "Hide subtitles" to the last position if it wasn't our selection
CString hidesubs;
hidesubs.LoadString(IDS_M_HIDESUBTITLES);
for (k = 1; k < j; k++) {
if (!langs[k].CompareNoCase(hidesubs)) { break; }
}
while (k < j - 1) {
CString tmp = langs[k];
langs[k] = langs[k + 1];
langs[k + 1] = tmp;
k++;
}
for (i = 0; i < j; i++) {
CString tmp;
tmp.Format(IDS_RL_LANG, i);
theApp.WriteProfileString(ResStr(IDS_R_PREFLANGS), tmp, langs[i]);
}
}
STDMETHODIMP CDirectVobSubFilter::Enable(long lIndex, DWORD dwFlags)
{
if (!(dwFlags & AMSTREAMSELECTENABLE_ENABLE)) {
return E_NOTIMPL;
}
int nLangs = 0;
get_LanguageCount(&nLangs);
if (!(lIndex >= 0 && lIndex < nLangs + 2 + 2)) {
return E_INVALIDARG;
}
int i = lIndex - 1;
if (i == -1 && !m_fLoading) { // we need this because when loading something stupid media player pushes the first stream it founds, which is "enable" in our case
put_HideSubtitles(false);
} else if (i >= 0 && i < nLangs) {
put_HideSubtitles(false);
put_SelectedLanguage(i);
WCHAR* pName = NULL;
if (SUCCEEDED(get_LanguageName(i, &pName))) {
UpdatePreferedLanguages(CString(pName));
if (pName) { CoTaskMemFree(pName); }
}
} else if (i == nLangs && !m_fLoading) {
put_HideSubtitles(true);
} else if ((i == nLangs + 1 || i == nLangs + 2) && !m_fLoading) {
put_Flip(i == nLangs + 2, m_fFlipSubtitles);
}
return S_OK;
}
STDMETHODIMP CDirectVobSubFilter::Info(long lIndex, AM_MEDIA_TYPE** ppmt, DWORD* pdwFlags, LCID* plcid, DWORD* pdwGroup, WCHAR** ppszName, IUnknown** ppObject, IUnknown** ppUnk)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
const int FLAG_CMD = 1;
const int FLAG_EXTERNAL_SUB = 2;
const int FLAG_PICTURE_CMD = 4;
const int FLAG_VISIBILITY_CMD = 8;
const int GROUP_NUM_BASE = 0x648E40;//random number
int nLangs = 0;
get_LanguageCount(&nLangs);
if (!(lIndex >= 0 && lIndex < nLangs + 2 + 2)) {
return E_INVALIDARG;
}
int i = lIndex - 1;
if (ppmt) { *ppmt = CreateMediaType(&m_pInput->CurrentMediaType()); }
if (pdwFlags) {
*pdwFlags = 0;
if (i == -1 && !m_fHideSubtitles
|| i >= 0 && i < nLangs && i == m_iSelectedLanguage
|| i == nLangs && m_fHideSubtitles
|| i == nLangs + 1 && !m_fFlipPicture
|| i == nLangs + 2 && m_fFlipPicture) {
*pdwFlags |= AMSTREAMSELECTINFO_ENABLED;
}
}
if (plcid) { *plcid = 0; }
if (pdwGroup) {
*pdwGroup = GROUP_NUM_BASE;
if (i == -1) {
*pdwGroup = GROUP_NUM_BASE | FLAG_CMD | FLAG_VISIBILITY_CMD;
} else if (i >= 0 && i < nLangs) {
bool isEmbedded = false;
if (SUCCEEDED(GetIsEmbeddedSubStream(i, &isEmbedded))) {
if (isEmbedded) {
*pdwGroup = GROUP_NUM_BASE & ~(FLAG_CMD | FLAG_EXTERNAL_SUB);
} else {
*pdwGroup = (GROUP_NUM_BASE & ~FLAG_CMD) | FLAG_EXTERNAL_SUB;
}
}
} else if (i == nLangs) {
*pdwGroup = GROUP_NUM_BASE | FLAG_CMD | FLAG_VISIBILITY_CMD;
} else if (i == nLangs + 1) {
*pdwGroup = GROUP_NUM_BASE | FLAG_CMD | FLAG_PICTURE_CMD;
} else if (i == nLangs + 2) {
*pdwGroup = GROUP_NUM_BASE | FLAG_CMD | FLAG_PICTURE_CMD;
}
}
if (ppszName) {
*ppszName = NULL;
CStringW str;
if (i == -1) { str = ResStr(IDS_M_SHOWSUBTITLES); }
else if (i >= 0 && i < nLangs) {
get_LanguageName(i, ppszName);
} else if (i == nLangs) {
str = ResStr(IDS_M_HIDESUBTITLES);
} else if (i == nLangs + 1) {
str = ResStr(IDS_M_ORIGINALPICTURE);
} else if (i == nLangs + 2) {
str = ResStr(IDS_M_FLIPPEDPICTURE);
}
if (!str.IsEmpty()) {
*ppszName = (WCHAR*)CoTaskMemAlloc((str.GetLength() + 1) * sizeof(WCHAR));
if (*ppszName == NULL) { return S_FALSE; }
wcscpy(*ppszName, str);
}
}
if (ppObject) { *ppObject = NULL; }
if (ppUnk) { *ppUnk = NULL; }
return S_OK;
}
STDMETHODIMP CDirectVobSubFilter::GetClassID(CLSID* pClsid)
{
if (pClsid == NULL) { return E_POINTER; }
*pClsid = m_clsid;
return NOERROR;
}
STDMETHODIMP CDirectVobSubFilter::GetPages(CAUUID* pPages)
{
CheckPointer(pPages, E_POINTER);
pPages->cElems = 8;
pPages->pElems = (GUID*)CoTaskMemAlloc(sizeof(GUID) * pPages->cElems);
if (pPages->pElems == NULL) { return E_OUTOFMEMORY; }
int i = 0;
pPages->pElems[i++] = __uuidof(CDVSMainPPage);
pPages->pElems[i++] = __uuidof(CDVSGeneralPPage);
pPages->pElems[i++] = __uuidof(CDVSMiscPPage);
pPages->pElems[i++] = __uuidof(CDVSMorePPage);
pPages->pElems[i++] = __uuidof(CDVSTimingPPage);
pPages->pElems[i++] = __uuidof(CDVSColorPPage);
pPages->pElems[i++] = __uuidof(CDVSPathsPPage);
pPages->pElems[i++] = __uuidof(CDVSAboutPPage);
return NOERROR;
}
// IDirectVobSub
STDMETHODIMP CDirectVobSubFilter::put_FileName(WCHAR* fn)
{
AMTRACE((TEXT(__FUNCTION__), 0));
HRESULT hr = CDirectVobSub::put_FileName(fn);
if (hr == S_OK && !Open()) {
m_FileName.Empty();
hr = E_FAIL;
}
return hr;
}
STDMETHODIMP CDirectVobSubFilter::get_LanguageCount(int* nLangs)
{
HRESULT hr = CDirectVobSub::get_LanguageCount(nLangs);
if (hr == NOERROR && nLangs) {
CAutoLock cAutolock(&m_csQueueLock);
*nLangs = 0;
POSITION pos = m_pSubStreams.GetHeadPosition();
while (pos) { (*nLangs) += m_pSubStreams.GetNext(pos)->GetStreamCount(); }
}
return hr;
}
STDMETHODIMP CDirectVobSubFilter::get_LanguageName(int iLanguage, WCHAR** ppName)
{
HRESULT hr = CDirectVobSub::get_LanguageName(iLanguage, ppName);
if (!ppName) { return E_POINTER; }
if (hr == NOERROR) {
CAutoLock cAutolock(&m_csQueueLock);
hr = E_INVALIDARG;
int i = iLanguage;
POSITION pos = m_pSubStreams.GetHeadPosition();
while (i >= 0 && pos) {
CComPtr<ISubStream> pSubStream = m_pSubStreams.GetNext(pos);
if (i < pSubStream->GetStreamCount()) {
pSubStream->GetStreamInfo(i, ppName, NULL);
hr = NOERROR;
break;
}
i -= pSubStream->GetStreamCount();
}
}
return hr;
}
STDMETHODIMP CDirectVobSubFilter::put_SelectedLanguage(int iSelected)
{
HRESULT hr = CDirectVobSub::put_SelectedLanguage(iSelected);
if (hr == NOERROR) {
UpdateSubtitle(false);
}
return hr;
}
STDMETHODIMP CDirectVobSubFilter::put_HideSubtitles(bool fHideSubtitles)
{
HRESULT hr = CDirectVobSub::put_HideSubtitles(fHideSubtitles);
if (hr == NOERROR) {
UpdateSubtitle(false);
}
return hr;
}
STDMETHODIMP CDirectVobSubFilter::put_PreBuffering(bool fDoPreBuffering)
{
HRESULT hr = CDirectVobSub::put_PreBuffering(fDoPreBuffering);
if (hr == NOERROR) {
DbgLog((LOG_TRACE, 3, "put_PreBuffering => InitSubPicQueue"));
InitSubPicQueue();
}
return hr;
}
STDMETHODIMP CDirectVobSubFilter::put_Placement(bool fOverridePlacement, int xperc, int yperc)
{
DbgLog((LOG_TRACE, 3, "%s(%d) %s", __FILE__, __LINE__, __FUNCTION__));
HRESULT hr = CDirectVobSub::put_Placement(fOverridePlacement, xperc, yperc);
if (hr == NOERROR) {
//DbgLog((LOG_TRACE, 3, "%d %s:UpdateSubtitle(true)", __LINE__, __FUNCTION__));
//UpdateSubtitle(true);
UpdateSubtitle(false);
}
return hr;
}
STDMETHODIMP CDirectVobSubFilter::put_VobSubSettings(bool fBuffer, bool fOnlyShowForcedSubs, bool fReserved)
{
HRESULT hr = CDirectVobSub::put_VobSubSettings(fBuffer, fOnlyShowForcedSubs, fReserved);
if (hr == NOERROR) {
// UpdateSubtitle(false);
InvalidateSubtitle();
}
return hr;
}
STDMETHODIMP CDirectVobSubFilter::put_TextSettings(void* lf, int lflen, COLORREF color, bool fShadow, bool fOutline, bool fAdvancedRenderer)
{
HRESULT hr = CDirectVobSub::put_TextSettings(lf, lflen, color, fShadow, fOutline, fAdvancedRenderer);
if (hr == NOERROR) {
// UpdateSubtitle(true);
InvalidateSubtitle();
}
return hr;
}
STDMETHODIMP CDirectVobSubFilter::put_SubtitleTiming(int delay, int speedmul, int speeddiv)
{
HRESULT hr = CDirectVobSub::put_SubtitleTiming(delay, speedmul, speeddiv);
if (hr == NOERROR) {
InvalidateSubtitle();
}
return hr;
}
STDMETHODIMP CDirectVobSubFilter::get_CachesInfo(CachesInfo* caches_info)
{
CAutoLock cAutoLock(&m_csQueueLock);
HRESULT hr = CDirectVobSub::get_CachesInfo(caches_info);
caches_info->path_cache_cur_item_num = CacheManager::GetPathDataMruCache()->GetCurItemNum();
caches_info->path_cache_hit_count = CacheManager::GetPathDataMruCache()->GetCacheHitCount();
caches_info->path_cache_query_count = CacheManager::GetPathDataMruCache()->GetQueryCount();
caches_info->scanline_cache2_cur_item_num = CacheManager::GetScanLineData2MruCache()->GetCurItemNum();
caches_info->scanline_cache2_hit_count = CacheManager::GetScanLineData2MruCache()->GetCacheHitCount();
caches_info->scanline_cache2_query_count = CacheManager::GetScanLineData2MruCache()->GetQueryCount();
caches_info->non_blur_cache_cur_item_num = CacheManager::GetOverlayNoBlurMruCache()->GetCurItemNum();
caches_info->non_blur_cache_hit_count = CacheManager::GetOverlayNoBlurMruCache()->GetCacheHitCount();
caches_info->non_blur_cache_query_count = CacheManager::GetOverlayNoBlurMruCache()->GetQueryCount();
caches_info->overlay_cache_cur_item_num = CacheManager::GetOverlayMruCache()->GetCurItemNum();
caches_info->overlay_cache_hit_count = CacheManager::GetOverlayMruCache()->GetCacheHitCount();
caches_info->overlay_cache_query_count = CacheManager::GetOverlayMruCache()->GetQueryCount();
caches_info->bitmap_cache_cur_item_num = CacheManager::GetBitmapMruCache()->GetCurItemNum();
caches_info->bitmap_cache_hit_count = CacheManager::GetBitmapMruCache()->GetCacheHitCount();
caches_info->bitmap_cache_query_count = CacheManager::GetBitmapMruCache()->GetQueryCount();
caches_info->interpolate_cache_cur_item_num = CacheManager::GetSubpixelVarianceCache()->GetCurItemNum();
caches_info->interpolate_cache_hit_count = CacheManager::GetSubpixelVarianceCache()->GetCacheHitCount();
caches_info->interpolate_cache_query_count = CacheManager::GetSubpixelVarianceCache()->GetQueryCount();
caches_info->text_info_cache_cur_item_num = CacheManager::GetTextInfoCache()->GetCurItemNum();
caches_info->text_info_cache_hit_count = CacheManager::GetTextInfoCache()->GetCacheHitCount();
caches_info->text_info_cache_query_count = CacheManager::GetTextInfoCache()->GetQueryCount();
caches_info->word_info_cache_cur_item_num = CacheManager::GetAssTagListMruCache()->GetCurItemNum();
caches_info->word_info_cache_hit_count = CacheManager::GetAssTagListMruCache()->GetCacheHitCount();
caches_info->word_info_cache_query_count = CacheManager::GetAssTagListMruCache()->GetQueryCount();
caches_info->scanline_cache_cur_item_num = CacheManager::GetScanLineDataMruCache()->GetCurItemNum();
caches_info->scanline_cache_hit_count = CacheManager::GetScanLineDataMruCache()->GetCacheHitCount();
caches_info->scanline_cache_query_count = CacheManager::GetScanLineDataMruCache()->GetQueryCount();
caches_info->overlay_key_cache_cur_item_num = CacheManager::GetOverlayNoOffsetMruCache()->GetCurItemNum();
caches_info->overlay_key_cache_hit_count = CacheManager::GetOverlayNoOffsetMruCache()->GetCacheHitCount();
caches_info->overlay_key_cache_query_count = CacheManager::GetOverlayNoOffsetMruCache()->GetQueryCount();
caches_info->clipper_cache_cur_item_num = CacheManager::GetClipperAlphaMaskMruCache()->GetCurItemNum();
caches_info->clipper_cache_hit_count = CacheManager::GetClipperAlphaMaskMruCache()->GetCacheHitCount();
caches_info->clipper_cache_query_count = CacheManager::GetClipperAlphaMaskMruCache()->GetQueryCount();
return hr;
}
STDMETHODIMP CDirectVobSubFilter::get_XyFlyWeightInfo(XyFlyWeightInfo* xy_fw_info)
{
CAutoLock cAutoLock(&m_csQueueLock);
HRESULT hr = CDirectVobSub::get_XyFlyWeightInfo(xy_fw_info);
xy_fw_info->xy_fw_string_w.cur_item_num = XyFwStringW::GetCacher()->GetCurItemNum();
xy_fw_info->xy_fw_string_w.hit_count = XyFwStringW::GetCacher()->GetCacheHitCount();
xy_fw_info->xy_fw_string_w.query_count = XyFwStringW::GetCacher()->GetQueryCount();
xy_fw_info->xy_fw_grouped_draw_items_hash_key.cur_item_num = XyFwGroupedDrawItemsHashKey::GetCacher()->GetCurItemNum();
xy_fw_info->xy_fw_grouped_draw_items_hash_key.hit_count = XyFwGroupedDrawItemsHashKey::GetCacher()->GetCacheHitCount();
xy_fw_info->xy_fw_grouped_draw_items_hash_key.query_count = XyFwGroupedDrawItemsHashKey::GetCacher()->GetQueryCount();
return hr;
}
STDMETHODIMP CDirectVobSubFilter::get_MediaFPS(bool* fEnabled, double* fps)
{
HRESULT hr = CDirectVobSub::get_MediaFPS(fEnabled, fps);
CComQIPtr<IMediaSeeking> pMS = m_pGraph;
double rate;
if (pMS && SUCCEEDED(pMS->GetRate(&rate))) {
m_MediaFPS = rate * m_fps;
if (fps) { *fps = m_MediaFPS; }
}
return hr;
}
STDMETHODIMP CDirectVobSubFilter::put_MediaFPS(bool fEnabled, double fps)
{
HRESULT hr = CDirectVobSub::put_MediaFPS(fEnabled, fps);
CComQIPtr<IMediaSeeking> pMS = m_pGraph;
if (pMS) {
if (hr == NOERROR) {
hr = pMS->SetRate(m_fMediaFPSEnabled ? m_MediaFPS / m_fps : 1.0);
}
double dRate;
if (SUCCEEDED(pMS->GetRate(&dRate))) {
m_MediaFPS = dRate * m_fps;
}
}
return hr;
}
STDMETHODIMP CDirectVobSubFilter::get_ZoomRect(NORMALIZEDRECT* rect)
{
return E_NOTIMPL;
}
STDMETHODIMP CDirectVobSubFilter::put_ZoomRect(NORMALIZEDRECT* rect)
{
return E_NOTIMPL;
}
// IDirectVobSub2
STDMETHODIMP CDirectVobSubFilter::put_TextSettings(STSStyle* pDefStyle)
{
HRESULT hr = CDirectVobSub::put_TextSettings(pDefStyle);
if (hr == NOERROR) {
//DbgLog((LOG_TRACE, 3, "%d %s:UpdateSubtitle(true)", __LINE__, __FUNCTION__));
//UpdateSubtitle(true);
UpdateSubtitle(false);
}
return hr;
}
STDMETHODIMP CDirectVobSubFilter::put_AspectRatioSettings(CSimpleTextSubtitle::EPARCompensationType* ePARCompensationType)
{
HRESULT hr = CDirectVobSub::put_AspectRatioSettings(ePARCompensationType);
if (hr == NOERROR) {
//DbgLog((LOG_TRACE, 3, "%d %s:UpdateSubtitle(true)", __LINE__, __FUNCTION__));
//UpdateSubtitle(true);
UpdateSubtitle(false);
}
return hr;
}
// IDirectVobSubFilterColor
STDMETHODIMP CDirectVobSubFilter::HasConfigDialog(int iSelected)
{
int nLangs;
if (FAILED(get_LanguageCount(&nLangs))) { return E_FAIL; }
return E_FAIL;
// TODO: temporally disabled since we don't have a new textsub/vobsub editor dlg for dvs yet
// return(nLangs >= 0 && iSelected < nLangs ? S_OK : E_FAIL);
}
STDMETHODIMP CDirectVobSubFilter::ShowConfigDialog(int iSelected, HWND hWndParent)
{
// TODO: temporally disabled since we don't have a new textsub/vobsub editor dlg for dvs yet
return (E_FAIL);
}
///////////////////////////////////////////////////////////////////////////
CDirectVobSubFilter2::CDirectVobSubFilter2(LPUNKNOWN punk, HRESULT* phr, const GUID& clsid) :
CDirectVobSubFilter(punk, phr, clsid)
{
}
HRESULT CDirectVobSubFilter2::CheckConnect(PIN_DIRECTION dir, IPin* pPin)
{
CPinInfo pi;
if (FAILED(pPin->QueryPinInfo(&pi))) { return E_FAIL; }
if (CComQIPtr<IDirectVobSub>(pi.pFilter)) { return E_FAIL; }
if (dir == PINDIR_INPUT) {
CFilterInfo fi;
if (SUCCEEDED(pi.pFilter->QueryFilterInfo(&fi))
&& !wcsnicmp(fi.achName, L"Overlay Mixer", 13)) {
return (E_FAIL);
}
} else {
}
return __super::CheckConnect(dir, pPin);
}
HRESULT CDirectVobSubFilter2::JoinFilterGraph(IFilterGraph* pGraph, LPCWSTR pName)
{
XY_AUTO_TIMING(_T("CDirectVobSubFilter2::JoinFilterGraph"));
if (pGraph) {
if (IsAppBlackListed()) { return E_FAIL; }
BeginEnumFilters(pGraph, pEF, pBF) {
if (pBF != (IBaseFilter*)this && CComQIPtr<IDirectVobSub>(pBF)) {
return E_FAIL;
}
}
EndEnumFilters
// don't look... we will do some serious graph hacking again...
//
// we will add dvs2 to the filter graph cache
// - if the main app has already added some kind of renderer or overlay mixer (anything which accepts video on its input)
// and
// - if we have a reason to auto-load (we don't want to make any trouble when there is no need :)
//
// This whole workaround is needed because the video stream will always be connected
// to the pre-added filters first, no matter how high merit we have.
if (!get_Forced()) {
BeginEnumFilters(pGraph, pEF, pBF) {
if (CComQIPtr<IDirectVobSub>(pBF)) {
continue;
}
CComPtr<IPin> pInPin = GetFirstPin(pBF, PINDIR_INPUT);
CComPtr<IPin> pOutPin = GetFirstPin(pBF, PINDIR_OUTPUT);
if (!pInPin) {
continue;
}
CComPtr<IPin> pPin;
if (pInPin && SUCCEEDED(pInPin->ConnectedTo(&pPin))
|| pOutPin && SUCCEEDED(pOutPin->ConnectedTo(&pPin))) {
continue;
}
if (pOutPin && GetFilterName(pBF) != _T("Overlay Mixer")) {
continue;
}
bool fVideoInputPin = false;
do {
BITMAPINFOHEADER bih = {sizeof(BITMAPINFOHEADER), 384, 288, 1, 16, '2YUY', 384 * 288 * 2, 0, 0, 0, 0};
CMediaType cmt;
cmt.majortype = MEDIATYPE_Video;
cmt.subtype = MEDIASUBTYPE_YUY2;
cmt.formattype = FORMAT_VideoInfo;
cmt.pUnk = NULL;
cmt.bFixedSizeSamples = TRUE;
cmt.bTemporalCompression = TRUE;
cmt.lSampleSize = 384 * 288 * 2;
VIDEOINFOHEADER* vih = (VIDEOINFOHEADER*)cmt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER));
memset(vih, 0, sizeof(VIDEOINFOHEADER));
memcpy(&vih->bmiHeader, &bih, sizeof(bih));
vih->AvgTimePerFrame = 400000;
if (SUCCEEDED(pInPin->QueryAccept(&cmt))) {
fVideoInputPin = true;
break;
}
VIDEOINFOHEADER2* vih2 = (VIDEOINFOHEADER2*)cmt.AllocFormatBuffer(sizeof(VIDEOINFOHEADER2));
memset(vih2, 0, sizeof(VIDEOINFOHEADER2));
memcpy(&vih2->bmiHeader, &bih, sizeof(bih));
vih2->AvgTimePerFrame = 400000;
vih2->dwPictAspectRatioX = 384;
vih2->dwPictAspectRatioY = 288;
if (SUCCEEDED(pInPin->QueryAccept(&cmt))) {
fVideoInputPin = true;
break;
}
} while (false);
if (fVideoInputPin) {
CComPtr<IBaseFilter> pDVS;
if (ShouldWeAutoload(pGraph) && SUCCEEDED(pDVS.CoCreateInstance(__uuidof(CDirectVobSubFilter2)))) {
CComQIPtr<IDirectVobSub2>(pDVS)->put_Forced(true);
CComQIPtr<IGraphConfig>(pGraph)->AddFilterToCache(pDVS);
}
break;
}
}
EndEnumFilters
}
} else {
}
return __super::JoinFilterGraph(pGraph, pName);
}
HRESULT CDirectVobSubFilter2::CheckInputType(const CMediaType* mtIn)
{
XY_AUTO_TIMING(_T("CDirectVobSubFilter2::CheckInputType"));
HRESULT hr = __super::CheckInputType(mtIn);
if (FAILED(hr) || m_pInput->IsConnected()) { return hr; }
if (IsAppBlackListed() || !ShouldWeAutoload(m_pGraph)) {
return VFW_E_TYPE_NOT_ACCEPTED;
}
GetRidOfInternalScriptRenderer();
return NOERROR;
}
bool CDirectVobSubFilter2::IsAppBlackListed()
{
XY_AUTO_TIMING(_T("CDirectVobSubFilter2::IsAppBlackListed"));
// all entries must be lowercase!
TCHAR* blacklistedapps[] = {
_T("wm8eutil."), // wmp8 encoder's dummy renderer releases the outputted media sample after calling Receive on its input pin (yes, even when dvobsub isn't registered at all)
_T("explorer."), // as some users reported thumbnail preview loads dvobsub, I've never experienced this yet...
_T("producer."), // this is real's producer
_T("googledesktopindex."), // Google Desktop
_T("googledesktopdisplay."), // Google Desktop
_T("googledesktopcrawl."), // Google Desktop
_T("subtitleworkshop."), // Subtitle Workshop
_T("subtitleworkshop4."),
_T("darksouls."), // Dark Souls (Game)
_T("data."), // Dark Souls (Game - Steam Release)
_T("rometw."), // Rome Total War (Game)
_T("everquest2."), // EverQuest II (Game)
_T("yso_win."), // Ys Origin (Game)
_T("launcher_main."), // Logitech WebCam Software
_T("webcamdell2."), // Dell WebCam Software
};
for (size_t i = 0; i < _countof(blacklistedapps); i++) {
if (theApp.m_AppName.Find(blacklistedapps[i]) >= 0) {
return (true);
}
}
return (false);
}
bool CDirectVobSubFilter2::ShouldWeAutoload(IFilterGraph* pGraph)
{
XY_AUTO_TIMING(_T("CDirectVobSubFilter2::ShouldWeAutoload"));
int level;
bool m_fExternalLoad, m_fWebLoad, m_fEmbeddedLoad;
get_LoadSettings(&level, &m_fExternalLoad, &m_fWebLoad, &m_fEmbeddedLoad);
if (level < 0 || level >= 2) { return (false); }
bool fRet = false;
if (level == 1) {
fRet = m_fExternalLoad = m_fWebLoad = m_fEmbeddedLoad = true;
}
// find text stream on known splitters
if (!fRet && m_fEmbeddedLoad) {
CComPtr<IBaseFilter> pBF;
if ((pBF = FindFilter(CLSID_OggSplitter, pGraph)) || (pBF = FindFilter(CLSID_AviSplitter, pGraph))
|| (pBF = FindFilter(L"{34293064-02F2-41D5-9D75-CC5967ACA1AB}", pGraph)) // matroska demux
|| (pBF = FindFilter(L"{0A68C3B5-9164-4a54-AFAF-995B2FF0E0D4}", pGraph)) // matroska source
|| (pBF = FindFilter(L"{149D2E01-C32E-4939-80F6-C07B81015A7A}", pGraph)) // matroska splitter
|| (pBF = FindFilter(L"{55DA30FC-F16B-49fc-BAA5-AE59FC65F82D}", pGraph)) // Haali Media Splitter
|| (pBF = FindFilter(L"{564FD788-86C9-4444-971E-CC4A243DA150}", pGraph)) // Haali Media Splitter (AR)
|| (pBF = FindFilter(L"{8F43B7D9-9D6B-4F48-BE18-4D787C795EEA}", pGraph)) // Haali Simple Media Splitter
|| (pBF = FindFilter(L"{52B63861-DC93-11CE-A099-00AA00479A58}", pGraph)) // 3ivx splitter
|| (pBF = FindFilter(L"{6D3688CE-3E9D-42F4-92CA-8A11119D25CD}", pGraph)) // our ogg source
|| (pBF = FindFilter(L"{9FF48807-E133-40AA-826F-9B2959E5232D}", pGraph)) // our ogg splitter
|| (pBF = FindFilter(L"{803E8280-F3CE-4201-982C-8CD8FB512004}", pGraph)) // dsm source
|| (pBF = FindFilter(L"{0912B4DD-A30A-4568-B590-7179EBB420EC}", pGraph)) // dsm splitter
|| (pBF = FindFilter(L"{3CCC052E-BDEE-408a-BEA7-90914EF2964B}", pGraph)) // mp4 source
|| (pBF = FindFilter(L"{61F47056-E400-43d3-AF1E-AB7DFFD4C4AD}", pGraph)) // mp4 splitter
|| (pBF = FindFilter(L"{171252A0-8820-4AFE-9DF8-5C92B2D66B04}", pGraph)) // LAV splitter
|| (pBF = FindFilter(L"{B98D13E7-55DB-4385-A33D-09FD1BA26338}", pGraph)) // LAV Splitter Source
|| (pBF = FindFilter(L"{E436EBB5-524F-11CE-9F53-0020AF0BA770}", pGraph)) // Solveig matroska splitter
|| (pBF = FindFilter(L"{1365BE7A-C86A-473C-9A41-C0A6E82C9FA3}", pGraph)) // MPC-HC MPEG PS/TS/PVA source
|| (pBF = FindFilter(L"{DC257063-045F-4BE2-BD5B-E12279C464F0}", pGraph)) // MPC-HC MPEG splitter
|| (pBF = FindFilter(L"{529A00DB-0C43-4f5b-8EF2-05004CBE0C6F}", pGraph)) // AV splitter
|| (pBF = FindFilter(L"{D8980E15-E1F6-4916-A10F-D7EB4E9E10B8}", pGraph)) // AV source
) {
BeginEnumPins(pBF, pEP, pPin) {
BeginEnumMediaTypes(pPin, pEM, pmt) {
if (pmt->majortype == MEDIATYPE_Text || pmt->majortype == MEDIATYPE_Subtitle) {
fRet = true;
break;
}
}
EndEnumMediaTypes(pmt)
if (fRet) { break; }
}
EndEnumFilters
}
}
// find file name
CStringW fn;
BeginEnumFilters(pGraph, pEF, pBF) {
if (CComQIPtr<IFileSourceFilter> pFSF = pBF) {
LPOLESTR fnw = NULL;
if (!pFSF || FAILED(pFSF->GetCurFile(&fnw, NULL)) || !fnw) {
continue;
}
fn = CString(fnw);
CoTaskMemFree(fnw);
break;
}
}
EndEnumFilters
if ((m_fExternalLoad || m_fWebLoad) && (m_fWebLoad || !(wcsstr(fn, L"http://") || wcsstr(fn, L"mms://")))) {
bool fTemp = m_fHideSubtitles;
fRet = !fn.IsEmpty() && SUCCEEDED(put_FileName((LPWSTR)(LPCWSTR)fn))
|| SUCCEEDED(put_FileName(L"c:\\tmp.srt"))
|| fRet;
if (fTemp) { m_fHideSubtitles = true; }
}
return (fRet);
}
void CDirectVobSubFilter2::GetRidOfInternalScriptRenderer()
{
while (CComPtr<IBaseFilter> pBF = FindFilter(L"{48025243-2D39-11CE-875D-00608CB78066}", m_pGraph)) {
BeginEnumPins(pBF, pEP, pPin) {
PIN_DIRECTION dir;
CComPtr<IPin> pPinTo;
if (SUCCEEDED(pPin->QueryDirection(&dir)) && dir == PINDIR_INPUT
&& SUCCEEDED(pPin->ConnectedTo(&pPinTo))) {
m_pGraph->Disconnect(pPinTo);
m_pGraph->Disconnect(pPin);
m_pGraph->ConnectDirect(pPinTo, GetPin(2 + m_pTextInput.GetCount() - 1), NULL);
}
}
EndEnumPins
if (FAILED(m_pGraph->RemoveFilter(pBF))) {
break;
}
}
}
///////////////////////////////////////////////////////////////////////////////
bool CDirectVobSubFilter::Open()
{
AMTRACE((TEXT(__FUNCTION__), 0));
XY_AUTO_TIMING(TEXT("CDirectVobSubFilter::Open"));
AFX_MANAGE_STATE(AfxGetStaticModuleState());
CAutoLock cAutolock(&m_csQueueLock);
m_pSubStreams.RemoveAll();
m_fIsSubStreamEmbeded.RemoveAll();
m_frd.files.RemoveAll();
CAtlArray<CString> paths;
for (int i = 0; i < 10; i++) {
CString tmp;
tmp.Format(IDS_RP_PATH, i);
CString path = theApp.GetProfileString(ResStr(IDS_R_DEFTEXTPATHES), tmp);
if (!path.IsEmpty()) { paths.Add(path); }
}
CAtlArray<SubFile> ret;
GetSubFileNames(m_FileName, paths, m_xy_str_opt[DirectVobSubXyOptions::STRING_LOAD_EXT_LIST], ret);
for (size_t i = 0; i < ret.GetCount(); i++) {
if (m_frd.files.Find(ret[i].full_file_name)) {
continue;
}
CComPtr<ISubStream> pSubStream;
if (!pSubStream) {
// CAutoTiming t(TEXT("CRenderedTextSubtitle::Open"), 0);
XY_AUTO_TIMING(TEXT("CRenderedTextSubtitle::Open"));
CAutoPtr<CRenderedTextSubtitle> pRTS(new CRenderedTextSubtitle(&m_csSubLock));
if (pRTS && pRTS->Open(ret[i].full_file_name, DEFAULT_CHARSET) && pRTS->GetStreamCount() > 0) {
pSubStream = pRTS.Detach();
m_frd.files.AddTail(ret[i].full_file_name + _T(".style"));
}
}
if (!pSubStream) {
CAutoTiming t(TEXT("CVobSubFile::Open"), 0);
CAutoPtr<CVobSubFile> pVSF(new CVobSubFile(&m_csSubLock));
if (pVSF && pVSF->Open(ret[i].full_file_name) && pVSF->GetStreamCount() > 0) {
pSubStream = pVSF.Detach();
m_frd.files.AddTail(ret[i].full_file_name.Left(ret[i].full_file_name.GetLength() - 4) + _T(".sub"));
}
}
if (!pSubStream) {
CAutoTiming t(TEXT("ssf::CRenderer::Open"), 0);
CAutoPtr<ssf::CRenderer> pSSF(new ssf::CRenderer(&m_csSubLock));
if (pSSF && pSSF->Open(ret[i].full_file_name) && pSSF->GetStreamCount() > 0) {
pSubStream = pSSF.Detach();
}
}
if (pSubStream) {
m_pSubStreams.AddTail(pSubStream);
m_fIsSubStreamEmbeded.AddTail(false);
m_frd.files.AddTail(ret[i].full_file_name);
}
}
for (size_t i = 0; i < m_pTextInput.GetCount(); i++) {
if (m_pTextInput[i]->IsConnected()) {
m_pSubStreams.AddTail(m_pTextInput[i]->GetSubStream());
m_fIsSubStreamEmbeded.AddTail(true);
}
}
if (S_FALSE == put_SelectedLanguage(FindPreferedLanguage())) {
UpdateSubtitle(false); // make sure pSubPicProvider of our queue gets updated even if the stream number hasn't changed
}
m_frd.RefreshEvent.Set();
return (m_pSubStreams.GetCount() > 0);
}
void CDirectVobSubFilter::UpdateSubtitle(bool fApplyDefStyle)
{
CAutoLock cAutolock(&m_csQueueLock);
if (!m_simple_provider) { return; }
InvalidateSubtitle();
CComPtr<ISubStream> pSubStream;
if (!m_fHideSubtitles) {
int i = m_iSelectedLanguage;
for (POSITION pos = m_pSubStreams.GetHeadPosition(); i >= 0 && pos; pSubStream = NULL) {
pSubStream = m_pSubStreams.GetNext(pos);
if (i < pSubStream->GetStreamCount()) {
CAutoLock cAutoLock(&m_csSubLock);
pSubStream->SetStream(i);
break;
}
i -= pSubStream->GetStreamCount();
}
}
SetSubtitle(pSubStream, fApplyDefStyle);
}
void CDirectVobSubFilter::SetSubtitle(ISubStream* pSubStream, bool fApplyDefStyle)
{
DbgLog((LOG_TRACE, 3, "%s(%d): %s", __FILE__, __LINE__, __FUNCTION__));
DbgLog((LOG_TRACE, 3, "\tpSubStream:%x fApplyDefStyle:%d", pSubStream, (int)fApplyDefStyle));
CAutoLock cAutolock(&m_csQueueLock);
CSize playres(0, 0);
m_video_yuv_matrix_decided_by_sub = ColorConvTable::NONE;
m_video_yuv_range_decided_by_sub = ColorConvTable::RANGE_NONE;
if (pSubStream) {
CAutoLock cAutolock(&m_csSubLock);
CLSID clsid;
pSubStream->GetClassID(&clsid);
if (clsid == __uuidof(CVobSubFile)) {
CVobSubSettings* pVSS = dynamic_cast<CVobSubFile*>(pSubStream);
if (fApplyDefStyle) {
pVSS->SetAlignment(m_fOverridePlacement, m_PlacementXperc, m_PlacementYperc, 1, 1);
pVSS->m_fOnlyShowForcedSubs = m_fOnlyShowForcedVobSubs;
}
} else if (clsid == __uuidof(CVobSubStream)) {
CVobSubSettings* pVSS = dynamic_cast<CVobSubStream*>(pSubStream);
if (fApplyDefStyle) {
pVSS->SetAlignment(m_fOverridePlacement, m_PlacementXperc, m_PlacementYperc, 1, 1);
pVSS->m_fOnlyShowForcedSubs = m_fOnlyShowForcedVobSubs;
}
} else if (clsid == __uuidof(CRenderedTextSubtitle)) {
CRenderedTextSubtitle* pRTS = dynamic_cast<CRenderedTextSubtitle*>(pSubStream);
if (fApplyDefStyle || pRTS->m_fUsingAutoGeneratedDefaultStyle) {
STSStyle s = m_defStyle;
if (m_fOverridePlacement) {
s.scrAlignment = 2;
int w = pRTS->m_dstScreenSize.cx;
int h = pRTS->m_dstScreenSize.cy;
CRect tmp_rect = s.marginRect.get();
int mw = w - tmp_rect.left - tmp_rect.right;
tmp_rect.bottom = h - MulDiv(h, m_PlacementYperc, 100);
tmp_rect.left = MulDiv(w, m_PlacementXperc, 100) - mw / 2;
tmp_rect.right = w - (tmp_rect.left + mw);
s.marginRect = tmp_rect;
}
pRTS->SetDefaultStyle(s);
}
pRTS->m_ePARCompensationType = m_ePARCompensationType;
if (m_CurrentVIH2.dwPictAspectRatioX != 0 && m_CurrentVIH2.dwPictAspectRatioY != 0 && m_CurrentVIH2.bmiHeader.biWidth != 0 && m_CurrentVIH2.bmiHeader.biHeight != 0) {
pRTS->m_dPARCompensation = ((double)abs(m_CurrentVIH2.bmiHeader.biWidth) / (double)abs(m_CurrentVIH2.bmiHeader.biHeight)) /
((double)abs((long)m_CurrentVIH2.dwPictAspectRatioX) / (double)abs((long)m_CurrentVIH2.dwPictAspectRatioY));
} else {
pRTS->m_dPARCompensation = 1.00;
}
switch (pRTS->m_eYCbCrMatrix) {
case CSimpleTextSubtitle::YCbCrMatrix_BT601:
m_video_yuv_matrix_decided_by_sub = ColorConvTable::BT601;
break;
case CSimpleTextSubtitle::YCbCrMatrix_BT709:
m_video_yuv_matrix_decided_by_sub = ColorConvTable::BT709;
break;
default:
m_video_yuv_matrix_decided_by_sub = ColorConvTable::NONE;
break;
}
switch (pRTS->m_eYCbCrRange) {
case CSimpleTextSubtitle::YCbCrRange_PC:
m_video_yuv_range_decided_by_sub = ColorConvTable::RANGE_PC;
break;
case CSimpleTextSubtitle::YCbCrRange_TV:
m_video_yuv_range_decided_by_sub = ColorConvTable::RANGE_TV;
break;
default:
m_video_yuv_range_decided_by_sub = ColorConvTable::RANGE_NONE;
break;
}
pRTS->Deinit();
playres = pRTS->m_dstScreenSize;
} else if (clsid == __uuidof(CRenderedHdmvSubtitle)) {
CRenderedHdmvSubtitle* sub = dynamic_cast<CRenderedHdmvSubtitle*>(pSubStream);
CompositionObject::ColorType color_type = CompositionObject::NONE;
CompositionObject::YuvRangeType range_type = CompositionObject::RANGE_NONE;
if (m_xy_str_opt[STRING_PGS_YUV_RANGE].CompareNoCase(_T("PC")) == 0) {
range_type = CompositionObject::RANGE_PC;
} else if (m_xy_str_opt[STRING_PGS_YUV_RANGE].CompareNoCase(_T("TV")) == 0) {
range_type = CompositionObject::RANGE_TV;
}
if (m_xy_str_opt[STRING_PGS_YUV_MATRIX].CompareNoCase(_T("BT601")) == 0) {
color_type = CompositionObject::YUV_Rec601;
} else if (m_xy_str_opt[STRING_PGS_YUV_MATRIX].CompareNoCase(_T("BT709")) == 0) {
color_type = CompositionObject::YUV_Rec709;
}
m_video_yuv_matrix_decided_by_sub = (m_w > m_bt601Width || m_h > m_bt601Height) ? ColorConvTable::BT709 :
ColorConvTable::BT601;
sub->SetYuvType(color_type, range_type);
}
}
if (!fApplyDefStyle) {
int i = 0;
POSITION pos = m_pSubStreams.GetHeadPosition();
while (pos) {
CComPtr<ISubStream> pSubStream2 = m_pSubStreams.GetNext(pos);
if (pSubStream == pSubStream2) {
m_iSelectedLanguage = i + pSubStream2->GetStream();
break;
}
i += pSubStream2->GetStreamCount();
}
}
m_nSubtitleId = reinterpret_cast<DWORD_PTR>(pSubStream);
SetYuvMatrix();
XySetSize(SIZE_ASS_PLAY_RESOLUTION, playres);
if (m_simple_provider) {
m_simple_provider->SetSubPicProvider(CComQIPtr<ISubPicProviderEx>(pSubStream));
}
}
void CDirectVobSubFilter::InvalidateSubtitle(REFERENCE_TIME rtInvalidate, DWORD_PTR nSubtitleId)
{
CAutoLock cAutolock(&m_csQueueLock);
if (m_simple_provider) {
if (nSubtitleId == -1 || nSubtitleId == m_nSubtitleId) {
DbgLog((LOG_TRACE, 3, "InvalidateSubtitle::Invalidate"));
m_simple_provider->Invalidate(rtInvalidate);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////
void CDirectVobSubFilter::AddSubStream(ISubStream* pSubStream)
{
CAutoLock cAutoLock(&m_csQueueLock);
POSITION pos = m_pSubStreams.Find(pSubStream);
if (!pos) {
m_pSubStreams.AddTail(pSubStream);
m_fIsSubStreamEmbeded.AddTail(true);//todo: fix me
}
int len = m_pTextInput.GetCount();
for (size_t i = 0; i < m_pTextInput.GetCount(); i++)
if (m_pTextInput[i]->IsConnected()) { len--; }
if (len == 0) {
HRESULT hr = S_OK;
m_pTextInput.Add(new CTextInputPin(this, m_pLock, &m_csSubLock, &hr));
}
}
void CDirectVobSubFilter::RemoveSubStream(ISubStream* pSubStream)
{
CAutoLock cAutoLock(&m_csQueueLock);
POSITION pos = m_pSubStreams.GetHeadPosition();
POSITION pos2 = m_fIsSubStreamEmbeded.GetHeadPosition();
while (pos != NULL) {
if (m_pSubStreams.GetAt(pos) == pSubStream) {
m_pSubStreams.RemoveAt(pos);
m_fIsSubStreamEmbeded.RemoveAt(pos2);
break;
} else {
m_pSubStreams.GetNext(pos);
m_fIsSubStreamEmbeded.GetNext(pos2);
}
}
}
void CDirectVobSubFilter::Post_EC_OLE_EVENT(CString str, DWORD_PTR nSubtitleId)
{
if (nSubtitleId != -1 && nSubtitleId != m_nSubtitleId) {
return;
}
CComQIPtr<IMediaEventSink> pMES = m_pGraph;
if (!pMES) { return; }
CComBSTR bstr1("Text"), bstr2(" ");
str.Trim();
if (!str.IsEmpty()) { bstr2 = CStringA(str); }
pMES->Notify(EC_OLE_EVENT, (LONG_PTR)bstr1.Detach(), (LONG_PTR)bstr2.Detach());
}
////////////////////////////////////////////////////////////////
void CDirectVobSubFilter::SetupFRD(CStringArray& paths, CAtlArray<HANDLE>& handles)
{
CAutoLock cAutolock(&m_csSubLock);
for (size_t i = 2; i < handles.GetCount(); i++) {
FindCloseChangeNotification(handles[i]);
}
paths.RemoveAll();
handles.RemoveAll();
handles.Add(m_frd.EndThreadEvent);
handles.Add(m_frd.RefreshEvent);
m_frd.mtime.SetCount(m_frd.files.GetCount());
POSITION pos = m_frd.files.GetHeadPosition();
for (int i = 0; pos; i++) {
CString fn = m_frd.files.GetNext(pos);
CFileStatus status;
if (CFileGetStatus(fn, status)) {
m_frd.mtime[i] = status.m_mtime;
}
fn.Replace('\\', '/');
fn = fn.Left(fn.ReverseFind('/') + 1);
bool fFound = false;
for (int j = 0; !fFound && j < paths.GetCount(); j++) {
if (paths[j] == fn) { fFound = true; }
}
if (!fFound) {
paths.Add(fn);
HANDLE h = FindFirstChangeNotification(fn, FALSE, FILE_NOTIFY_CHANGE_LAST_WRITE);
if (h != INVALID_HANDLE_VALUE) { handles.Add(h); }
}
}
}
DWORD CDirectVobSubFilter::ThreadProc()
{
SetThreadPriority(m_hThread, THREAD_PRIORITY_LOWEST/*THREAD_PRIORITY_BELOW_NORMAL*/);
CStringArray paths;
CAtlArray<HANDLE> handles;
SetupFRD(paths, handles);
m_frd.ThreadStartedEvent.Set();
while (1) {
DWORD idx = WaitForMultipleObjects(handles.GetCount(), handles.GetData(), FALSE, INFINITE);
if (idx == (WAIT_OBJECT_0 + 0)) { // m_frd.hEndThreadEvent
break;
}
if (idx == (WAIT_OBJECT_0 + 1)) { // m_frd.hRefreshEvent
SetupFRD(paths, handles);
} else if (idx >= (WAIT_OBJECT_0 + 2) && idx < (WAIT_OBJECT_0 + handles.GetCount())) {
bool fLocked = true;
IsSubtitleReloaderLocked(&fLocked);
if (fLocked) { continue; }
if (FindNextChangeNotification(handles[idx - WAIT_OBJECT_0]) == FALSE) {
break;
}
int j = 0;
POSITION pos = m_frd.files.GetHeadPosition();
for (int i = 0; pos && j == 0; i++) {
CString fn = m_frd.files.GetNext(pos);
CFileStatus status;
if (CFileGetStatus(fn, status) && m_frd.mtime[i] != status.m_mtime) {
for (j = 0; j < 10; j++) {
if (FILE* f = _tfopen(fn, _T("rb+"))) {
fclose(f);
j = 0;
break;
} else {
Sleep(100);
j++;
}
}
}
}
if (j > 0) {
SetupFRD(paths, handles);
} else {
Sleep(500);
POSITION pos = m_frd.files.GetHeadPosition();
for (int i = 0; pos; i++) {
CFileStatus status;
if (CFileGetStatus(m_frd.files.GetNext(pos), status)
&& m_frd.mtime[i] != status.m_mtime) {
Open();
SetupFRD(paths, handles);
break;
}
}
}
} else {
break;
}
}
for (size_t i = 2; i < handles.GetCount(); i++) {
FindCloseChangeNotification(handles[i]);
}
return 0;
}
void CDirectVobSubFilter::GetInputColorspaces(ColorSpaceId* preferredOrder, UINT* count)
{
ColorSpaceOpt* color_space = NULL;
int tempCount = 0;
if (XyGetBin(BIN_INPUT_COLOR_FORMAT, reinterpret_cast<LPVOID*>(&color_space), &tempCount) == S_OK) {
*count = 0;
for (int i = 0; i < tempCount; i++) {
if (color_space[i].selected) {
preferredOrder[*count] = color_space[i].color_space;
(*count)++;
}
}
} else {
CBaseVideoFilter::GetInputColorspaces(preferredOrder, count);
}
delete[]color_space;
}
void CDirectVobSubFilter::GetOutputColorspaces(ColorSpaceId* preferredOrder, UINT* count)
{
ColorSpaceOpt* color_space = NULL;
int tempCount = 0;
if (XyGetBin(BIN_OUTPUT_COLOR_FORMAT, reinterpret_cast<LPVOID*>(&color_space), &tempCount) == S_OK) {
*count = 0;
for (int i = 0; i < tempCount; i++) {
if (color_space[i].selected) {
preferredOrder[*count] = color_space[i].color_space;
(*count)++;
}
}
} else {
CBaseVideoFilter::GetInputColorspaces(preferredOrder, count);
}
delete []color_space;
}
HRESULT CDirectVobSubFilter::GetIsEmbeddedSubStream(int iSelected, bool* fIsEmbedded)
{
CAutoLock cAutolock(&m_csQueueLock);
HRESULT hr = E_INVALIDARG;
if (!fIsEmbedded) {
return S_FALSE;
}
int i = iSelected;
*fIsEmbedded = false;
POSITION pos = m_pSubStreams.GetHeadPosition();
POSITION pos2 = m_fIsSubStreamEmbeded.GetHeadPosition();
while (i >= 0 && pos) {
CComPtr<ISubStream> pSubStream = m_pSubStreams.GetNext(pos);
bool isEmbedded = m_fIsSubStreamEmbeded.GetNext(pos2);
if (i < pSubStream->GetStreamCount()) {
hr = NOERROR;
*fIsEmbedded = isEmbedded;
break;
}
i -= pSubStream->GetStreamCount();
}
return hr;
}
void CDirectVobSubFilter::SetYuvMatrix()
{
ColorConvTable::YuvMatrixType yuv_matrix = ColorConvTable::BT601;
ColorConvTable::YuvRangeType yuv_range = ColorConvTable::RANGE_TV;
DXVA2_ExtendedFormat extformat;
extformat.value = m_cf;
if (m_xy_int_opt[INT_COLOR_SPACE] == CDirectVobSub::YuvMatrix_AUTO) {
if (m_video_yuv_matrix_decided_by_sub != ColorConvTable::NONE) {
yuv_matrix = m_video_yuv_matrix_decided_by_sub;
} else {
yuv_matrix = (extformat.VideoTransferMatrix == DXVA2_VideoTransferMatrix_BT709 ||
extformat.VideoTransferMatrix == DXVA2_VideoTransferMatrix_SMPTE240M ||
m_xy_size_opt[SIZE_ORIGINAL_VIDEO].cx > m_bt601Width ||
m_xy_size_opt[SIZE_ORIGINAL_VIDEO].cy > m_bt601Height) ? ColorConvTable::BT709 : ColorConvTable::BT601;
}
} else {
switch (m_xy_int_opt[INT_COLOR_SPACE]) {
case CDirectVobSub::BT_601:
yuv_matrix = ColorConvTable::BT601;
break;
case CDirectVobSub::BT_709:
yuv_matrix = ColorConvTable::BT709;
break;
case CDirectVobSub::GUESS:
default:
yuv_matrix = (m_w > m_bt601Width || m_h > m_bt601Height) ? ColorConvTable::BT709 : ColorConvTable::BT601;
break;
}
}
if (m_xy_int_opt[INT_YUV_RANGE] == CDirectVobSub::YuvRange_Auto) {
if (m_video_yuv_range_decided_by_sub != ColorConvTable::RANGE_NONE) {
yuv_range = m_video_yuv_range_decided_by_sub;
} else {
yuv_range = (extformat.NominalRange == DXVA2_NominalRange_0_255) ? ColorConvTable::RANGE_PC : ColorConvTable::RANGE_TV;
}
} else {
switch (m_xy_int_opt[INT_YUV_RANGE]) {
case CDirectVobSub::YuvRange_TV:
yuv_range = ColorConvTable::RANGE_TV;
break;
case CDirectVobSub::YuvRange_PC:
yuv_range = ColorConvTable::RANGE_PC;
break;
}
}
ColorConvTable::SetDefaultConvType(yuv_matrix, yuv_range);
}
// IDirectVobSubXy
STDMETHODIMP CDirectVobSubFilter::XySetBool(int field, bool value)
{
CAutoLock cAutolock(&m_csQueueLock);
HRESULT hr = CDirectVobSub::XySetBool(field, value);
if (hr != NOERROR) {
return hr;
}
switch (field) {
case DirectVobSubXyOptions::BOOL_FOLLOW_UPSTREAM_PREFERRED_ORDER:
m_donot_follow_upstream_preferred_order = !m_xy_bool_opt[BOOL_FOLLOW_UPSTREAM_PREFERRED_ORDER];
break;
default:
hr = E_NOTIMPL;
break;
}
return hr;
}
STDMETHODIMP CDirectVobSubFilter::XySetInt(int field, int value)
{
CAutoLock cAutolock(&m_csQueueLock);
HRESULT hr = CDirectVobSub::XySetInt(field, value);
if (hr != NOERROR) {
return hr;
}
switch (field) {
case DirectVobSubXyOptions::INT_COLOR_SPACE:
case DirectVobSubXyOptions::INT_YUV_RANGE:
SetYuvMatrix();
break;
case DirectVobSubXyOptions::INT_OVERLAY_CACHE_MAX_ITEM_NUM:
CacheManager::GetOverlayMruCache()->SetMaxItemNum(m_xy_int_opt[field]);
break;
case DirectVobSubXyOptions::INT_SCAN_LINE_DATA_CACHE_MAX_ITEM_NUM:
CacheManager::GetScanLineData2MruCache()->SetMaxItemNum(m_xy_int_opt[field]);
break;
case DirectVobSubXyOptions::INT_PATH_DATA_CACHE_MAX_ITEM_NUM:
CacheManager::GetPathDataMruCache()->SetMaxItemNum(m_xy_int_opt[field]);
break;
case DirectVobSubXyOptions::INT_OVERLAY_NO_BLUR_CACHE_MAX_ITEM_NUM:
CacheManager::GetOverlayNoBlurMruCache()->SetMaxItemNum(m_xy_int_opt[field]);
break;
case DirectVobSubXyOptions::INT_BITMAP_MRU_CACHE_ITEM_NUM:
CacheManager::GetBitmapMruCache()->SetMaxItemNum(m_xy_int_opt[field]);
break;
case DirectVobSubXyOptions::INT_CLIPPER_MRU_CACHE_ITEM_NUM:
CacheManager::GetClipperAlphaMaskMruCache()->SetMaxItemNum(m_xy_int_opt[field]);
break;
case DirectVobSubXyOptions::INT_TEXT_INFO_CACHE_ITEM_NUM:
CacheManager::GetTextInfoCache()->SetMaxItemNum(m_xy_int_opt[field]);
break;
case DirectVobSubXyOptions::INT_ASS_TAG_LIST_CACHE_ITEM_NUM:
CacheManager::GetAssTagListMruCache()->SetMaxItemNum(m_xy_int_opt[field]);
break;
case DirectVobSubXyOptions::INT_SUBPIXEL_POS_LEVEL:
SubpixelPositionControler::GetGlobalControler().SetSubpixelLevel(static_cast<SubpixelPositionControler::SUBPIXEL_LEVEL>(m_xy_int_opt[field]));
break;
default:
hr = E_NOTIMPL;
break;
}
return hr;
}
//
// OSD
//
void CDirectVobSubFilter::ZeroObj4OSD()
{
m_hdc = 0;
m_hbm = 0;
m_hfont = 0;
{
LOGFONT lf;
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfOutPrecision = OUT_CHARACTER_PRECIS;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfQuality = ANTIALIASED_QUALITY;
HDC hdc = GetDC(NULL);
lf.lfHeight = 28;
//MulDiv(20, GetDeviceCaps(hdc, LOGPIXELSY), 54);
ReleaseDC(NULL, hdc);
lf.lfWeight = FW_BOLD;
_tcscpy(lf.lfFaceName, _T("Arial"));
m_hfont = CreateFontIndirect(&lf);
}
}
void CDirectVobSubFilter::DeleteObj4OSD()
{
if (m_hfont) {DeleteObject(m_hfont); m_hfont = 0;}
if (m_hbm) {DeleteObject(m_hbm); m_hbm = 0;}
if (m_hdc) {DeleteObject(m_hdc); m_hdc = 0;}
}
void CDirectVobSubFilter::InitObj4OSD()
{
if (m_hbm) {DeleteObject(m_hbm); m_hbm = NULL;}
if (m_hdc) {DeleteDC(m_hdc); m_hdc = NULL;}
struct {BITMAPINFOHEADER bih; DWORD mask[3];} b = {{sizeof(BITMAPINFOHEADER), m_w, -(int)m_h, 1, 32, BI_BITFIELDS, 0, 0, 0, 0, 0}, 0xFF0000, 0x00FF00, 0x0000FF};
m_hdc = CreateCompatibleDC(NULL);
m_hbm = CreateDIBSection(m_hdc, (BITMAPINFO*)&b, DIB_RGB_COLORS, NULL, NULL, 0);
BITMAP bm;
GetObject(m_hbm, sizeof(bm), &bm);
memsetd(bm.bmBits, 0xFF000000, bm.bmHeight * bm.bmWidthBytes);
}
| kenygia/xy-vsfilter | src/filters/transform/vsfilter/DirectVobSubFilter.cpp | C++ | gpl-2.0 | 79,462 |
/**
@file elasticityJac.C
@author Rahul Sampath, rahul.sampath@gmail.com
*/
#include "petscmat.h"
#include "omg/omg.h"
#include "oda/oda.h"
#include "oda/odaUtils.h"
#include "elasticityJac.h"
#ifdef PETSC_USE_LOG
extern int elasticityDiagEvent;
extern int elasticityMultEvent;
extern int elasticityFinestDiagEvent;
extern int elasticityFinestMultEvent;
#endif
extern double**** LaplacianType2Stencil;
extern double**** GradDivType2Stencil;
void getActiveStateAndActiveCommForKSP_Shell_Elas(Mat mat,
bool & activeState, MPI_Comm & activeComm) {
PetscTruth isshell;
PetscTypeCompare((PetscObject)mat, MATSHELL, &isshell);
assert(isshell);
ot::DAMG damg;
MatShellGetContext(mat, (void**)(&damg));
ot::DA* da = damg->da;
activeState = da->iAmActive();
activeComm = da->getCommActive();
}
void getPrivateMatricesForKSP_Shell_Elas(Mat mat,
Mat *AmatPrivate, Mat *PmatPrivate, MatStructure* pFlag) {
PetscTruth isshell;
PetscTypeCompare((PetscObject)mat, MATSHELL, &isshell);
assert(isshell);
ot::DAMG damg;
MatShellGetContext(mat, (void**)(&damg));
ElasticityData* data = (static_cast<ElasticityData*>(damg->user));
*AmatPrivate = data->Jmat_private;
*PmatPrivate = data->Jmat_private;
*pFlag = DIFFERENT_NONZERO_PATTERN;
}
#define ELASTICITY_ELEM_DIAG_BLOCK {\
unsigned int idx = da->curr();\
unsigned int lev = da->getLevel(idx);\
double h = hFac*(1u << (maxD - lev));\
double fac = h/2.0;\
unsigned int indices[8];\
da->getNodeIndices(indices);\
unsigned char childNum = da->getChildNumber();\
unsigned char hnMask = da->getHangingNodeIndex(idx);\
unsigned char elemType = 0;\
GET_ETYPE_BLOCK(elemType,hnMask,childNum)\
for(int k = 0; k < 8; k++) {\
if(bdyArr[indices[k]]) {\
/*Dirichlet Node*/\
for(int dof = 0; dof < 3; dof++) {\
diagArr[(3*indices[k])+dof] = 1.0;\
} /*end dof*/\
} else { \
for(int dof = 0; dof < 3; dof++) {\
diagArr[(3*indices[k])+dof] += (fac*(\
(mu*LaplacianType2Stencil[childNum][elemType][k][k])\
+ ((mu+lambda)*GradDivType2Stencil[childNum][elemType][(3*k) + dof][(3*k) + dof])));\
} /*end dof*/\
}\
} /*end k*/\
}
#define ELASTICITY_DIAG_BLOCK {\
ot::DA* da = damg->da;\
ElasticityData* data = (static_cast<ElasticityData*>(damg->user));\
iC(VecZeroEntries(diag));\
PetscScalar *diagArr = NULL;\
unsigned char* bdyArr = data->bdyArr;\
double mu = data->mu;\
double lambda = data->lambda;\
unsigned int maxD;\
double hFac;\
/*Nodal,Non-Ghosted,Write,3 dof*/\
da->vecGetBuffer(diag,diagArr,false,false,false,3);\
if(da->iAmActive()) {\
maxD = (da->getMaxDepth());\
hFac = 1.0/((double)(1u << (maxD-1)));\
/*Loop through All Elements including ghosted*/\
for(da->init<ot::DA_FLAGS::ALL>();\
da->curr() < da->end<ot::DA_FLAGS::ALL>();\
da->next<ot::DA_FLAGS::ALL>()) {\
ELASTICITY_ELEM_DIAG_BLOCK \
} /*end i*/\
} /*end if active*/\
da->vecRestoreBuffer(diag,diagArr,false,false,false,3);\
/*2 IOP = 1 FLOP. Loop counters are included too.*/\
PetscLogFlops(235*(da->getGhostedElementSize()));\
}
PetscErrorCode ElasticityMatGetDiagonal(Mat J, Vec diag) {
PetscFunctionBegin;
PetscLogEventBegin(elasticityDiagEvent,diag,0,0,0);
ot::DAMG damg;
iC(MatShellGetContext(J, (void**)(&damg)));
bool isFinestLevel = (damg->nlevels == 1);
if(isFinestLevel) {
PetscLogEventBegin(elasticityFinestDiagEvent,diag,0,0,0);
}
ELASTICITY_DIAG_BLOCK
if(isFinestLevel) {
PetscLogEventEnd(elasticityFinestDiagEvent,diag,0,0,0);
}
PetscLogEventEnd(elasticityDiagEvent,diag,0,0,0);
PetscFunctionReturn(0);
}
#undef ELASTICITY_DIAG_BLOCK
#undef ELASTICITY_ELEM_DIAG_BLOCK
#define ELASTICITY_ELEM_MULT_BLOCK {\
unsigned int idx = da->curr();\
unsigned int lev = da->getLevel(idx);\
double h = hFac*(1u << (maxD - lev));\
double fac = h/2.0;\
unsigned int indices[8];\
da->getNodeIndices(indices);\
unsigned char childNum = da->getChildNumber();\
unsigned char hnMask = da->getHangingNodeIndex(idx);\
unsigned char elemType = 0;\
GET_ETYPE_BLOCK(elemType,hnMask,childNum)\
for(int k = 0;k < 8;k++) {\
if(bdyArr[indices[k]]) {\
/*Dirichlet Node Row*/\
for(int dof = 0; dof < 3; dof++) {\
outArr[(3*indices[k]) + dof] = inArr[(3*indices[k]) + dof];\
}/*end for dof*/\
} else {\
for(int j=0;j<8;j++) {\
/*Avoid Dirichlet Node Columns*/\
if(!(bdyArr[indices[j]])) {\
for(int dof = 0; dof < 3; dof++) {\
outArr[(3*indices[k]) + dof] += (mu*fac*LaplacianType2Stencil[childNum][elemType][k][j]\
*inArr[(3*indices[j]) + dof]);\
}/*end for dof*/\
for(int dofOut = 0; dofOut < 3; dofOut++) {\
for(int dofIn = 0; dofIn < 3; dofIn++) {\
outArr[(3*indices[k]) + dofOut] += ((mu+lambda)*fac*\
(GradDivType2Stencil[childNum][elemType][(3*k) + dofOut][(3*j) + dofIn])\
*inArr[(3*indices[j]) + dofIn]);\
}/*end for dofIn*/\
}/*end for dofOut*/\
}\
}/*end for j*/\
}\
}/*end for k*/\
}
#define ELASTICITY_MULT_BLOCK {\
ot::DA* da = damg->da;\
ElasticityData* data = (static_cast<ElasticityData*>(damg->user));\
iC(VecZeroEntries(out));\
unsigned int maxD;\
double hFac;\
if(da->iAmActive()) {\
maxD = da->getMaxDepth();\
hFac = 1.0/((double)(1u << (maxD-1)));\
}\
PetscScalar *outArr=NULL;\
PetscScalar *inArr=NULL;\
unsigned char* bdyArr = data->bdyArr;\
double mu = data->mu;\
double lambda = data->lambda;\
/*Nodal,Non-Ghosted,Read,3 dof*/\
da->vecGetBuffer(in,inArr,false,false,true,3);\
/*Nodal,Non-Ghosted,Write,3 dof*/\
da->vecGetBuffer(out,outArr,false,false,false,3);\
if(da->iAmActive()) {\
da->ReadFromGhostsBegin<PetscScalar>(inArr,3);\
/*Loop through All Independent Elements*/\
for(da->init<ot::DA_FLAGS::INDEPENDENT>();\
da->curr() < da->end<ot::DA_FLAGS::INDEPENDENT>();\
da->next<ot::DA_FLAGS::INDEPENDENT>() ) {\
ELASTICITY_ELEM_MULT_BLOCK \
} /*end independent*/\
da->ReadFromGhostsEnd<PetscScalar>(inArr);\
/*Loop through All Dependent Elements,*/\
/*i.e. Elements which have atleast one*/\
/*vertex owned by this processor and at least one*/\
/*vertex not owned by this processor.*/\
for(da->init<ot::DA_FLAGS::DEPENDENT>();\
da->curr() < da->end<ot::DA_FLAGS::DEPENDENT>();\
da->next<ot::DA_FLAGS::DEPENDENT>() ) {\
ELASTICITY_ELEM_MULT_BLOCK \
} /*end loop for dependent elems*/\
} /*end if active*/\
da->vecRestoreBuffer(in,inArr,false,false,true,3);\
da->vecRestoreBuffer(out,outArr,false,false,false,3);\
/*2 IOP = 1 FLOP. Loop counters are included too.*/\
PetscLogFlops(6855*(da->getGhostedElementSize()));\
}
PetscErrorCode ElasticityMatMult(Mat J, Vec in, Vec out)
{
PetscFunctionBegin;
PetscLogEventBegin(elasticityMultEvent,in,out,0,0);
ot::DAMG damg;
iC(MatShellGetContext(J, (void**)(&damg)));
bool isFinestLevel = (damg->nlevels == 1);
if(isFinestLevel) {
PetscLogEventBegin(elasticityFinestMultEvent,in,out,0,0);
}
ELASTICITY_MULT_BLOCK
if(isFinestLevel) {
PetscLogEventEnd(elasticityFinestMultEvent,in,out,0,0);
}
PetscLogEventEnd(elasticityMultEvent,in,out,0,0);
PetscFunctionReturn(0);
}
#undef ELASTICITY_ELEM_MULT_BLOCK
#undef ELASTICITY_MULT_BLOCK
#define BUILD_FULL_ELASTICITY_ELEM_ADD_BLOCK {\
unsigned int idx = da->curr();\
unsigned int lev = da->getLevel(idx);\
double h = hFac*(1u << (maxD - lev));\
double fac = h/2.0;\
unsigned int indices[8];\
da->getNodeIndices(indices);\
unsigned char childNum = da->getChildNumber();\
unsigned char hnMask = da->getHangingNodeIndex(idx);\
unsigned char elemType = 0;\
GET_ETYPE_BLOCK(elemType,hnMask,childNum)\
for(int k = 0;k < 8;k++) {\
/*Avoid Dirichlet Node Rows during ADD_VALUES loop.*/\
/*Need a separate INSERT_VALUES loop for those*/\
if(!(bdyArr[indices[k]])) {\
for(int j=0;j<8;j++) {\
if(!(bdyArr[indices[j]])) {\
for(int dof = 0; dof < 3; dof++) {\
ot::MatRecord currRec;\
currRec.rowIdx = indices[k];\
currRec.colIdx = indices[j];\
currRec.rowDim = dof;\
currRec.colDim = dof;\
currRec.val = (mu*fac*\
LaplacianType2Stencil[childNum][elemType][k][j]);\
records.push_back(currRec);\
} /*end for dof*/\
for(int dofOut = 0; dofOut < 3; dofOut++) {\
for(int dofIn = 0; dofIn < 3; dofIn++) {\
ot::MatRecord currRec;\
currRec.rowIdx = indices[k];\
currRec.colIdx = indices[j];\
currRec.rowDim = dofOut;\
currRec.colDim = dofIn;\
currRec.val = ((mu+lambda)*fac*\
GradDivType2Stencil[childNum][elemType][(3*k)+dofOut][(3*j)+dofIn]);\
records.push_back(currRec);\
} /*end for dofIn*/\
} /*end for dofOut*/\
}\
} /*end for j*/\
}\
} /*end for k*/\
if(records.size() > 1000) {\
/*records will be cleared inside the function*/\
da->setValuesInMatrix(B, records, 3, ADD_VALUES);\
}\
}
#define BUILD_FULL_ELASTICITY_ELEM_INSERT_BLOCK {\
unsigned int idx = da->curr();\
unsigned int lev = da->getLevel(idx);\
double h = hFac*(1u << (maxD - lev));\
double fac = h/2.0;\
unsigned int indices[8];\
da->getNodeIndices(indices);\
unsigned char childNum = da->getChildNumber();\
unsigned char hnMask = da->getHangingNodeIndex(idx);\
unsigned char elemType = 0;\
GET_ETYPE_BLOCK(elemType,hnMask,childNum)\
for(int k = 0;k < 8;k++) {\
/*Insert values for Dirichlet Node Rows only.*/\
if(bdyArr[indices[k]]) {\
for(int dof = 0; dof < 3; dof++) {\
ot::MatRecord currRec;\
currRec.rowIdx = indices[k];\
currRec.colIdx = indices[k];\
currRec.rowDim = dof;\
currRec.colDim = dof;\
currRec.val = 1.0;\
records.push_back(currRec);\
} /*end for dof*/\
}\
} /*end for k*/\
if(records.size() > 1000) {\
/*records will be cleared inside the function*/\
da->setValuesInMatrix(B, records, 3, INSERT_VALUES);\
}\
}
#define BUILD_FULL_ELASTICITY_BLOCK {\
ot::DA* da = damg->da;\
MatZeroEntries(B);\
std::vector<ot::MatRecord> records;\
unsigned int maxD;\
double hFac;\
if(da->iAmActive()) {\
maxD = da->getMaxDepth();\
hFac = 1.0/((double)(1u << (maxD-1)));\
}\
unsigned char* bdyArr = data->bdyArr;\
double mu = data->mu;\
double lambda = data->lambda;\
if(da->iAmActive()) {\
for(da->init<ot::DA_FLAGS::WRITABLE>();\
da->curr() < da->end<ot::DA_FLAGS::WRITABLE>();\
da->next<ot::DA_FLAGS::WRITABLE>()) {\
BUILD_FULL_ELASTICITY_ELEM_ADD_BLOCK \
} /*end writable*/\
} /*end if active*/\
da->setValuesInMatrix(B, records, 3, ADD_VALUES);\
MatAssemblyBegin(B, MAT_FLUSH_ASSEMBLY);\
MatAssemblyEnd(B, MAT_FLUSH_ASSEMBLY);\
if(da->iAmActive()) {\
for(da->init<ot::DA_FLAGS::WRITABLE>();\
da->curr() < da->end<ot::DA_FLAGS::WRITABLE>();\
da->next<ot::DA_FLAGS::WRITABLE>()) {\
BUILD_FULL_ELASTICITY_ELEM_INSERT_BLOCK \
} /*end writable*/\
} /*end if active*/\
da->setValuesInMatrix(B, records, 3, INSERT_VALUES);\
MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY);\
MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY);\
if(data->bdyArr) {\
delete [] (data->bdyArr);\
data->bdyArr = NULL;\
}\
}
PetscErrorCode ComputeElasticityMat(ot::DAMG damg, Mat J, Mat B) {
//For matShells nothing to be done here.
PetscFunctionBegin;
ElasticityData* data = (static_cast<ElasticityData*>(damg->user));
PetscTruth isshell;
PetscTypeCompare((PetscObject)B, MATSHELL, &isshell);
assert(J == B);
if(isshell) {
if( data->Jmat_private == NULL ) {
//inactive processors will return
PetscFunctionReturn(0);
} else {
J = data->Jmat_private;
B = data->Jmat_private;
}
}
PetscTypeCompare((PetscObject)B, MATSHELL, &isshell);
if(isshell) {
PetscFunctionReturn(0);
}
BUILD_FULL_ELASTICITY_BLOCK
PetscFunctionReturn(0);
}
#undef BUILD_FULL_ELASTICITY_ELEM_ADD_BLOCK
#undef BUILD_FULL_ELASTICITY_ELEM_INSERT_BLOCK
#undef BUILD_FULL_ELASTICITY_BLOCK
void SetElasticityContexts(ot::DAMG* damg) {
int nlevels = damg[0]->nlevels; //number of multigrid levels
PetscReal muVal = 1.0;
PetscReal lambdaVal = 1.0;
PetscTruth optFound;
PetscOptionsGetReal("elasticity","-_mu", &muVal, &optFound);
PetscOptionsGetReal("elasticity","-_lambda", &lambdaVal, &optFound);
for(int i = 0; i < nlevels; i++) {
ElasticityData* ctx= new ElasticityData;
ctx->mu = muVal;
ctx->lambda = lambdaVal;
ctx->bdyArr = NULL;
ctx->Jmat_private = NULL;
ctx->inTmp = NULL;
ctx->outTmp = NULL;
std::vector<unsigned char> tmpBdyFlags;
std::vector<unsigned char> tmpBdyFlagsAux;
unsigned char* bdyArrAux = NULL;
//This will create a nodal, non-ghosted, 1 dof array
assignBoundaryFlags(damg[i]->da, tmpBdyFlags);
((damg[i])->da)->vecGetBuffer<unsigned char>(tmpBdyFlags, ctx->bdyArr, false, false, true, 1);
if(damg[i]->da->iAmActive()) {
((damg[i])->da)->ReadFromGhostsBegin<unsigned char>(ctx->bdyArr, 1);
}
if(damg[i]->da_aux) {
assignBoundaryFlags( damg[i]->da_aux, tmpBdyFlagsAux);
((damg[i])->da_aux)->vecGetBuffer<unsigned char>(tmpBdyFlagsAux, bdyArrAux,
false, false, true, 1);
if(damg[i]->da_aux->iAmActive()) {
((damg[i])->da_aux)->ReadFromGhostsBegin<unsigned char>(bdyArrAux, 1);
}
}
tmpBdyFlags.clear();
tmpBdyFlagsAux.clear();
if(damg[i]->da->iAmActive()) {
((damg[i])->da)->ReadFromGhostsEnd<unsigned char>(ctx->bdyArr);
}
if((damg[i])->da_aux) {
if(damg[i]->da_aux->iAmActive()) {
((damg[i])->da_aux)->ReadFromGhostsEnd<unsigned char>(bdyArrAux);
}
}
for(int loopCtr = 0; loopCtr < 2; loopCtr++) {
ot::DA* da = NULL;
unsigned char* suppressedDOFptr = NULL;
unsigned char* bdyArrPtr = NULL;
if(loopCtr == 0) {
da = damg[i]->da;
suppressedDOFptr = damg[i]->suppressedDOF;
bdyArrPtr = ctx->bdyArr;
} else {
da = damg[i]->da_aux;
suppressedDOFptr = damg[i]->suppressedDOFaux;
bdyArrPtr = bdyArrAux;
}
if(da) {
if(da->iAmActive()) {
for(da->init<ot::DA_FLAGS::ALL>();
da->curr() < da->end<ot::DA_FLAGS::ALL>();
da->next<ot::DA_FLAGS::ALL>()) {
unsigned int indices[8];
da->getNodeIndices(indices);
for(unsigned int k = 0; k < 8; k++) {
for(unsigned int d = 0; d < 3; d++) {
suppressedDOFptr[(3*indices[k]) + d] = bdyArrPtr[indices[k]];
}
}
}
}
}
}
if(bdyArrAux) {
delete [] bdyArrAux;
bdyArrAux = NULL;
}
(damg[i])->user = ctx;
}//end for i
}//end fn.
void DestroyElasticityContexts(ot::DAMG* damg) {
int nlevels = damg[0]->nlevels; //number of multigrid levels
for(int i = 0; i < nlevels; i++) {
ElasticityData* ctx = (static_cast<ElasticityData*>(damg[i]->user));
if(ctx->bdyArr) {
delete [] (ctx->bdyArr);
ctx->bdyArr = NULL;
}
if(ctx->Jmat_private) {
MatDestroy(ctx->Jmat_private);
ctx->Jmat_private = NULL;
}
if(ctx->inTmp) {
VecDestroy(ctx->inTmp);
ctx->inTmp = NULL;
}
if(ctx->outTmp) {
VecDestroy(ctx->outTmp);
ctx->outTmp = NULL;
}
delete ctx;
ctx = NULL;
}
}//end fn.
PetscErrorCode ElasticityShellMatMult(Mat J, Vec in, Vec out)
{
PetscFunctionBegin;
ot::DAMG damg;
iC(MatShellGetContext(J, (void**)(&damg)));
ElasticityData* ctx = (static_cast<ElasticityData*>(damg->user));
if(damg->da->iAmActive()) {
PetscScalar* inArray;
PetscScalar* outArray;
VecGetArray(in, &inArray);
VecGetArray(out, &outArray);
VecPlaceArray(ctx->inTmp, inArray);
VecPlaceArray(ctx->outTmp, outArray);
MatMult(ctx->Jmat_private, ctx->inTmp, ctx->outTmp);
VecResetArray(ctx->inTmp);
VecResetArray(ctx->outTmp);
VecRestoreArray(in, &inArray);
VecRestoreArray(out, &outArray);
}
PetscFunctionReturn(0);
}
PetscErrorCode CreateElasticityMat(ot::DAMG damg, Mat *jac) {
PetscFunctionBegin;
PetscInt buildFullCoarseMat;
PetscInt buildFullMatAll;
int totalLevels;
PetscTruth flg;
PetscOptionsGetInt(PETSC_NULL,"-buildFullCoarseMat",&buildFullCoarseMat,&flg);
PetscOptionsGetInt(PETSC_NULL,"-buildFullMatAll",&buildFullMatAll,&flg);
if(buildFullMatAll) {
buildFullCoarseMat = 1;
}
totalLevels = damg->totalLevels;
ot::DA* da = damg->da;
int myRank;
MPI_Comm_rank(da->getComm(), &myRank);
if( totalLevels == damg->nlevels ) {
//This is the coarsest.
if( (!myRank) && (buildFullCoarseMat) ) {
std::cout<<"Building Full elasticity Mat at the coarsest level."<<std::endl;
}
char matType[30];
if(buildFullCoarseMat) {
if(!(da->computedLocalToGlobal())) {
da->computeLocalToGlobalMappings();
}
PetscTruth typeFound;
PetscOptionsGetString(PETSC_NULL,"-fullJacMatType",matType,30,&typeFound);
if(!typeFound) {
std::cout<<"I need a MatType for the full matrix!"<<std::endl;
assert(false);
}
}
bool requirePrivateMats = (da->getNpesActive() != da->getNpesAll());
if(requirePrivateMats) {
unsigned int m,n;
m=n=(3*(da->getNodeSize()));
ElasticityData* ctx = (static_cast<ElasticityData*>(damg->user));
if(da->iAmActive()) {
if(buildFullCoarseMat) {
da->createActiveMatrix(ctx->Jmat_private, matType, 3);
} else {
MatCreateShell(da->getCommActive(), m ,n, PETSC_DETERMINE,
PETSC_DETERMINE, damg, (&(ctx->Jmat_private)));
MatShellSetOperation(ctx->Jmat_private, MATOP_MULT,
(void (*)(void)) ElasticityMatMult);
MatShellSetOperation(ctx->Jmat_private, MATOP_GET_DIAGONAL,
(void (*)(void)) ElasticityMatGetDiagonal);
MatShellSetOperation(ctx->Jmat_private, MATOP_DESTROY,
(void (*)(void)) ElasticityMatDestroy);
}
MatGetVecs(ctx->Jmat_private, &(ctx->inTmp), &(ctx->outTmp));
} else {
ctx->Jmat_private = NULL;
}
//Need a MATShell wrapper anyway. But, the matvecs are not implemented for
//this matrix. However, a matmult function is required for compute
//residuals
MatCreateShell(damg->comm, m ,n, PETSC_DETERMINE, PETSC_DETERMINE, damg, jac);
MatShellSetOperation(*jac ,MATOP_DESTROY, (void (*)(void)) ElasticityMatDestroy);
MatShellSetOperation(*jac, MATOP_MULT, (void (*)(void)) ElasticityShellMatMult);
} else {
if(buildFullCoarseMat) {
da->createMatrix(*jac, matType, 3);
} else {
unsigned int m,n;
m=n=(3*(da->getNodeSize()));
MatCreateShell(damg->comm, m ,n, PETSC_DETERMINE, PETSC_DETERMINE, damg, jac);
MatShellSetOperation(*jac ,MATOP_MULT, (void (*)(void)) ElasticityMatMult);
MatShellSetOperation(*jac ,MATOP_GET_DIAGONAL, (void (*)(void)) ElasticityMatGetDiagonal);
MatShellSetOperation(*jac ,MATOP_DESTROY, (void (*)(void)) ElasticityMatDestroy);
}
}
if( (!myRank) && (buildFullCoarseMat) ) {
std::cout<<"Finished Building Full elasticity Mat at the coarsest level."<<std::endl;
}
}else {
//This is not the coarsest level. No need to bother with KSP_Shell
if(buildFullMatAll) {
if( !myRank ) {
std::cout<<"Building Full elasticity Mat at level: "<<(damg->nlevels)<<std::endl;
}
if(!(da->computedLocalToGlobal())) {
da->computeLocalToGlobalMappings();
}
char matType[30];
PetscTruth typeFound;
PetscOptionsGetString(PETSC_NULL,"-fullJacMatType",matType,30,&typeFound);
if(!typeFound) {
std::cout<<"I need a MatType for the full matrix!"<<std::endl;
assert(false);
}
da->createMatrix(*jac, matType, 3);
if(!myRank) {
std::cout<<"Finished Building Full elasticity Mat at level: "<<(damg->nlevels)<<std::endl;
}
} else {
//Create a MATShell
//The size this processor owns ( without ghosts).
unsigned int m,n;
m=n=(3*(da->getNodeSize()));
MatCreateShell(damg->comm, m ,n, PETSC_DETERMINE, PETSC_DETERMINE, damg, jac);
MatShellSetOperation(*jac ,MATOP_MULT, (void (*)(void)) ElasticityMatMult);
MatShellSetOperation(*jac ,MATOP_GET_DIAGONAL, (void (*)(void)) ElasticityMatGetDiagonal);
MatShellSetOperation(*jac ,MATOP_DESTROY, (void (*)(void)) ElasticityMatDestroy);
}
}
PetscFunctionReturn(0);
}//end fn.
PetscErrorCode ElasticityMatDestroy(Mat J) {
PetscFunctionBegin;
//Nothing to be done here. No new pointers were created during creation.
PetscFunctionReturn(0);
}
//Functions required in order to use BlockDiag PC
void computeInvBlockDiagEntriesForElasticityMat(Mat J, double **invBlockDiagEntries) {
ot::DAMG damg;
MatShellGetContext(J, (void**)(&damg));
ElasticityData* data = (static_cast<ElasticityData*>(damg->user));
ot::DA* da = damg->da;
unsigned int dof = 3;
unsigned int nodeSize = damg->da->getNodeSize();
//Initialize
for(int i = 0; i < (dof*nodeSize); i++ ) {
for(int j = 0; j < dof; j++) {
invBlockDiagEntries[i][j] = 0.0;
}//end for j
}//end for i
unsigned char* bdyArr = data->bdyArr;
double mu = data->mu;
double lambda = data->lambda;
unsigned int maxD;
double hFac;
std::vector<double> blockDiagVec;
da->createVector<double>(blockDiagVec, false, false, 9);
for(unsigned int i = 0; i < blockDiagVec.size(); i++) {
blockDiagVec[i] = 0.0;
}
double *blockDiagArr;
/*Nodal,Non-Ghosted,Write,9 dof*/
da->vecGetBuffer<double>(blockDiagVec, blockDiagArr, false, false, false, 9);
if(da->iAmActive()) {
maxD = (da->getMaxDepth());
hFac = 1.0/((double)(1u << (maxD-1)));
/*Loop through All Elements including ghosted*/
for(da->init<ot::DA_FLAGS::ALL>();
da->curr() < da->end<ot::DA_FLAGS::ALL>();
da->next<ot::DA_FLAGS::ALL>()) {
unsigned int idx = da->curr();
unsigned int lev = da->getLevel(idx);
double h = hFac*(1u << (maxD - lev));
double fac = h/2.0;
unsigned int indices[8];
da->getNodeIndices(indices);
unsigned char childNum = da->getChildNumber();
unsigned char hnMask = da->getHangingNodeIndex(idx);
unsigned char elemType = 0;
GET_ETYPE_BLOCK(elemType,hnMask,childNum)
for(int k = 0; k < 8; k++) {
if(bdyArr[indices[k]]) {
/*Dirichlet Node*/
for(int dof = 0; dof < 3; dof++) {
blockDiagArr[(9*indices[k]) + (3*dof) + dof] = 1.0;
} /*end dof*/
} else {
for(int dof = 0; dof < 3; dof++) {
blockDiagArr[(9*indices[k])+(3*dof) + dof] += (mu*fac*
LaplacianType2Stencil[childNum][elemType][k][k]);
} /*end dof*/
for(int dofOut = 0; dofOut < 3; dofOut++) {
for(int dofIn = 0; dofIn < 3; dofIn++) {
blockDiagArr[(9*indices[k]) + (3*dofOut) + dofIn] +=
((mu+lambda)*fac*
GradDivType2Stencil[childNum][elemType][(3*k) + dofOut][(3*k) + dofIn]);
}/*end dofIn*/
} /*end dofOut*/
}
} /*end k*/
} /*end i*/
} /*end if active*/
da->vecRestoreBuffer<double>(blockDiagVec,blockDiagArr,false,false,false,9);
for(unsigned int i = 0; i < nodeSize; i++) {
double a11 = blockDiagVec[(9*i)];
double a12 = blockDiagVec[(9*i)+1];
double a13 = blockDiagVec[(9*i)+2];
double a21 = blockDiagVec[(9*i)+3];
double a22 = blockDiagVec[(9*i)+4];
double a23 = blockDiagVec[(9*i)+5];
double a31 = blockDiagVec[(9*i)+6];
double a32 = blockDiagVec[(9*i)+7];
double a33 = blockDiagVec[(9*i)+8];
double detA = ((a11*a22*a33)-(a11*a23*a32)-(a21*a12*a33)
+(a21*a13*a32)+(a31*a12*a23)-(a31*a13*a22));
invBlockDiagEntries[3*i][0] = (a22*a33-a23*a32)/detA;
invBlockDiagEntries[3*i][1] = -(a12*a33-a13*a32)/detA;
invBlockDiagEntries[3*i][2] = (a12*a23-a13*a22)/detA;
invBlockDiagEntries[(3*i)+1][0] = -(a21*a33-a23*a31)/detA;
invBlockDiagEntries[(3*i)+1][1] = (a11*a33-a13*a31)/detA;
invBlockDiagEntries[(3*i)+1][2] = -(a11*a23-a13*a21)/detA;
invBlockDiagEntries[(3*i)+2][0] = (a21*a32-a22*a31)/detA;
invBlockDiagEntries[(3*i)+2][1] = -(a11*a32-a12*a31)/detA;
invBlockDiagEntries[(3*i)+2][2] = (a11*a22-a12*a21)/detA;
}//end for i
blockDiagVec.clear();
}
void getDofAndNodeSizeForElasticityMat(Mat J, unsigned int & dof, unsigned int & nodeSize) {
ot::DAMG damg;
MatShellGetContext(J, (void**)(&damg));
dof = 3;
nodeSize = damg->da->getNodeSize();
}
| rahulsampath/dendro | examples/src/backend/elasticityJac.C | C++ | gpl-2.0 | 25,200 |
/***************************************************************************
testqgsstatisticalsummary.cpp
-----------------------------
Date : May 2015
Copyright : (C) 2015 Nyall Dawson
Email : nyall dot dawson at gmail dot com
***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <QtTest/QtTest>
#include <QObject>
#include <QString>
#include <QStringList>
#include <QSettings>
#include <QSharedPointer>
#include "qgsstatisticalsummary.h"
#include "qgis.h"
class TestQgsStatisticSummary: public QObject
{
Q_OBJECT
private slots:
void initTestCase();// will be called before the first testfunction is executed.
void cleanupTestCase();// will be called after the last testfunction was executed.
void init();// will be called before each testfunction is executed.
void cleanup();// will be called after every testfunction.
void stats();
void individualStatCalculations_data();
void individualStatCalculations();
void maxMin();
private:
};
void TestQgsStatisticSummary::initTestCase()
{
}
void TestQgsStatisticSummary::cleanupTestCase()
{
}
void TestQgsStatisticSummary::init()
{
}
void TestQgsStatisticSummary::cleanup()
{
}
void TestQgsStatisticSummary::stats()
{
QgsStatisticalSummary s( QgsStatisticalSummary::All );
QList<double> values;
values << 4 << 2 << 3 << 2 << 5 << 8;
s.calculate( values );
QCOMPARE( s.count(), 6 );
QCOMPARE( s.sum(), 24.0 );
QCOMPARE( s.mean(), 4.0 );
QVERIFY( qgsDoubleNear( s.stDev(), 2.0816, 0.0001 ) );
QVERIFY( qgsDoubleNear( s.sampleStDev(), 2.2803, 0.0001 ) );
QCOMPARE( s.min(), 2.0 );
QCOMPARE( s.max(), 8.0 );
QCOMPARE( s.range(), 6.0 );
QCOMPARE( s.median(), 3.5 );
values << 9;
s.calculate( values );
QCOMPARE( s.median(), 4.0 );
values << 4 << 5 << 8 << 12 << 12 << 12;
s.calculate( values );
QCOMPARE( s.variety(), 7 );
QCOMPARE( s.minority(), 3.0 );
QCOMPARE( s.majority(), 12.0 );
//test quartiles. lots of possibilities here, involving odd/even/divisible by 4 counts
values.clear();
values << 7 << 15 << 36 << 39 << 40 << 41;
s.calculate( values );
QCOMPARE( s.median(), 37.5 );
QCOMPARE( s.firstQuartile(), 15.0 );
QCOMPARE( s.thirdQuartile(), 40.0 );
QCOMPARE( s.interQuartileRange(), 25.0 );
values.clear();
values << 7 << 15 << 36 << 39 << 40 << 41 << 43 << 49;
s.calculate( values );
QCOMPARE( s.median(), 39.5 );
QCOMPARE( s.firstQuartile(), 25.5 );
QCOMPARE( s.thirdQuartile(), 42.0 );
QCOMPARE( s.interQuartileRange(), 16.5 );
values.clear();
values << 6 << 7 << 15 << 36 << 39 << 40 << 41 << 42 << 43 << 47 << 49;
s.calculate( values );
QCOMPARE( s.median(), 40.0 );
QCOMPARE( s.firstQuartile(), 25.5 );
QCOMPARE( s.thirdQuartile(), 42.5 );
QCOMPARE( s.interQuartileRange(), 17.0 );
values.clear();
values << 6 << 7 << 15 << 36 << 39 << 40 << 41 << 42 << 43 << 47 << 49 << 50 << 58;
s.calculate( values );
QCOMPARE( s.median(), 41.0 );
QCOMPARE( s.firstQuartile(), 36.0 );
QCOMPARE( s.thirdQuartile(), 47.0 );
QCOMPARE( s.interQuartileRange(), 11.0 );
}
void TestQgsStatisticSummary::individualStatCalculations_data()
{
QTest::addColumn< int >( "statInt" );
QTest::addColumn<double>( "expected" );
QTest::newRow( "count" ) << ( int )QgsStatisticalSummary::Count << 10.0;
QTest::newRow( "sum" ) << ( int )QgsStatisticalSummary::Sum << 45.0;
QTest::newRow( "mean" ) << ( int )QgsStatisticalSummary::Mean << 4.5;
QTest::newRow( "median" ) << ( int )QgsStatisticalSummary::Median << 4.0;
QTest::newRow( "st_dev" ) << ( int )QgsStatisticalSummary::StDev << 1.96214;
QTest::newRow( "st_dev_sample" ) << ( int )QgsStatisticalSummary::StDevSample << 2.06828;
QTest::newRow( "min" ) << ( int )QgsStatisticalSummary::Min << 2.0;
QTest::newRow( "max" ) << ( int )QgsStatisticalSummary::Max << 8.0;
QTest::newRow( "range" ) << ( int )QgsStatisticalSummary::Range << 6.0;
QTest::newRow( "minority" ) << ( int )QgsStatisticalSummary::Minority << 2.0;
QTest::newRow( "majority" ) << ( int )QgsStatisticalSummary::Majority << 3.0;
QTest::newRow( "variety" ) << ( int )QgsStatisticalSummary::Variety << 5.0;
QTest::newRow( "first_quartile" ) << ( int )QgsStatisticalSummary::FirstQuartile << 3.0;
QTest::newRow( "third_quartile" ) << ( int )QgsStatisticalSummary::ThirdQuartile << 5.0;
QTest::newRow( "iqr" ) << ( int )QgsStatisticalSummary::InterQuartileRange << 2.0;
}
void TestQgsStatisticSummary::individualStatCalculations()
{
//tests calculation of statistics one at a time, to make sure statistic calculations are not
//dependant on each other
QList<double> values;
values << 4 << 4 << 2 << 3 << 3 << 3 << 5 << 5 << 8 << 8;
QFETCH( int, statInt );
QgsStatisticalSummary::Statistic stat = ( QgsStatisticalSummary::Statistic ) statInt;
QFETCH( double, expected );
//start with a summary which calculates NO statistics
QgsStatisticalSummary s( QgsStatisticalSummary::Statistics( 0 ) );
//set it to calculate just a single statistic
s.setStatistics( stat );
QCOMPARE( s.statistics(), stat );
s.calculate( values );
QVERIFY( qgsDoubleNear( s.statistic( stat ), expected, 0.00001 ) );
//make sure stat has a valid display name
QVERIFY( !QgsStatisticalSummary::displayName( stat ).isEmpty() );
}
void TestQgsStatisticSummary::maxMin()
{
QgsStatisticalSummary s( QgsStatisticalSummary::All );
//test max/min of negative value list
QList<double> negativeVals;
negativeVals << -5.0 << -10.0 << -15.0;
s.calculate( negativeVals );
QCOMPARE( s.min(), -15.0 );
QCOMPARE( s.max(), -5.0 );
}
QTEST_MAIN( TestQgsStatisticSummary )
#include "testqgsstatisticalsummary.moc"
| carolinux/QGIS | tests/src/core/testqgsstatisticalsummary.cpp | C++ | gpl-2.0 | 6,293 |
/************************************************************************
************************************************************************
FAUST compiler
Copyright (C) 2003-2004 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
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., 675 Mass Ave, Cambridge, MA 02139, USA.
************************************************************************
************************************************************************/
#ifndef _DOC_
#define _DOC_
/*****************************************************************************
******************************************************************************
FAUST DOCUMENTATOR
K. Barkati & Y. Orlarey, (c) Grame 2009
------------------------------------------------------------------------------
History :
---------
2009-07-19 : First version
******************************************************************************
*****************************************************************************/
#include "tlib.hh"
#include "eval.hh"
/*****************************************************************************
******************************************************************************
The Documentator
******************************************************************************
*****************************************************************************/
/*****************************************************************************
Doc Types Creation & Test
*****************************************************************************/
Tree docTxt (const char*);
Tree docEqn (Tree x);
Tree docDgm (Tree x);
Tree docNtc ();
Tree docLst ();
Tree docMtd (Tree x);
bool isDocTxt (Tree t);
bool isDocTxt (Tree t, const char**);
bool isDocEqn (Tree t, Tree& x);
bool isDocDgm (Tree t, Tree& x);
bool isDocNtc (Tree t);
bool isDocLst (Tree t);
bool isDocMtd (Tree t);
/*****************************************************************************
Printing Public Function
*****************************************************************************/
void printDoc(const char* projname, const char* docdev, const char* faustversion);
#endif
| FlatIO/faudiostream | compiler/documentator/doc.hh | C++ | gpl-2.0 | 2,920 |
/*
* File: DistanceMetrics.cpp
* Author: billwhite
*
* Created on March 29, 2011, 5:23 PM
*/
#include <cmath>
#include <iostream>
#include <map>
#include <utility>
#include <cmath>
#include "Dataset.h"
#include "DistanceMetrics.h"
#include "DatasetInstance.h"
#include "Statistics.h"
using namespace std;
pair<bool, double> CheckMissing(unsigned int attributeIndex,
DatasetInstance* dsi1,
DatasetInstance* dsi2) {
int numMissing = 0;
pair<double, double> hasMissing = make_pair(false, false);
if(dsi1->attributes[attributeIndex] == MISSING_ATTRIBUTE_VALUE) {
hasMissing.first = true;
++numMissing;
}
if(dsi2->attributes[attributeIndex] == MISSING_ATTRIBUTE_VALUE) {
hasMissing.second = true;
++numMissing;
}
// RELIEF-D
if(!numMissing) {
return make_pair(false, 0.0);
} else {
return make_pair(true, 2.0 / 3.0);
}
pair<bool, double> retValue;
double diff = 0.0;
// unsigned int numLevels = 0;
// unsigned int V = 0;
// Dataset* ds = dsi1->GetDatasetPtr();
switch(numMissing) {
case 0:
retValue = make_pair(false, 0.0);
break;
case 1:
if(hasMissing.first == true) {
diff = 1.0 / 3.0;
// diff = 1.0 / (double) ds->NumLevels(attributeIndex);
// diff = ds->GetProbabilityValueGivenClass(attributeIndex,
// dsi2->attributes[attributeIndex],
// dsi1->GetClass());
} else {
diff = 1.0 / 3.0;
// diff = 1.0 / (double) ds->NumLevels(attributeIndex);
// diff = ds->GetProbabilityValueGivenClass(attributeIndex,
// dsi1->attributes[attributeIndex],
// dsi2->GetClass());
}
// cout << "One missing value, diff = " << diff << endl;
retValue = make_pair(true, 1.0 - diff);
break;
case 2:
diff = 1.0 / 3.0;
// diff = 1.0 / (double) ds->NumLevels(attributeIndex);
// numLevels = ds->NumLevels(attributeIndex);
// diff = 0.0;
// double PVCI1 = 0.0, PVCI2 = 0.0;
// for(V = 0; V < numLevels; ++V) {
// PVCI1 = ds->GetProbabilityValueGivenClass(attributeIndex, V, dsi1->GetClass());
// PVCI2 = ds->GetProbabilityValueGivenClass(attributeIndex, V, dsi2->GetClass());
// cout << PVCI1 << " * " << PVCI2 << " = " << (PVCI1 * PVCI2) << endl;
// diff += (PVCI1 * PVCI2);
// }
// cout << "Two missing values, diff = " << diff << endl;
retValue = make_pair(true, 1.0 - diff);
break;
}
return retValue;
}
pair<bool, double> CheckMissingNumeric(unsigned int numericIndex,
DatasetInstance* dsi1,
DatasetInstance* dsi2) {
int numMissing = 0;
pair<double, double> hasMissing = make_pair(false, false);
if(dsi1->numerics[numericIndex] == MISSING_NUMERIC_VALUE) {
hasMissing.first = true;
++numMissing;
}
if(dsi2->numerics[numericIndex] == MISSING_NUMERIC_VALUE) {
hasMissing.second = true;
++numMissing;
}
if(numMissing) {
// ripped from Weka ReliefFAttributeEval.java:difference(), lines 828-836
double diff = 0.0;
if(numMissing == 2) {
return make_pair(true, 1.0);
} else {
if(hasMissing.first) {
pair<double, double> thisMinMax =
dsi2->GetDatasetPtr()->GetMinMaxForNumeric(numericIndex);
diff = norm(dsi2->numerics[numericIndex], thisMinMax.first, thisMinMax.second);
} else {
pair<double, double> thisMinMax =
dsi1->GetDatasetPtr()->GetMinMaxForNumeric(numericIndex);
diff = norm(dsi1->numerics[numericIndex], thisMinMax.first, thisMinMax.second);
}
if(diff < 0.5) {
diff = 1.0 - diff;
}
return make_pair(true, diff);
}
} else {
return make_pair(false, 0.0);
}
}
double norm(double x, double minX, double maxX) {
if(minX == maxX) {
return 0;
} else {
return(x - minX) / (maxX - minX);
}
}
double diffAMM(unsigned int attributeIndex,
DatasetInstance* dsi1,
DatasetInstance* dsi2) {
double distance = 0.0;
pair<bool, double> checkMissing = CheckMissing(attributeIndex, dsi1, dsi2);
if(checkMissing.first) {
distance = checkMissing.second;
} else {
distance = (double)
abs((int) dsi1->attributes[attributeIndex] -
(int) dsi2->attributes[attributeIndex]) * 0.5;
}
return distance;
}
double diffGMM(unsigned int attributeIndex,
DatasetInstance* dsi1,
DatasetInstance* dsi2) {
double distance = 0.0;
pair<bool, double> checkMissing = CheckMissing(attributeIndex, dsi1, dsi2);
if(checkMissing.first) {
distance = checkMissing.second;
} else {
distance = (dsi1->attributes[attributeIndex] !=
dsi2->attributes[attributeIndex]) ? 1.0 : 0.0;
}
return distance;
}
double diffNCA(unsigned int attributeIndex,
DatasetInstance* dsi1,
DatasetInstance* dsi2) {
double distance = 0.0;
// TODO: need special missing value checks for NCA metrics
pair<bool, double> checkMissing = CheckMissing(attributeIndex, dsi1, dsi2);
if(checkMissing.first) {
distance = checkMissing.second;
} else {
pair<char, char> alleles =
dsi1->GetDatasetPtr()->GetAttributeAlleles(attributeIndex);
string a1 = " ";
a1[0] = alleles.first;
string a2 = " ";
a2[0] = alleles.second;
map<AttributeLevel, string> genotypeMap;
genotypeMap[0] = a1 + a1;
genotypeMap[1] = a1 + a2;
genotypeMap[2] = a2 + a2;
AttributeLevel attrLevel1 = dsi1->attributes[attributeIndex];
AttributeLevel attrLevel2 = dsi2->attributes[attributeIndex];
string genotype1 = genotypeMap[attrLevel1];
string genotype2 = genotypeMap[attrLevel2];
map<char, unsigned int> nca1;
nca1['A'] = 0; nca1['T'] = 0; nca1['C'] = 0; nca1['G'] = 0;
++nca1[genotype1[0]];
++nca1[genotype1[1]];
map<char, unsigned int> nca2;
nca2['A'] = 0; nca2['T'] = 0; nca2['C'] = 0; nca2['G'] = 0;
++nca2[genotype2[0]];
++nca2[genotype2[1]];
map<char, unsigned int>::const_iterator nca1It = nca1.begin();
map<char, unsigned int>::const_iterator nca2It = nca2.begin();
for(; nca1It != nca1.end(); ++nca1It, ++nca2It) {
double nucleotideCount1 = (double) nca1It->second;
double nucleotideCount2 = (double) nca2It->second;
distance += abs(nucleotideCount1 - nucleotideCount2);
}
}
return distance;
}
double diffNCA6(unsigned int attributeIndex,
DatasetInstance* dsi1,
DatasetInstance* dsi2) {
double distance = 0.0;
// TODO: need special missing value checks for NCA metrics
pair<bool, double> checkMissing = CheckMissing(attributeIndex, dsi1, dsi2);
if(checkMissing.first) {
distance = checkMissing.second;
} else {
pair<char, char> alleles =
dsi1->GetDatasetPtr()->GetAttributeAlleles(attributeIndex);
string a1 = " ";
a1[0] = alleles.first;
string a2 = " ";
a2[0] = alleles.second;
map<AttributeLevel, string> genotypeMap;
genotypeMap[0] = a1 + a1;
genotypeMap[1] = a1 + a2;
genotypeMap[2] = a2 + a2;
AttributeLevel attrLevel1 = dsi1->attributes[attributeIndex];
AttributeLevel attrLevel2 = dsi2->attributes[attributeIndex];
string genotype1 = genotypeMap[attrLevel1];
string genotype2 = genotypeMap[attrLevel2];
map<char, unsigned int> nca1;
nca1['A'] = 0; nca1['T'] = 0; nca1['C'] = 0; nca1['G'] = 0;
nca1['X'] = 0; nca1['Y'] = 0;
++nca1[genotype1[0]];
++nca1[genotype1[1]];
nca1['X'] = nca1['A'] + nca1['G'];
nca1['Y'] = nca1['C'] + nca1['T'];
map<char, unsigned int> nca2;
nca2['A'] = 0; nca2['T'] = 0; nca2['C'] = 0; nca2['G'] = 0;
nca2['X'] = 0; nca2['Y'] = 0;
++nca2[genotype2[0]];
++nca2[genotype2[1]];
nca2['X'] = nca2['A'] + nca2['G'];
nca2['Y'] = nca2['C'] + nca2['T'];
map<char, unsigned int>::const_iterator nca1It = nca1.begin();
map<char, unsigned int>::const_iterator nca2It = nca2.begin();
for(; nca1It != nca1.end(); ++nca1It, ++nca2It) {
double nucleotideCount1 = (double) nca1It->second;
double nucleotideCount2 = (double) nca2It->second;
distance += abs(nucleotideCount1 - nucleotideCount2);
}
}
return distance;
}
double diffKM(unsigned int attributeIndex,
DatasetInstance* dsi1,
DatasetInstance* dsi2) {
double distance = 0.0;
AttributeLevel dsi1Al = dsi1->GetAttribute(attributeIndex);
AttributeLevel dsi2Al = dsi2->GetAttribute(attributeIndex);
if(dsi1Al != dsi2Al) {
if(dsi1->GetDatasetPtr()->GetAttributeMutationType(attributeIndex) ==
TRANSITION_MUTATION) {
distance = 1.0;
}
if(dsi1->GetDatasetPtr()->GetAttributeMutationType(attributeIndex) ==
TRANSVERSION_MUTATION) {
distance = 2.0;
}
}
return distance;
}
double diffManhattan(unsigned int attributeIndex,
DatasetInstance* dsi1,
DatasetInstance* dsi2) {
// double wekaNormDiff = fabs(norm(dsi1->numerics[attributeIndex],
// minMax.first, minMax.second) -
// norm(dsi2->numerics[attributeIndex],
// minMax.first, minMax.second));
// the above code is equivalent; why???
double distance = 0.0;
pair<bool, double> checkMissing =
CheckMissingNumeric(attributeIndex, dsi1, dsi2);
if(checkMissing.first) {
distance = checkMissing.second;
} else {
pair<double, double> minMax =
dsi1->GetDatasetPtr()->GetMinMaxForNumeric(attributeIndex);
distance =
fabs(dsi1->numerics[attributeIndex] -
dsi2->numerics[attributeIndex]) /
(minMax.second - minMax.first);
}
return distance;
}
double diffEuclidean(unsigned int attributeIndex,
DatasetInstance* dsi1,
DatasetInstance* dsi2) {
double distance = 0.0;
pair<bool, double> checkMissing =
CheckMissingNumeric(attributeIndex, dsi1, dsi2);
if(checkMissing.first) {
distance = checkMissing.second;
} else {
distance =
hypot(dsi1->numerics[attributeIndex], dsi2->numerics[attributeIndex]);
}
return distance;
}
double diffPredictedValueTau(DatasetInstance* dsi1, DatasetInstance* dsi2) {
pair<double, double> minMax =
dsi1->GetDatasetPtr()->GetMinMaxForContinuousPhenotype();
// double diff = fabs(dsi1->GetPredictedValueTau() - dsi2->GetPredictedValueTau());
double diff =
fabs(dsi1->GetPredictedValueTau() - dsi2->GetPredictedValueTau()) /
(minMax.second - minMax.first);
return diff;
}
| insilico/EC | src/library/DistanceMetrics.cpp | C++ | gpl-2.0 | 10,946 |
<?php
/**
* Template part for displaying single posts.
*
* @package Simppeli
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
<div class="entry-meta">
<?php simppeli_posted_on(); ?>
</div><!-- .entry-meta -->
</header><!-- .entry-header -->
<div class="entry-content">
<?php the_content(); ?>
<?php
wp_link_pages( array(
'before' => '<div class="page-links"><span class="page-links-title">' . __( 'Pages:', 'simppeli' ) . '</span>',
'after' => '</div>',
'link_before' => '<span>',
'link_after' => '</span>',
'pagelink' => '<span class="screen-reader-text">' . __( 'Page', 'simppeli' ) . ' </span>%',
'separator' => '<span class="screen-reader-text">, </span>',
) );
?>
</div><!-- .entry-content -->
<footer class="entry-footer">
<?php simppeli_entry_footer(); ?>
</footer><!-- .entry-footer -->
</article><!-- #post-## -->
| lisajwells/annierehill | wp-content/themes/simppeli/template-parts/content-single.php | PHP | gpl-2.0 | 1,011 |
/*
* Copyright (c) 1999, 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.
*
*/
#ifndef OS_BSD_VM_OS_BSD_HPP
#define OS_BSD_VM_OS_BSD_HPP
// Bsd_OS defines the interface to Bsd operating systems
// Information about the protection of the page at address '0' on this os.
static bool zero_page_read_protected() { return true; }
#ifdef __APPLE__
// Mac OS X doesn't support clock_gettime. Stub out the type, it is
// unused
typedef int clockid_t;
#endif
class Bsd {
friend class os;
// For signal-chaining
#define MAXSIGNUM 32
static struct sigaction sigact[MAXSIGNUM]; // saved preinstalled sigactions
static unsigned int sigs; // mask of signals that have
// preinstalled signal handlers
static bool libjsig_is_loaded; // libjsig that interposes sigaction(),
// __sigaction(), signal() is loaded
static struct sigaction *(*get_signal_action)(int);
static struct sigaction *get_preinstalled_handler(int);
static void save_preinstalled_handler(int, struct sigaction&);
static void check_signal_handler(int sig);
// For signal flags diagnostics
static int sigflags[MAXSIGNUM];
#ifdef __APPLE__
// mach_absolute_time
static mach_timebase_info_data_t _timebase_info;
static volatile uint64_t _max_abstime;
#else
static int (*_clock_gettime)(clockid_t, struct timespec *);
#endif
static GrowableArray<int>* _cpu_to_node;
protected:
static julong _physical_memory;
static pthread_t _main_thread;
static int _page_size;
static julong available_memory();
static julong physical_memory() { return _physical_memory; }
static void initialize_system_info();
static void rebuild_cpu_to_node_map();
static GrowableArray<int>* cpu_to_node() { return _cpu_to_node; }
static bool hugetlbfs_sanity_check(bool warn, size_t page_size);
public:
static void init_thread_fpu_state();
static pthread_t main_thread(void) { return _main_thread; }
static void hotspot_sigmask(Thread* thread);
static bool is_initial_thread(void);
static pid_t gettid();
static int page_size(void) { return _page_size; }
static void set_page_size(int val) { _page_size = val; }
static address ucontext_get_pc(ucontext_t* uc);
static void ucontext_set_pc(ucontext_t* uc, address pc);
static intptr_t* ucontext_get_sp(ucontext_t* uc);
static intptr_t* ucontext_get_fp(ucontext_t* uc);
// For Analyzer Forte AsyncGetCallTrace profiling support:
//
// This interface should be declared in os_bsd_i486.hpp, but
// that file provides extensions to the os class and not the
// Bsd class.
static ExtendedPC fetch_frame_from_ucontext(Thread* thread, ucontext_t* uc,
intptr_t** ret_sp, intptr_t** ret_fp);
// This boolean allows users to forward their own non-matching signals
// to JVM_handle_bsd_signal, harmlessly.
static bool signal_handlers_are_installed;
static int get_our_sigflags(int);
static void set_our_sigflags(int, int);
static void signal_sets_init();
static void install_signal_handlers();
static void set_signal_handler(int, bool);
static bool is_sig_ignored(int sig);
static sigset_t* unblocked_signals();
static sigset_t* vm_signals();
static sigset_t* allowdebug_blocked_signals();
// For signal-chaining
static struct sigaction *get_chained_signal_action(int sig);
static bool chained_handler(int sig, siginfo_t* siginfo, void* context);
// Minimum stack size a thread can be created with (allowing
// the VM to completely create the thread and enter user code)
static size_t min_stack_allowed;
// Return default stack size or guard size for the specified thread type
static size_t default_stack_size(os::ThreadType thr_type);
static size_t default_guard_size(os::ThreadType thr_type);
// Real-time clock functions
static void clock_init(void);
// Stack repair handling
// none present
private:
typedef int (*sched_getcpu_func_t)(void);
typedef int (*numa_node_to_cpus_func_t)(int node, unsigned long *buffer, int bufferlen);
typedef int (*numa_max_node_func_t)(void);
typedef int (*numa_available_func_t)(void);
typedef int (*numa_tonode_memory_func_t)(void *start, size_t size, int node);
typedef void (*numa_interleave_memory_func_t)(void *start, size_t size, unsigned long *nodemask);
static sched_getcpu_func_t _sched_getcpu;
static numa_node_to_cpus_func_t _numa_node_to_cpus;
static numa_max_node_func_t _numa_max_node;
static numa_available_func_t _numa_available;
static numa_tonode_memory_func_t _numa_tonode_memory;
static numa_interleave_memory_func_t _numa_interleave_memory;
static unsigned long* _numa_all_nodes;
static void set_sched_getcpu(sched_getcpu_func_t func) { _sched_getcpu = func; }
static void set_numa_node_to_cpus(numa_node_to_cpus_func_t func) { _numa_node_to_cpus = func; }
static void set_numa_max_node(numa_max_node_func_t func) { _numa_max_node = func; }
static void set_numa_available(numa_available_func_t func) { _numa_available = func; }
static void set_numa_tonode_memory(numa_tonode_memory_func_t func) { _numa_tonode_memory = func; }
static void set_numa_interleave_memory(numa_interleave_memory_func_t func) { _numa_interleave_memory = func; }
static void set_numa_all_nodes(unsigned long* ptr) { _numa_all_nodes = ptr; }
public:
static int sched_getcpu() { return _sched_getcpu != NULL ? _sched_getcpu() : -1; }
static int numa_node_to_cpus(int node, unsigned long *buffer, int bufferlen) {
return _numa_node_to_cpus != NULL ? _numa_node_to_cpus(node, buffer, bufferlen) : -1;
}
static int numa_max_node() { return _numa_max_node != NULL ? _numa_max_node() : -1; }
static int numa_available() { return _numa_available != NULL ? _numa_available() : -1; }
static int numa_tonode_memory(void *start, size_t size, int node) {
return _numa_tonode_memory != NULL ? _numa_tonode_memory(start, size, node) : -1;
}
static void numa_interleave_memory(void *start, size_t size) {
if (_numa_interleave_memory != NULL && _numa_all_nodes != NULL) {
_numa_interleave_memory(start, size, _numa_all_nodes);
}
}
static int get_node_by_cpu(int cpu_id);
};
class PlatformEvent : public CHeapObj<mtInternal> {
private:
double CachePad[4]; // increase odds that _mutex is sole occupant of cache line
volatile int _Event;
volatile int _nParked;
pthread_mutex_t _mutex[1];
pthread_cond_t _cond[1];
double PostPad[2];
Thread * _Assoc;
public: // TODO-FIXME: make dtor private
~PlatformEvent() { guarantee(0, "invariant"); }
public:
PlatformEvent() {
int status;
status = pthread_cond_init(_cond, NULL);
assert_status(status == 0, status, "cond_init");
status = pthread_mutex_init(_mutex, NULL);
assert_status(status == 0, status, "mutex_init");
_Event = 0;
_nParked = 0;
_Assoc = NULL;
}
// Use caution with reset() and fired() -- they may require MEMBARs
void reset() { _Event = 0; }
int fired() { return _Event; }
void park();
void unpark();
int park(jlong millis);
void SetAssociation(Thread * a) { _Assoc = a; }
};
class PlatformParker : public CHeapObj<mtInternal> {
protected:
pthread_mutex_t _mutex[1];
pthread_cond_t _cond[1];
public: // TODO-FIXME: make dtor private
~PlatformParker() { guarantee(0, "invariant"); }
public:
PlatformParker() {
int status;
status = pthread_cond_init(_cond, NULL);
assert_status(status == 0, status, "cond_init");
status = pthread_mutex_init(_mutex, NULL);
assert_status(status == 0, status, "mutex_init");
}
};
#endif // OS_BSD_VM_OS_BSD_HPP
| WillDignazio/hotspot | src/os/bsd/vm/os_bsd.hpp | C++ | gpl-2.0 | 8,792 |
<?php
namespace Drupal\hal\Normalizer;
use Drupal\Component\Utility\NestedArray;
use Drupal\serialization\Normalizer\FieldNormalizer as SerializationFieldNormalizer;
/**
* Converts the Drupal field structure to HAL array structure.
*/
class FieldNormalizer extends SerializationFieldNormalizer {
/**
* {@inheritdoc}
*/
protected $format = ['hal_json'];
/**
* {@inheritdoc}
*/
public function normalize($field, $format = NULL, array $context = []) {
$normalized_field_items = [];
// Get the field definition.
$entity = $field->getEntity();
$field_name = $field->getName();
$field_definition = $field->getFieldDefinition();
// If this field is not translatable, it can simply be normalized without
// separating it into different translations.
if (!$field_definition->isTranslatable()) {
$normalized_field_items = $this->normalizeFieldItems($field, $format, $context);
}
// Otherwise, the languages have to be extracted from the entity and passed
// in to the field item normalizer in the context. The langcode is appended
// to the field item values.
else {
foreach ($entity->getTranslationLanguages() as $language) {
$context['langcode'] = $language->getId();
$translation = $entity->getTranslation($language->getId());
$translated_field = $translation->get($field_name);
$normalized_field_items = array_merge($normalized_field_items, $this->normalizeFieldItems($translated_field, $format, $context));
}
}
// Merge deep so that links set in entity reference normalizers are merged
// into the links property.
$normalized = NestedArray::mergeDeepArray($normalized_field_items);
return $normalized;
}
/**
* Helper function to normalize field items.
*
* @param \Drupal\Core\Field\FieldItemListInterface $field
* The field object.
* @param string $format
* The format.
* @param array $context
* The context array.
*
* @return array
* The array of normalized field items.
*/
protected function normalizeFieldItems($field, $format, $context) {
$normalized_field_items = [];
if (!$field->isEmpty()) {
foreach ($field as $field_item) {
$normalized_field_items[] = $this->serializer->normalize($field_item, $format, $context);
}
}
return $normalized_field_items;
}
}
| jakegibs617/portfolio-drupal | core/modules/hal/src/Normalizer/FieldNormalizer.php | PHP | gpl-2.0 | 2,400 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "sim4.H"
#include "util++.H"
int
main(int argc, char **argv) {
char *outPrefix = 0L;
char datName[FILENAME_MAX];
char gnuName[FILENAME_MAX];
char pngName[FILENAME_MAX];
char gnuCmd[FILENAME_MAX];
char *inName = 0L;
int arg = 1;
int err = 0;
while (arg < argc) {
if (strncmp(argv[arg], "-o", 2) == 0) {
outPrefix = argv[++arg];
} else if (strncmp(argv[arg], "-i", 2) == 0) {
inName = argv[++arg];
} else {
fprintf(stderr, "Unknown arg '%s'\n", argv[arg]);
err++;
}
arg++;
}
if ((inName == 0L) || (outPrefix == 0L) || (err != 0)) {
fprintf(stderr, "usage: %s -i sim4db -o outputPrefix\n", argv[0]);
fprintf(stderr, "\n");
fprintf(stderr, " Creates outputPrefix.dat containing the number of errors at each\n");
fprintf(stderr, " base position, and outputPrefix.png the visual representation.\n");
fprintf(stderr, "\n");
fprintf(stderr, " Suggested usage:\n");
fprintf(stderr, "\n");
fprintf(stderr, " snapper2\n");
fprintf(stderr, " -queries Q.fasta\n");
fprintf(stderr, " -genomic G.fasta\n");
fprintf(stderr, " -positions G.posDB\n");
fprintf(stderr, " -aligns\n");
fprintf(stderr, " -minmatchidentity 94\n");
fprintf(stderr, " -minmatchcoverage 90\n");
fprintf(stderr, " -mersize 18\n");
fprintf(stderr, " -ignore 500\n");
fprintf(stderr, " -numthreads 16\n");
fprintf(stderr, " -verbose\n");
fprintf(stderr, " -output Q.sim4db\n");
fprintf(stderr, "\n");
fprintf(stderr, " pickBestPolish < Q.sim4db > Q.best.sim4db\n");
fprintf(stderr, "\n");
fprintf(stderr, " reportAlignmentDifferences\n");
fprintf(stderr, " -i Q.best.sim4db\n");
fprintf(stderr, " -o Q\n");
fprintf(stderr, "\n");
fprintf(stderr, "\n");
exit(1);
}
fprintf(stderr, "Reading input from '%s'\n", inName);
fprintf(stderr, "Writing output to '%s'\n", outPrefix);
// Open output files early, in case they fail.
errno = 0;
sprintf(datName, "%s.dat", outPrefix);
sprintf(gnuName, "%s.gnuplot", outPrefix);
sprintf(pngName, "%s.png", outPrefix);
FILE *DAT = fopen(datName, "w");
if (errno)
fprintf(stderr, "Failed to open '%s' for writing data: %s\n", datName, strerror(errno)), exit(1);
FILE *GNU = fopen(gnuName, "w");
if (errno)
fprintf(stderr, "Failed to open '%s' for writing gnuplot command: %s\n", gnuName, strerror(errno)), exit(1);
// Read matches.
uint32 lMax = 10240;
uint32 lLen = 0;
uint32 *nTot = new uint32 [lMax];
uint32 *nIde = new uint32 [lMax];
uint32 *nMis = new uint32 [lMax];
uint32 *nIns = new uint32 [lMax];
uint32 *nDel = new uint32 [lMax];
memset(nTot, 0, sizeof(uint32) * lMax);
memset(nIde, 0, sizeof(uint32) * lMax);
memset(nMis, 0, sizeof(uint32) * lMax);
memset(nIns, 0, sizeof(uint32) * lMax);
memset(nDel, 0, sizeof(uint32) * lMax);
sim4polishReader *R = new sim4polishReader(inName);
sim4polish *p = 0L;
while (R->nextAlignment(p)) {
bool fwd = (p->_matchOrientation == SIM4_MATCH_FORWARD);
for (uint32 exon=0; exon<p->_numExons; exon++) {
sim4polishExon *e = p->_exons + exon;
// Fail if there are no alignments.
if ((e->_estAlignment == 0L) ||
(e->_genAlignment == 0L))
fprintf(stderr, "FAIL: Input has no alignment strings (-aligns option in snapper2).\n"), exit(1);
// Parse the alignment to find ungapped blocks
uint32 aPos = 0; // Position in the alignment
uint32 qPos = e->_estFrom - 1; // Actual position in the query sequence
uint32 gPos = e->_genFrom - 1; // Actual position in the genome sequence
if (fwd == false)
qPos = p->_estLen - e->_estFrom + 1;
bool notDone = true; // There should be a way to get rid of this stupid variable....
while (notDone) {
notDone = ((e->_estAlignment[aPos] != 0) &&
(e->_genAlignment[aPos] != 0));
// If we find the end of a gapless block, emit a match
if (e->_estAlignment[aPos] == e->_genAlignment[aPos])
nIde[qPos]++;
else if (e->_estAlignment[aPos] == '-')
nDel[qPos]++;
else if (e->_genAlignment[aPos] == '-')
nIns[qPos]++;
else
nMis[qPos]++;
nTot[qPos]++;
assert(qPos < lMax);
if (lLen < qPos)
lLen = qPos;
//fprintf(stdout, "%s "uint32FMT" %c ->_ %s "uint32FMT" %c\n",
// p->_estDefLine, qPos, e->_estAlignment[aPos],
// p->_genDefLine, gPos, e->_genAlignment[aPos]);
if (e->_estAlignment[aPos] != '-')
if (fwd) qPos++;
else qPos--;
if (e->_genAlignment[aPos] != '-')
gPos++;
aPos++;
}
}
}
// Index
// nTot
// nIde, percent
// nDel, percent
// nIns, percent
// nMis, percent
fprintf(DAT, "#idx\tnTot\tnIde\tfrac\tnDel\tfrac\tnIns\tfrac\tnMis\tfrac\tnErr\tfrac\n");
for (uint32 i=0; i<=lLen; i++)
fprintf(DAT, "%u\t%u\t%u\t%6.4f\t%u\t%6.4f\t%u\t%6.4f\t%u\t%6.4f\t%u\t%6.4f\n",
i,
nTot[i],
nIde[i], (double)nIde[i] / nTot[i],
nDel[i], (double)nDel[i] / nTot[i],
nIns[i], (double)nIns[i] / nTot[i],
nMis[i], (double)nMis[i] / nTot[i],
nTot[i] - nIde[i], (double)(nTot[i] - nIde[i]) / nTot[i]);
fprintf(GNU, "set terminal png\n");
fprintf(GNU, "set output \"%s\"\n", pngName);
fprintf(GNU, "set title \"Fraction error per base for '%s'\"\n", inName);
fprintf(GNU, "set xlabel \"Base position\"\n");
fprintf(GNU, "set ylabel \"Fraction error\"\n");
fprintf(GNU, "plot [][0:0.04] \\\n");
fprintf(GNU, " \"%s\" using 1:4 with lines title \"nTot\", \\\n", datName);
fprintf(GNU, " \"%s\" using 1:6 with lines title \"nDel\", \\\n", datName);
fprintf(GNU, " \"%s\" using 1:8 with lines title \"nIns\", \\\n", datName);
fprintf(GNU, " \"%s\" using 1:10 with lines title \"nMis\", \\\n", datName);
fprintf(GNU, " \"%s\" using 1:12 with lines title \"nErr\"\n", datName);
fclose(DAT);
fclose(GNU);
sprintf(gnuCmd, "gnuplot < %s", gnuName);
system(gnuCmd);
return(0);
}
| macmanes-lab/wgs-assembler | kmer/sim4dbutils/reportAlignmentDifferences.C | C++ | gpl-2.0 | 6,477 |
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact H. Carter Edwards (hcedwar@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#ifndef KOKKOS_CUDA_PARALLEL_HPP
#define KOKKOS_CUDA_PARALLEL_HPP
#include <Kokkos_Macros.hpp>
#if defined( __CUDACC__ ) && defined( KOKKOS_ENABLE_CUDA )
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdint>
#include <utility>
#include <Kokkos_Parallel.hpp>
#include <Cuda/Kokkos_CudaExec.hpp>
#include <Cuda/Kokkos_Cuda_ReduceScan.hpp>
#include <Cuda/Kokkos_Cuda_Internal.hpp>
#include <Kokkos_Vectorization.hpp>
#if defined(KOKKOS_ENABLE_PROFILING)
#include <impl/Kokkos_Profiling_Interface.hpp>
#include <typeinfo>
#endif
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
namespace Kokkos {
namespace Impl {
template< class ... Properties >
class TeamPolicyInternal< Kokkos::Cuda , Properties ... >: public PolicyTraits<Properties ... >
{
public:
//! Tag this class as a kokkos execution policy
typedef TeamPolicyInternal execution_policy ;
typedef PolicyTraits<Properties ... > traits;
private:
enum { MAX_WARP = 8 };
int m_league_size ;
int m_team_size ;
int m_vector_length ;
int m_team_scratch_size[2] ;
int m_thread_scratch_size[2] ;
int m_chunk_size;
public:
//! Execution space of this execution policy
typedef Kokkos::Cuda execution_space ;
TeamPolicyInternal& operator = (const TeamPolicyInternal& p) {
m_league_size = p.m_league_size;
m_team_size = p.m_team_size;
m_vector_length = p.m_vector_length;
m_team_scratch_size[0] = p.m_team_scratch_size[0];
m_team_scratch_size[1] = p.m_team_scratch_size[1];
m_thread_scratch_size[0] = p.m_thread_scratch_size[0];
m_thread_scratch_size[1] = p.m_thread_scratch_size[1];
m_chunk_size = p.m_chunk_size;
return *this;
}
//----------------------------------------
template< class FunctorType >
inline static
int team_size_max( const FunctorType & functor )
{
int n = MAX_WARP * Impl::CudaTraits::WarpSize ;
for ( ; n ; n >>= 1 ) {
const int shmem_size =
/* for global reduce */ Impl::cuda_single_inter_block_reduce_scan_shmem<false,FunctorType,typename traits::work_tag>( functor , n )
/* for team reduce */ + ( n + 2 ) * sizeof(double)
/* for team shared */ + Impl::FunctorTeamShmemSize< FunctorType >::value( functor , n );
if ( shmem_size < Impl::CudaTraits::SharedMemoryCapacity ) break ;
}
return n ;
}
template< class FunctorType >
static int team_size_recommended( const FunctorType & functor )
{ return team_size_max( functor ); }
template< class FunctorType >
static int team_size_recommended( const FunctorType & functor , const int vector_length)
{
int max = team_size_max( functor )/vector_length;
if(max<1) max = 1;
return max;
}
inline static
int vector_length_max()
{ return Impl::CudaTraits::WarpSize; }
//----------------------------------------
inline int vector_length() const { return m_vector_length ; }
inline int team_size() const { return m_team_size ; }
inline int league_size() const { return m_league_size ; }
inline int scratch_size(int level, int team_size_ = -1) const {
if(team_size_<0) team_size_ = m_team_size;
return m_team_scratch_size[level] + team_size_*m_thread_scratch_size[level];
}
inline int team_scratch_size(int level) const {
return m_team_scratch_size[level];
}
inline int thread_scratch_size(int level) const {
return m_thread_scratch_size[level];
}
TeamPolicyInternal()
: m_league_size( 0 )
, m_team_size( 0 )
, m_vector_length( 0 )
, m_team_scratch_size {0,0}
, m_thread_scratch_size {0,0}
, m_chunk_size ( 32 )
{}
/** \brief Specify league size, request team size */
TeamPolicyInternal( execution_space &
, int league_size_
, int team_size_request
, int vector_length_request = 1 )
: m_league_size( league_size_ )
, m_team_size( team_size_request )
, m_vector_length( vector_length_request )
, m_team_scratch_size {0,0}
, m_thread_scratch_size {0,0}
, m_chunk_size ( 32 )
{
// Allow only power-of-two vector_length
if ( ! Kokkos::Impl::is_integral_power_of_two( vector_length_request ) ) {
Impl::throw_runtime_exception( "Requested non-power-of-two vector length for TeamPolicy.");
}
// Make sure league size is permissable
if(league_size_ >= int(Impl::cuda_internal_maximum_grid_count()))
Impl::throw_runtime_exception( "Requested too large league_size for TeamPolicy on Cuda execution space.");
// Make sure total block size is permissable
if ( m_team_size * m_vector_length > 1024 ) {
Impl::throw_runtime_exception(std::string("Kokkos::TeamPolicy< Cuda > the team size is too large. Team size x vector length must be smaller than 1024."));
}
}
/** \brief Specify league size, request team size */
TeamPolicyInternal( execution_space &
, int league_size_
, const Kokkos::AUTO_t & /* team_size_request */
, int vector_length_request = 1 )
: m_league_size( league_size_ )
, m_team_size( -1 )
, m_vector_length( vector_length_request )
, m_team_scratch_size {0,0}
, m_thread_scratch_size {0,0}
, m_chunk_size ( 32 )
{
// Allow only power-of-two vector_length
if ( ! Kokkos::Impl::is_integral_power_of_two( vector_length_request ) ) {
Impl::throw_runtime_exception( "Requested non-power-of-two vector length for TeamPolicy.");
}
// Make sure league size is permissable
if(league_size_ >= int(Impl::cuda_internal_maximum_grid_count()))
Impl::throw_runtime_exception( "Requested too large league_size for TeamPolicy on Cuda execution space.");
}
TeamPolicyInternal( int league_size_
, int team_size_request
, int vector_length_request = 1 )
: m_league_size( league_size_ )
, m_team_size( team_size_request )
, m_vector_length ( vector_length_request )
, m_team_scratch_size {0,0}
, m_thread_scratch_size {0,0}
, m_chunk_size ( 32 )
{
// Allow only power-of-two vector_length
if ( ! Kokkos::Impl::is_integral_power_of_two( vector_length_request ) ) {
Impl::throw_runtime_exception( "Requested non-power-of-two vector length for TeamPolicy.");
}
// Make sure league size is permissable
if(league_size_ >= int(Impl::cuda_internal_maximum_grid_count()))
Impl::throw_runtime_exception( "Requested too large league_size for TeamPolicy on Cuda execution space.");
// Make sure total block size is permissable
if ( m_team_size * m_vector_length > 1024 ) {
Impl::throw_runtime_exception(std::string("Kokkos::TeamPolicy< Cuda > the team size is too large. Team size x vector length must be smaller than 1024."));
}
}
TeamPolicyInternal( int league_size_
, const Kokkos::AUTO_t & /* team_size_request */
, int vector_length_request = 1 )
: m_league_size( league_size_ )
, m_team_size( -1 )
, m_vector_length ( vector_length_request )
, m_team_scratch_size {0,0}
, m_thread_scratch_size {0,0}
, m_chunk_size ( 32 )
{
// Allow only power-of-two vector_length
if ( ! Kokkos::Impl::is_integral_power_of_two( vector_length_request ) ) {
Impl::throw_runtime_exception( "Requested non-power-of-two vector length for TeamPolicy.");
}
// Make sure league size is permissable
if(league_size_ >= int(Impl::cuda_internal_maximum_grid_count()))
Impl::throw_runtime_exception( "Requested too large league_size for TeamPolicy on Cuda execution space.");
}
inline int chunk_size() const { return m_chunk_size ; }
/** \brief set chunk_size to a discrete value*/
inline TeamPolicyInternal set_chunk_size(typename traits::index_type chunk_size_) const {
TeamPolicyInternal p = *this;
p.m_chunk_size = chunk_size_;
return p;
}
/** \brief set per team scratch size for a specific level of the scratch hierarchy */
inline TeamPolicyInternal set_scratch_size(const int& level, const PerTeamValue& per_team) const {
TeamPolicyInternal p = *this;
p.m_team_scratch_size[level] = per_team.value;
return p;
};
/** \brief set per thread scratch size for a specific level of the scratch hierarchy */
inline TeamPolicyInternal set_scratch_size(const int& level, const PerThreadValue& per_thread) const {
TeamPolicyInternal p = *this;
p.m_thread_scratch_size[level] = per_thread.value;
return p;
};
/** \brief set per thread and per team scratch size for a specific level of the scratch hierarchy */
inline TeamPolicyInternal set_scratch_size(const int& level, const PerTeamValue& per_team, const PerThreadValue& per_thread) const {
TeamPolicyInternal p = *this;
p.m_team_scratch_size[level] = per_team.value;
p.m_thread_scratch_size[level] = per_thread.value;
return p;
};
typedef Kokkos::Impl::CudaTeamMember member_type ;
};
} // namspace Impl
} // namespace Kokkos
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
namespace Kokkos {
namespace Impl {
template< class FunctorType , class ... Traits >
class ParallelFor< FunctorType
, Kokkos::RangePolicy< Traits ... >
, Kokkos::Cuda
>
{
private:
typedef Kokkos::RangePolicy< Traits ... > Policy;
typedef typename Policy::member_type Member ;
typedef typename Policy::work_tag WorkTag ;
const FunctorType m_functor ;
const Policy m_policy ;
ParallelFor() = delete ;
ParallelFor & operator = ( const ParallelFor & ) = delete ;
template< class TagType >
inline __device__
typename std::enable_if< std::is_same< TagType , void >::value >::type
exec_range( const Member i ) const
{ m_functor( i ); }
template< class TagType >
inline __device__
typename std::enable_if< ! std::is_same< TagType , void >::value >::type
exec_range( const Member i ) const
{ m_functor( TagType() , i ); }
public:
typedef FunctorType functor_type ;
inline
__device__
void operator()(void) const
{
const Member work_stride = blockDim.y * gridDim.x ;
const Member work_end = m_policy.end();
for ( Member
iwork = m_policy.begin() + threadIdx.y + blockDim.y * blockIdx.x ;
iwork < work_end ;
iwork += work_stride ) {
this-> template exec_range< WorkTag >( iwork );
}
}
inline
void execute() const
{
const int nwork = m_policy.end() - m_policy.begin();
const dim3 block( 1 , CudaTraits::WarpSize * cuda_internal_maximum_warp_count(), 1);
const dim3 grid( std::min( ( nwork + block.y - 1 ) / block.y , cuda_internal_maximum_grid_count() ) , 1 , 1);
CudaParallelLaunch< ParallelFor >( *this , grid , block , 0 );
}
ParallelFor( const FunctorType & arg_functor ,
const Policy & arg_policy )
: m_functor( arg_functor )
, m_policy( arg_policy )
{ }
};
template< class FunctorType , class ... Properties >
class ParallelFor< FunctorType
, Kokkos::TeamPolicy< Properties ... >
, Kokkos::Cuda
>
{
private:
typedef TeamPolicyInternal< Kokkos::Cuda , Properties ... > Policy ;
typedef typename Policy::member_type Member ;
typedef typename Policy::work_tag WorkTag ;
public:
typedef FunctorType functor_type ;
typedef Cuda::size_type size_type ;
private:
// Algorithmic constraints: blockDim.y is a power of two AND blockDim.y == blockDim.z == 1
// shared memory utilization:
//
// [ team reduce space ]
// [ team shared space ]
//
const FunctorType m_functor ;
const size_type m_league_size ;
const size_type m_team_size ;
const size_type m_vector_size ;
const int m_shmem_begin ;
const int m_shmem_size ;
void* m_scratch_ptr[2] ;
const int m_scratch_size[2] ;
template< class TagType >
__device__ inline
typename std::enable_if< std::is_same< TagType , void >::value >::type
exec_team( const Member & member ) const
{ m_functor( member ); }
template< class TagType >
__device__ inline
typename std::enable_if< ! std::is_same< TagType , void >::value >::type
exec_team( const Member & member ) const
{ m_functor( TagType() , member ); }
public:
__device__ inline
void operator()(void) const
{
// Iterate this block through the league
int threadid = 0;
if ( m_scratch_size[1]>0 ) {
__shared__ int base_thread_id;
if (threadIdx.x==0 && threadIdx.y==0 ) {
threadid = ((blockIdx.x*blockDim.z + threadIdx.z) * blockDim.x * blockDim.y) % kokkos_impl_cuda_lock_arrays.n;
threadid = ((threadid + blockDim.x * blockDim.y-1)/(blockDim.x * blockDim.y)) * blockDim.x * blockDim.y;
if(threadid > kokkos_impl_cuda_lock_arrays.n) threadid-=blockDim.x * blockDim.y;
int done = 0;
while (!done) {
done = (0 == atomicCAS(&kokkos_impl_cuda_lock_arrays.atomic[threadid],0,1));
if(!done) {
threadid += blockDim.x * blockDim.y;
if(threadid > kokkos_impl_cuda_lock_arrays.n) threadid = 0;
}
}
base_thread_id = threadid;
}
__syncthreads();
threadid = base_thread_id;
}
for ( int league_rank = blockIdx.x ; league_rank < m_league_size ; league_rank += gridDim.x ) {
this-> template exec_team< WorkTag >(
typename Policy::member_type( kokkos_impl_cuda_shared_memory<void>()
, m_shmem_begin
, m_shmem_size
, (void*) ( ((char*)m_scratch_ptr[1]) + threadid/(blockDim.x*blockDim.y) * m_scratch_size[1])
, m_scratch_size[1]
, league_rank
, m_league_size ) );
}
if ( m_scratch_size[1]>0 ) {
__syncthreads();
if (threadIdx.x==0 && threadIdx.y==0 )
kokkos_impl_cuda_lock_arrays.atomic[threadid]=0;
}
}
inline
void execute() const
{
const int shmem_size_total = m_shmem_begin + m_shmem_size ;
const dim3 grid( int(m_league_size) , 1 , 1 );
const dim3 block( int(m_vector_size) , int(m_team_size) , 1 );
CudaParallelLaunch< ParallelFor >( *this, grid, block, shmem_size_total ); // copy to device and execute
}
ParallelFor( const FunctorType & arg_functor
, const Policy & arg_policy
)
: m_functor( arg_functor )
, m_league_size( arg_policy.league_size() )
, m_team_size( 0 <= arg_policy.team_size() ? arg_policy.team_size() :
Kokkos::Impl::cuda_get_opt_block_size< ParallelFor >( arg_functor , arg_policy.vector_length(), arg_policy.team_scratch_size(0),arg_policy.thread_scratch_size(0) ) / arg_policy.vector_length() )
, m_vector_size( arg_policy.vector_length() )
, m_shmem_begin( sizeof(double) * ( m_team_size + 2 ) )
, m_shmem_size( arg_policy.scratch_size(0,m_team_size) + FunctorTeamShmemSize< FunctorType >::value( m_functor , m_team_size ) )
, m_scratch_ptr{NULL,NULL}
, m_scratch_size{arg_policy.scratch_size(0,m_team_size),arg_policy.scratch_size(1,m_team_size)}
{
// Functor's reduce memory, team scan memory, and team shared memory depend upon team size.
m_scratch_ptr[1] = cuda_resize_scratch_space(m_scratch_size[1]*(Cuda::concurrency()/(m_team_size*m_vector_size)));
const int shmem_size_total = m_shmem_begin + m_shmem_size ;
if ( CudaTraits::SharedMemoryCapacity < shmem_size_total ) {
Kokkos::Impl::throw_runtime_exception(std::string("Kokkos::Impl::ParallelFor< Cuda > insufficient shared memory"));
}
if ( int(m_team_size) >
int(Kokkos::Impl::cuda_get_max_block_size< ParallelFor >
( arg_functor , arg_policy.vector_length(), arg_policy.team_scratch_size(0),arg_policy.thread_scratch_size(0) ) / arg_policy.vector_length())) {
Kokkos::Impl::throw_runtime_exception(std::string("Kokkos::Impl::ParallelFor< Cuda > requested too large team size."));
}
}
};
} // namespace Impl
} // namespace Kokkos
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
namespace Kokkos {
namespace Impl {
template< class FunctorType , class ReducerType, class ... Traits >
class ParallelReduce< FunctorType
, Kokkos::RangePolicy< Traits ... >
, ReducerType
, Kokkos::Cuda
>
{
private:
typedef Kokkos::RangePolicy< Traits ... > Policy ;
typedef typename Policy::WorkRange WorkRange ;
typedef typename Policy::work_tag WorkTag ;
typedef typename Policy::member_type Member ;
typedef Kokkos::Impl::if_c< std::is_same<InvalidType,ReducerType>::value, FunctorType, ReducerType> ReducerConditional;
typedef typename ReducerConditional::type ReducerTypeFwd;
typedef Kokkos::Impl::FunctorValueTraits< ReducerTypeFwd, WorkTag > ValueTraits ;
typedef Kokkos::Impl::FunctorValueInit< ReducerTypeFwd, WorkTag > ValueInit ;
typedef Kokkos::Impl::FunctorValueJoin< ReducerTypeFwd, WorkTag > ValueJoin ;
public:
typedef typename ValueTraits::pointer_type pointer_type ;
typedef typename ValueTraits::value_type value_type ;
typedef typename ValueTraits::reference_type reference_type ;
typedef FunctorType functor_type ;
typedef Cuda::size_type size_type ;
// Algorithmic constraints: blockSize is a power of two AND blockDim.y == blockDim.z == 1
const FunctorType m_functor ;
const Policy m_policy ;
const ReducerType m_reducer ;
const pointer_type m_result_ptr ;
size_type * m_scratch_space ;
size_type * m_scratch_flags ;
size_type * m_unified_space ;
// Shall we use the shfl based reduction or not (only use it for static sized types of more than 128bit
enum { UseShflReduction = ((sizeof(value_type)>2*sizeof(double)) && ValueTraits::StaticValueSize) };
// Some crutch to do function overloading
private:
typedef double DummyShflReductionType;
typedef int DummySHMEMReductionType;
public:
template< class TagType >
__device__ inline
typename std::enable_if< std::is_same< TagType , void >::value >::type
exec_range( const Member & i , reference_type update ) const
{ m_functor( i , update ); }
template< class TagType >
__device__ inline
typename std::enable_if< ! std::is_same< TagType , void >::value >::type
exec_range( const Member & i , reference_type update ) const
{ m_functor( TagType() , i , update ); }
__device__ inline
void operator() () const {
run(Kokkos::Impl::if_c<UseShflReduction, DummyShflReductionType, DummySHMEMReductionType>::select(1,1.0) );
}
__device__ inline
void run(const DummySHMEMReductionType& ) const
{
const integral_nonzero_constant< size_type , ValueTraits::StaticValueSize / sizeof(size_type) >
word_count( ValueTraits::value_size( ReducerConditional::select(m_functor , m_reducer) ) / sizeof(size_type) );
{
reference_type value =
ValueInit::init( ReducerConditional::select(m_functor , m_reducer) , kokkos_impl_cuda_shared_memory<size_type>() + threadIdx.y * word_count.value );
// Number of blocks is bounded so that the reduction can be limited to two passes.
// Each thread block is given an approximately equal amount of work to perform.
// Accumulate the values for this block.
// The accumulation ordering does not match the final pass, but is arithmatically equivalent.
const WorkRange range( m_policy , blockIdx.x , gridDim.x );
for ( Member iwork = range.begin() + threadIdx.y , iwork_end = range.end() ;
iwork < iwork_end ; iwork += blockDim.y ) {
this-> template exec_range< WorkTag >( iwork , value );
}
}
// Reduce with final value at blockDim.y - 1 location.
if ( cuda_single_inter_block_reduce_scan<false,ReducerTypeFwd,WorkTag>(
ReducerConditional::select(m_functor , m_reducer) , blockIdx.x , gridDim.x ,
kokkos_impl_cuda_shared_memory<size_type>() , m_scratch_space , m_scratch_flags ) ) {
// This is the final block with the final result at the final threads' location
size_type * const shared = kokkos_impl_cuda_shared_memory<size_type>() + ( blockDim.y - 1 ) * word_count.value ;
size_type * const global = m_unified_space ? m_unified_space : m_scratch_space ;
if ( threadIdx.y == 0 ) {
Kokkos::Impl::FunctorFinal< ReducerTypeFwd , WorkTag >::final( ReducerConditional::select(m_functor , m_reducer) , shared );
}
if ( CudaTraits::WarpSize < word_count.value ) { __syncthreads(); }
for ( unsigned i = threadIdx.y ; i < word_count.value ; i += blockDim.y ) { global[i] = shared[i]; }
}
}
__device__ inline
void run(const DummyShflReductionType&) const
{
value_type value;
ValueInit::init( ReducerConditional::select(m_functor , m_reducer) , &value);
// Number of blocks is bounded so that the reduction can be limited to two passes.
// Each thread block is given an approximately equal amount of work to perform.
// Accumulate the values for this block.
// The accumulation ordering does not match the final pass, but is arithmatically equivalent.
const WorkRange range( m_policy , blockIdx.x , gridDim.x );
for ( Member iwork = range.begin() + threadIdx.y , iwork_end = range.end() ;
iwork < iwork_end ; iwork += blockDim.y ) {
this-> template exec_range< WorkTag >( iwork , value );
}
pointer_type const result = (pointer_type) (m_unified_space ? m_unified_space : m_scratch_space) ;
int max_active_thread = range.end()-range.begin() < blockDim.y ? range.end() - range.begin():blockDim.y;
max_active_thread = (max_active_thread == 0)?blockDim.y:max_active_thread;
value_type init;
ValueInit::init( ReducerConditional::select(m_functor , m_reducer) , &init);
if(Impl::cuda_inter_block_reduction<ReducerTypeFwd,ValueJoin,WorkTag>
(value,init,ValueJoin(ReducerConditional::select(m_functor , m_reducer)),m_scratch_space,result,m_scratch_flags,max_active_thread)) {
const unsigned id = threadIdx.y*blockDim.x + threadIdx.x;
if(id==0) {
Kokkos::Impl::FunctorFinal< ReducerTypeFwd , WorkTag >::final( ReducerConditional::select(m_functor , m_reducer) , (void*) &value );
*result = value;
}
}
}
// Determine block size constrained by shared memory:
static inline
unsigned local_block_size( const FunctorType & f )
{
unsigned n = CudaTraits::WarpSize * 8 ;
while ( n && CudaTraits::SharedMemoryCapacity < cuda_single_inter_block_reduce_scan_shmem<false,FunctorType,WorkTag>( f , n ) ) { n >>= 1 ; }
return n ;
}
inline
void execute()
{
const int nwork = m_policy.end() - m_policy.begin();
if ( nwork ) {
const int block_size = local_block_size( m_functor );
m_scratch_space = cuda_internal_scratch_space( ValueTraits::value_size( ReducerConditional::select(m_functor , m_reducer) ) * block_size /* block_size == max block_count */ );
m_scratch_flags = cuda_internal_scratch_flags( sizeof(size_type) );
m_unified_space = cuda_internal_scratch_unified( ValueTraits::value_size( ReducerConditional::select(m_functor , m_reducer) ) );
// REQUIRED ( 1 , N , 1 )
const dim3 block( 1 , block_size , 1 );
// Required grid.x <= block.y
const dim3 grid( std::min( int(block.y) , int( ( nwork + block.y - 1 ) / block.y ) ) , 1 , 1 );
const int shmem = UseShflReduction?0:cuda_single_inter_block_reduce_scan_shmem<false,FunctorType,WorkTag>( m_functor , block.y );
CudaParallelLaunch< ParallelReduce >( *this, grid, block, shmem ); // copy to device and execute
Cuda::fence();
if ( m_result_ptr ) {
if ( m_unified_space ) {
const int count = ValueTraits::value_count( ReducerConditional::select(m_functor , m_reducer) );
for ( int i = 0 ; i < count ; ++i ) { m_result_ptr[i] = pointer_type(m_unified_space)[i] ; }
}
else {
const int size = ValueTraits::value_size( ReducerConditional::select(m_functor , m_reducer) );
DeepCopy<HostSpace,CudaSpace>( m_result_ptr , m_scratch_space , size );
}
}
}
else {
if (m_result_ptr) {
ValueInit::init( ReducerConditional::select(m_functor , m_reducer) , m_result_ptr );
}
}
}
template< class HostViewType >
ParallelReduce( const FunctorType & arg_functor
, const Policy & arg_policy
, const HostViewType & arg_result
, typename std::enable_if<
Kokkos::is_view< HostViewType >::value
,void*>::type = NULL)
: m_functor( arg_functor )
, m_policy( arg_policy )
, m_reducer( InvalidType() )
, m_result_ptr( arg_result.ptr_on_device() )
, m_scratch_space( 0 )
, m_scratch_flags( 0 )
, m_unified_space( 0 )
{ }
ParallelReduce( const FunctorType & arg_functor
, const Policy & arg_policy
, const ReducerType & reducer)
: m_functor( arg_functor )
, m_policy( arg_policy )
, m_reducer( reducer )
, m_result_ptr( reducer.view().ptr_on_device() )
, m_scratch_space( 0 )
, m_scratch_flags( 0 )
, m_unified_space( 0 )
{ }
};
//----------------------------------------------------------------------------
#if 1
template< class FunctorType , class ReducerType, class ... Properties >
class ParallelReduce< FunctorType
, Kokkos::TeamPolicy< Properties ... >
, ReducerType
, Kokkos::Cuda
>
{
private:
typedef TeamPolicyInternal< Kokkos::Cuda, Properties ... > Policy ;
typedef typename Policy::member_type Member ;
typedef typename Policy::work_tag WorkTag ;
typedef Kokkos::Impl::if_c< std::is_same<InvalidType,ReducerType>::value, FunctorType, ReducerType> ReducerConditional;
typedef typename ReducerConditional::type ReducerTypeFwd;
typedef Kokkos::Impl::FunctorValueTraits< ReducerTypeFwd, WorkTag > ValueTraits ;
typedef Kokkos::Impl::FunctorValueInit< ReducerTypeFwd, WorkTag > ValueInit ;
typedef Kokkos::Impl::FunctorValueJoin< ReducerTypeFwd, WorkTag > ValueJoin ;
typedef typename ValueTraits::pointer_type pointer_type ;
typedef typename ValueTraits::reference_type reference_type ;
typedef typename ValueTraits::value_type value_type ;
public:
typedef FunctorType functor_type ;
typedef Cuda::size_type size_type ;
enum { UseShflReduction = (true && ValueTraits::StaticValueSize) };
private:
typedef double DummyShflReductionType;
typedef int DummySHMEMReductionType;
// Algorithmic constraints: blockDim.y is a power of two AND blockDim.y == blockDim.z == 1
// shared memory utilization:
//
// [ global reduce space ]
// [ team reduce space ]
// [ team shared space ]
//
const FunctorType m_functor ;
const ReducerType m_reducer ;
const pointer_type m_result_ptr ;
size_type * m_scratch_space ;
size_type * m_scratch_flags ;
size_type * m_unified_space ;
size_type m_team_begin ;
size_type m_shmem_begin ;
size_type m_shmem_size ;
void* m_scratch_ptr[2] ;
int m_scratch_size[2] ;
const size_type m_league_size ;
const size_type m_team_size ;
const size_type m_vector_size ;
template< class TagType >
__device__ inline
typename std::enable_if< std::is_same< TagType , void >::value >::type
exec_team( const Member & member , reference_type update ) const
{ m_functor( member , update ); }
template< class TagType >
__device__ inline
typename std::enable_if< ! std::is_same< TagType , void >::value >::type
exec_team( const Member & member , reference_type update ) const
{ m_functor( TagType() , member , update ); }
public:
__device__ inline
void operator() () const {
int threadid = 0;
if ( m_scratch_size[1]>0 ) {
__shared__ int base_thread_id;
if (threadIdx.x==0 && threadIdx.y==0 ) {
threadid = ((blockIdx.x*blockDim.z + threadIdx.z) * blockDim.x * blockDim.y) % kokkos_impl_cuda_lock_arrays.n;
threadid = ((threadid + blockDim.x * blockDim.y-1)/(blockDim.x * blockDim.y)) * blockDim.x * blockDim.y;
if(threadid > kokkos_impl_cuda_lock_arrays.n) threadid-=blockDim.x * blockDim.y;
int done = 0;
while (!done) {
done = (0 == atomicCAS(&kokkos_impl_cuda_lock_arrays.atomic[threadid],0,1));
if(!done) {
threadid += blockDim.x * blockDim.y;
if(threadid > kokkos_impl_cuda_lock_arrays.n) threadid = 0;
}
}
base_thread_id = threadid;
}
__syncthreads();
threadid = base_thread_id;
}
run(Kokkos::Impl::if_c<UseShflReduction, DummyShflReductionType, DummySHMEMReductionType>::select(1,1.0), threadid );
if ( m_scratch_size[1]>0 ) {
__syncthreads();
if (threadIdx.x==0 && threadIdx.y==0 )
kokkos_impl_cuda_lock_arrays.atomic[threadid]=0;
}
}
__device__ inline
void run(const DummySHMEMReductionType&, const int& threadid) const
{
const integral_nonzero_constant< size_type , ValueTraits::StaticValueSize / sizeof(size_type) >
word_count( ValueTraits::value_size( ReducerConditional::select(m_functor , m_reducer) ) / sizeof(size_type) );
reference_type value =
ValueInit::init( ReducerConditional::select(m_functor , m_reducer) , kokkos_impl_cuda_shared_memory<size_type>() + threadIdx.y * word_count.value );
// Iterate this block through the league
for ( int league_rank = blockIdx.x ; league_rank < m_league_size ; league_rank += gridDim.x ) {
this-> template exec_team< WorkTag >
( Member( kokkos_impl_cuda_shared_memory<char>() + m_team_begin
, m_shmem_begin
, m_shmem_size
, (void*) ( ((char*)m_scratch_ptr[1]) + threadid/(blockDim.x*blockDim.y) * m_scratch_size[1])
, m_scratch_size[1]
, league_rank
, m_league_size )
, value );
}
// Reduce with final value at blockDim.y - 1 location.
if ( cuda_single_inter_block_reduce_scan<false,FunctorType,WorkTag>(
ReducerConditional::select(m_functor , m_reducer) , blockIdx.x , gridDim.x ,
kokkos_impl_cuda_shared_memory<size_type>() , m_scratch_space , m_scratch_flags ) ) {
// This is the final block with the final result at the final threads' location
size_type * const shared = kokkos_impl_cuda_shared_memory<size_type>() + ( blockDim.y - 1 ) * word_count.value ;
size_type * const global = m_unified_space ? m_unified_space : m_scratch_space ;
if ( threadIdx.y == 0 ) {
Kokkos::Impl::FunctorFinal< ReducerTypeFwd , WorkTag >::final( ReducerConditional::select(m_functor , m_reducer) , shared );
}
if ( CudaTraits::WarpSize < word_count.value ) { __syncthreads(); }
for ( unsigned i = threadIdx.y ; i < word_count.value ; i += blockDim.y ) { global[i] = shared[i]; }
}
}
__device__ inline
void run(const DummyShflReductionType&, const int& threadid) const
{
value_type value;
ValueInit::init( ReducerConditional::select(m_functor , m_reducer) , &value);
// Iterate this block through the league
for ( int league_rank = blockIdx.x ; league_rank < m_league_size ; league_rank += gridDim.x ) {
this-> template exec_team< WorkTag >
( Member( kokkos_impl_cuda_shared_memory<char>() + m_team_begin
, m_shmem_begin
, m_shmem_size
, (void*) ( ((char*)m_scratch_ptr[1]) + threadid/(blockDim.x*blockDim.y) * m_scratch_size[1])
, m_scratch_size[1]
, league_rank
, m_league_size )
, value );
}
pointer_type const result = (pointer_type) (m_unified_space ? m_unified_space : m_scratch_space) ;
value_type init;
ValueInit::init( ReducerConditional::select(m_functor , m_reducer) , &init);
if(Impl::cuda_inter_block_reduction<FunctorType,ValueJoin,WorkTag>
(value,init,ValueJoin(ReducerConditional::select(m_functor , m_reducer)),m_scratch_space,result,m_scratch_flags,blockDim.y)) {
const unsigned id = threadIdx.y*blockDim.x + threadIdx.x;
if(id==0) {
Kokkos::Impl::FunctorFinal< ReducerTypeFwd , WorkTag >::final( ReducerConditional::select(m_functor , m_reducer) , (void*) &value );
*result = value;
}
}
}
inline
void execute()
{
const int nwork = m_league_size * m_team_size ;
if ( nwork ) {
const int block_count = UseShflReduction? std::min( m_league_size , size_type(1024) )
:std::min( m_league_size , m_team_size );
m_scratch_space = cuda_internal_scratch_space( ValueTraits::value_size( ReducerConditional::select(m_functor , m_reducer) ) * block_count );
m_scratch_flags = cuda_internal_scratch_flags( sizeof(size_type) );
m_unified_space = cuda_internal_scratch_unified( ValueTraits::value_size( ReducerConditional::select(m_functor , m_reducer) ) );
const dim3 block( m_vector_size , m_team_size , 1 );
const dim3 grid( block_count , 1 , 1 );
const int shmem_size_total = m_team_begin + m_shmem_begin + m_shmem_size ;
CudaParallelLaunch< ParallelReduce >( *this, grid, block, shmem_size_total ); // copy to device and execute
Cuda::fence();
if ( m_result_ptr ) {
if ( m_unified_space ) {
const int count = ValueTraits::value_count( ReducerConditional::select(m_functor , m_reducer) );
for ( int i = 0 ; i < count ; ++i ) { m_result_ptr[i] = pointer_type(m_unified_space)[i] ; }
}
else {
const int size = ValueTraits::value_size( ReducerConditional::select(m_functor , m_reducer) );
DeepCopy<HostSpace,CudaSpace>( m_result_ptr, m_scratch_space, size );
}
}
}
else {
if (m_result_ptr) {
ValueInit::init( ReducerConditional::select(m_functor , m_reducer) , m_result_ptr );
}
}
}
template< class HostViewType >
ParallelReduce( const FunctorType & arg_functor
, const Policy & arg_policy
, const HostViewType & arg_result
, typename std::enable_if<
Kokkos::is_view< HostViewType >::value
,void*>::type = NULL)
: m_functor( arg_functor )
, m_reducer( InvalidType() )
, m_result_ptr( arg_result.ptr_on_device() )
, m_scratch_space( 0 )
, m_scratch_flags( 0 )
, m_unified_space( 0 )
, m_team_begin( 0 )
, m_shmem_begin( 0 )
, m_shmem_size( 0 )
, m_scratch_ptr{NULL,NULL}
, m_league_size( arg_policy.league_size() )
, m_team_size( 0 <= arg_policy.team_size() ? arg_policy.team_size() :
Kokkos::Impl::cuda_get_opt_block_size< ParallelReduce >( arg_functor , arg_policy.vector_length(),
arg_policy.team_scratch_size(0),arg_policy.thread_scratch_size(0) ) /
arg_policy.vector_length() )
, m_vector_size( arg_policy.vector_length() )
, m_scratch_size{
arg_policy.scratch_size(0,( 0 <= arg_policy.team_size() ? arg_policy.team_size() :
Kokkos::Impl::cuda_get_opt_block_size< ParallelReduce >( arg_functor , arg_policy.vector_length(),
arg_policy.team_scratch_size(0),arg_policy.thread_scratch_size(0) ) /
arg_policy.vector_length() )
), arg_policy.scratch_size(1,( 0 <= arg_policy.team_size() ? arg_policy.team_size() :
Kokkos::Impl::cuda_get_opt_block_size< ParallelReduce >( arg_functor , arg_policy.vector_length(),
arg_policy.team_scratch_size(0),arg_policy.thread_scratch_size(0) ) /
arg_policy.vector_length() )
)}
{
// Return Init value if the number of worksets is zero
if( arg_policy.league_size() == 0) {
ValueInit::init( ReducerConditional::select(m_functor , m_reducer) , arg_result.ptr_on_device() );
return ;
}
m_team_begin = UseShflReduction?0:cuda_single_inter_block_reduce_scan_shmem<false,FunctorType,WorkTag>( arg_functor , m_team_size );
m_shmem_begin = sizeof(double) * ( m_team_size + 2 );
m_shmem_size = arg_policy.scratch_size(0,m_team_size) + FunctorTeamShmemSize< FunctorType >::value( arg_functor , m_team_size );
m_scratch_ptr[1] = cuda_resize_scratch_space(static_cast<std::int64_t>(m_scratch_size[1])*(static_cast<std::int64_t>(Cuda::concurrency()/(m_team_size*m_vector_size))));
m_scratch_size[0] = m_shmem_size;
m_scratch_size[1] = arg_policy.scratch_size(1,m_team_size);
// The global parallel_reduce does not support vector_length other than 1 at the moment
if( (arg_policy.vector_length() > 1) && !UseShflReduction )
Impl::throw_runtime_exception( "Kokkos::parallel_reduce with a TeamPolicy using a vector length of greater than 1 is not currently supported for CUDA for dynamic sized reduction types.");
if( (m_team_size < 32) && !UseShflReduction )
Impl::throw_runtime_exception( "Kokkos::parallel_reduce with a TeamPolicy using a team_size smaller than 32 is not currently supported with CUDA for dynamic sized reduction types.");
// Functor's reduce memory, team scan memory, and team shared memory depend upon team size.
const int shmem_size_total = m_team_begin + m_shmem_begin + m_shmem_size ;
if (! Kokkos::Impl::is_integral_power_of_two( m_team_size ) && !UseShflReduction ) {
Kokkos::Impl::throw_runtime_exception(std::string("Kokkos::Impl::ParallelReduce< Cuda > bad team size"));
}
if ( CudaTraits::SharedMemoryCapacity < shmem_size_total ) {
Kokkos::Impl::throw_runtime_exception(std::string("Kokkos::Impl::ParallelReduce< Cuda > requested too much L0 scratch memory"));
}
if ( unsigned(m_team_size) >
unsigned(Kokkos::Impl::cuda_get_max_block_size< ParallelReduce >
( arg_functor , arg_policy.vector_length(), arg_policy.team_scratch_size(0),arg_policy.thread_scratch_size(0) ) / arg_policy.vector_length())) {
Kokkos::Impl::throw_runtime_exception(std::string("Kokkos::Impl::ParallelReduce< Cuda > requested too large team size."));
}
}
ParallelReduce( const FunctorType & arg_functor
, const Policy & arg_policy
, const ReducerType & reducer)
: m_functor( arg_functor )
, m_reducer( reducer )
, m_result_ptr( reducer.view().ptr_on_device() )
, m_scratch_space( 0 )
, m_scratch_flags( 0 )
, m_unified_space( 0 )
, m_team_begin( 0 )
, m_shmem_begin( 0 )
, m_shmem_size( 0 )
, m_scratch_ptr{NULL,NULL}
, m_league_size( arg_policy.league_size() )
, m_team_size( 0 <= arg_policy.team_size() ? arg_policy.team_size() :
Kokkos::Impl::cuda_get_opt_block_size< ParallelReduce >( arg_functor , arg_policy.vector_length(),
arg_policy.team_scratch_size(0),arg_policy.thread_scratch_size(0) ) /
arg_policy.vector_length() )
, m_vector_size( arg_policy.vector_length() )
{
// Return Init value if the number of worksets is zero
if( arg_policy.league_size() == 0) {
ValueInit::init( ReducerConditional::select(m_functor , m_reducer) , m_result_ptr );
return ;
}
m_team_begin = UseShflReduction?0:cuda_single_inter_block_reduce_scan_shmem<false,FunctorType,WorkTag>( arg_functor , m_team_size );
m_shmem_begin = sizeof(double) * ( m_team_size + 2 );
m_shmem_size = arg_policy.scratch_size(0,m_team_size) + FunctorTeamShmemSize< FunctorType >::value( arg_functor , m_team_size );
m_scratch_ptr[1] = cuda_resize_scratch_space(m_scratch_size[1]*(Cuda::concurrency()/(m_team_size*m_vector_size)));
m_scratch_size[0] = m_shmem_size;
m_scratch_size[1] = arg_policy.scratch_size(1,m_team_size);
// The global parallel_reduce does not support vector_length other than 1 at the moment
if( (arg_policy.vector_length() > 1) && !UseShflReduction )
Impl::throw_runtime_exception( "Kokkos::parallel_reduce with a TeamPolicy using a vector length of greater than 1 is not currently supported for CUDA for dynamic sized reduction types.");
if( (m_team_size < 32) && !UseShflReduction )
Impl::throw_runtime_exception( "Kokkos::parallel_reduce with a TeamPolicy using a team_size smaller than 32 is not currently supported with CUDA for dynamic sized reduction types.");
// Functor's reduce memory, team scan memory, and team shared memory depend upon team size.
const int shmem_size_total = m_team_begin + m_shmem_begin + m_shmem_size ;
if ( (! Kokkos::Impl::is_integral_power_of_two( m_team_size ) && !UseShflReduction ) ||
CudaTraits::SharedMemoryCapacity < shmem_size_total ) {
Kokkos::Impl::throw_runtime_exception(std::string("Kokkos::Impl::ParallelReduce< Cuda > bad team size"));
}
if ( int(m_team_size) >
int(Kokkos::Impl::cuda_get_max_block_size< ParallelReduce >
( arg_functor , arg_policy.vector_length(), arg_policy.team_scratch_size(0),arg_policy.thread_scratch_size(0) ) / arg_policy.vector_length())) {
Kokkos::Impl::throw_runtime_exception(std::string("Kokkos::Impl::ParallelReduce< Cuda > requested too large team size."));
}
}
};
//----------------------------------------------------------------------------
#else
//----------------------------------------------------------------------------
template< class FunctorType , class ReducerType, class ... Properties >
class ParallelReduce< FunctorType
, Kokkos::TeamPolicy< Properties ... >
, ReducerType
, Kokkos::Cuda
>
{
private:
enum : int { align_scratch_value = 0x0100 /* 256 */ };
enum : int { align_scratch_mask = align_scratch_value - 1 };
KOKKOS_INLINE_FUNCTION static constexpr
int align_scratch( const int n )
{
return ( n & align_scratch_mask )
? n + align_scratch_value - ( n & align_scratch_mask ) : n ;
}
//----------------------------------------
// Reducer does not wrap a functor
template< class R = ReducerType , class F = void >
struct reducer_type : public R {
template< class S >
using rebind = reducer_type< typename R::rebind<S> , void > ;
KOKKOS_INLINE_FUNCTION
reducer_type( FunctorType const *
, ReducerType const * arg_reducer
, typename R::value_type * arg_value )
: R( *arg_reducer , arg_value ) {}
};
// Reducer does wrap a functor
template< class R >
struct reducer_type< R , FunctorType > : public R {
template< class S >
using rebind = reducer_type< typename R::rebind<S> , FunctorType > ;
KOKKOS_INLINE_FUNCTION
reducer_type( FunctorType const * arg_functor
, ReducerType const *
, typename R::value_type * arg_value )
: R( arg_functor , arg_value ) {}
};
//----------------------------------------
typedef TeamPolicyInternal< Kokkos::Cuda, Properties ... > Policy ;
typedef CudaTeamMember Member ;
typedef typename Policy::work_tag WorkTag ;
typedef typename reducer_type<>::pointer_type pointer_type ;
typedef typename reducer_type<>::reference_type reference_type ;
typedef typename reducer_type<>::value_type value_type ;
typedef Kokkos::Impl::FunctorAnalysis
< Kokkos::Impl::FunctorPatternInterface::REDUCE
, Policy
, FunctorType
> Analysis ;
public:
typedef FunctorType functor_type ;
typedef Cuda::size_type size_type ;
private:
const FunctorType m_functor ;
const reducer_type<> m_reducer ;
size_type * m_scratch_space ;
size_type * m_unified_space ;
size_type m_team_begin ;
size_type m_shmem_begin ;
size_type m_shmem_size ;
void* m_scratch_ptr[2] ;
int m_scratch_size[2] ;
const size_type m_league_size ;
const size_type m_team_size ;
const size_type m_vector_size ;
template< class TagType >
__device__ inline
typename std::enable_if< std::is_same< TagType , void >::value >::type
exec_team( const Member & member , reference_type update ) const
{ m_functor( member , update ); }
template< class TagType >
__device__ inline
typename std::enable_if< ! std::is_same< TagType , void >::value >::type
exec_team( const Member & member , reference_type update ) const
{ m_functor( TagType() , member , update ); }
public:
__device__ inline
void operator() () const
{
void * const shmem = kokkos_impl_cuda_shared_memory<char>();
const bool reduce_to_host =
std::is_same< typename reducer_type<>::memory_space
, Kokkos::HostSpace >::value &&
m_reducer.data();
value_type value ;
typename reducer_type<>::rebind< CudaSpace >
reduce( & m_functor , & m_reducer , & value );
reduce.init( reduce.data() );
// Iterate this block through the league
for ( int league_rank = blockIdx.x
; league_rank < m_league_size
; league_rank += gridDim.x ) {
// Initialization of team member data:
const Member member
( shmem
, m_shmem_team_begin
, m_shmem_team_size
, reinterpret_cast<char*>(m_scratch_space) + m_global_team_begin
, m_global_team_size
, league_rank
, m_league_size );
ParallelReduce::template
exec_team< WorkTag >( member , reduce.reference() );
}
if ( Member::global_reduce( reduce
, m_scratch_space
, reinterpret_cast<char*>(m_scratch_space)
+ aligned_flag_size
, shmem
, m_shmem_size ) ) {
// Single thread with data in value
reduce.final( reduce.data() );
if ( reduce_to_host ) {
reducer.copy( m_unified_space , reduce.data() );
}
}
}
inline
void execute()
{
const bool reduce_to_host =
std::is_same< typename reducer_type<>::memory_space
, Kokkos::HostSpace >::value &&
m_reducer.data();
const bool reduce_to_gpu =
std::is_same< typename reducer_type<>::memory_space
, Kokkos::CudaSpace >::value &&
m_reducer.data();
if ( m_league_size && m_team_size ) {
const int value_size = Analysis::value_size( m_functor );
m_scratch_space = cuda_internal_scratch_space( m_scratch_size );
m_unified_space = cuda_internal_scratch_unified( value_size );
const dim3 block( m_vector_size , m_team_size , m_team_per_block );
const dim3 grid( m_league_size , 1 , 1 );
const int shmem = m_shmem_team_begin + m_shmem_team_size ;
// copy to device and execute
CudaParallelLaunch<ParallelReduce>( *this, grid, block, shmem );
Cuda::fence();
if ( reduce_to_host ) {
m_reducer.copy( m_reducer.data() , pointer_type(m_unified_space) );
}
}
else if ( reduce_to_host ) {
m_reducer.init( m_reducer.data() );
}
else if ( reduce_to_gpu ) {
value_type tmp ;
m_reduce.init( & tmp );
cudaMemcpy( m_reduce.data() , & tmp , cudaMemcpyHostToDevice );
}
}
/**\brief Set up parameters and allocations for kernel launch.
*
* block = { vector_size , team_size , team_per_block }
* grid = { number_of_teams , 1 , 1 }
*
* shmem = shared memory for:
* [ team_reduce_buffer
* , team_scratch_buffer_level_0 ]
* reused by:
* [ global_reduce_buffer ]
*
* global_scratch for:
* [ global_reduce_flag_buffer
* , global_reduce_value_buffer
* , team_scratch_buffer_level_1 * max_concurrent_team ]
*/
ParallelReduce( FunctorType && arg_functor
, Policy && arg_policy
, ReducerType const & arg_reducer
)
: m_functor( arg_functor )
// the input reducer may wrap the input functor so must
// generate a reducer bound to the copied functor.
, m_reducer( & m_functor , & arg_reducer , arg_reducer.data() )
, m_scratch_space( 0 )
, m_unified_space( 0 )
, m_team_begin( 0 )
, m_shmem_begin( 0 )
, m_shmem_size( 0 )
, m_scratch_ptr{NULL,NULL}
, m_league_size( arg_policy.league_size() )
, m_team_per_block( 0 )
, m_team_size( arg_policy.team_size() )
, m_vector_size( arg_policy.vector_length() )
{
if ( 0 == m_league_size ) return ;
const int value_size = Analysis::value_size( m_functor );
//----------------------------------------
// Vector length must be <= WarpSize and power of two
const bool ok_vector = m_vector_size < CudaTraits::WarpSize &&
Kokkos::Impl::is_integral_power_of_two( m_vector_size );
//----------------------------------------
if ( 0 == m_team_size ) {
// Team size is AUTO, use a whole block per team.
// Calculate block size using the occupance calculator.
// Occupancy calculator assumes whole block.
m_team_size =
Kokkos::Impl::cuda_get_opt_block_size< ParallelReduce >
( arg_functor
, arg_policy.vector_length()
, arg_policy.team_scratch_size(0)
, arg_policy.thread_scratch_size(0) / arg_policy.vector_length() );
m_team_per_block = 1 ;
}
//----------------------------------------
// How many CUDA threads per team.
// If more than a warp or multiple teams cannot exactly fill a warp
// then only one team per block.
const int team_threads = m_team_size * m_vector_size ;
if ( ( CudaTraits::WarpSize < team_threads ) ||
( CudaTraits::WarpSize % team_threads ) ) {
m_team_per_block = 1 ;
}
//----------------------------------------
// How much team scratch shared memory determined from
// either the functor or the policy:
if ( CudaTraits::WarpSize < team_threads ) {
// Need inter-warp team reduction (collectives) shared memory
// Speculate an upper bound for the value size
m_shmem_team_begin =
align_scratch( CudaTraits::warp_count(team_threads) * sizeof(double) );
}
m_shmem_team_size = arg_policy.scratch_size(0,m_team_size);
if ( 0 == m_shmem_team_size ) {
m_shmem_team_size = Analysis::team_shmem_size( m_functor , m_team_size );
}
m_shmem_team_size = align_scratch( m_shmem_team_size );
// Can fit a team in a block:
const bool ok_shmem_team =
( m_shmem_team_begin + m_shmem_team_size )
< CudaTraits::SharedMemoryCapacity ;
//----------------------------------------
if ( 0 == m_team_per_block ) {
// Potentially more than one team per block.
// Determine number of teams per block based upon
// how much team scratch can fit and exactly filling each warp.
const int team_per_warp = team_threads / CudaTraits::WarpSize ;
const int max_team_per_block =
Kokkos::Impl::CudaTraits::SharedMemoryCapacity
/ shmem_team_scratch_size ;
for ( m_team_per_block = team_per_warp ;
m_team_per_block + team_per_warp < max_team_per_block ;
m_team_per_block += team_per_warp );
}
//----------------------------------------
// How much global reduce scratch shared memory.
int shmem_global_reduce_size = 8 * value_size ;
//----------------------------------------
// Global scratch memory requirements.
const int aligned_flag_size = align_scratch( sizeof(int) );
const int max_concurrent_block =
cuda_internal_maximum_concurrent_block_count();
// Reduce space has claim flag followed by vaue buffer
const int global_reduce_value_size =
max_concurrent_block *
( aligned_flag_size + align_scratch( value_size ) );
// Scratch space has claim flag followed by scratch buffer
const int global_team_scratch_size =
max_concurrent_block * m_team_per_block *
( aligned_flag_size +
align_scratch( arg_policy.scratch_size(1,m_team_size) / m_vector_size )
);
const int global_size = aligned_flag_size
+ global_reduce_value_size
+ global_team_scratch_size ;
m_global_reduce_begin = aligned_flag_size ;
m_global_team_begin = m_global_reduce_begin + global_reduce_value_size ;
m_global_size = m_global_team_begin + global_team_scratch_size ;
}
};
#endif
} // namespace Impl
} // namespace Kokkos
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
namespace Kokkos {
namespace Impl {
template< class FunctorType , class ... Traits >
class ParallelScan< FunctorType
, Kokkos::RangePolicy< Traits ... >
, Kokkos::Cuda
>
{
private:
typedef Kokkos::RangePolicy< Traits ... > Policy ;
typedef typename Policy::member_type Member ;
typedef typename Policy::work_tag WorkTag ;
typedef typename Policy::WorkRange WorkRange ;
typedef Kokkos::Impl::FunctorValueTraits< FunctorType, WorkTag > ValueTraits ;
typedef Kokkos::Impl::FunctorValueInit< FunctorType, WorkTag > ValueInit ;
typedef Kokkos::Impl::FunctorValueOps< FunctorType, WorkTag > ValueOps ;
public:
typedef typename ValueTraits::pointer_type pointer_type ;
typedef typename ValueTraits::reference_type reference_type ;
typedef FunctorType functor_type ;
typedef Cuda::size_type size_type ;
private:
// Algorithmic constraints:
// (a) blockDim.y is a power of two
// (b) blockDim.y == blockDim.z == 1
// (c) gridDim.x <= blockDim.y * blockDim.y
// (d) gridDim.y == gridDim.z == 1
const FunctorType m_functor ;
const Policy m_policy ;
size_type * m_scratch_space ;
size_type * m_scratch_flags ;
size_type m_final ;
template< class TagType >
__device__ inline
typename std::enable_if< std::is_same< TagType , void >::value >::type
exec_range( const Member & i , reference_type update , const bool final_result ) const
{ m_functor( i , update , final_result ); }
template< class TagType >
__device__ inline
typename std::enable_if< ! std::is_same< TagType , void >::value >::type
exec_range( const Member & i , reference_type update , const bool final_result ) const
{ m_functor( TagType() , i , update , final_result ); }
//----------------------------------------
__device__ inline
void initial(void) const
{
const integral_nonzero_constant< size_type , ValueTraits::StaticValueSize / sizeof(size_type) >
word_count( ValueTraits::value_size( m_functor ) / sizeof(size_type) );
size_type * const shared_value = kokkos_impl_cuda_shared_memory<size_type>() + word_count.value * threadIdx.y ;
ValueInit::init( m_functor , shared_value );
// Number of blocks is bounded so that the reduction can be limited to two passes.
// Each thread block is given an approximately equal amount of work to perform.
// Accumulate the values for this block.
// The accumulation ordering does not match the final pass, but is arithmatically equivalent.
const WorkRange range( m_policy , blockIdx.x , gridDim.x );
for ( Member iwork = range.begin() + threadIdx.y , iwork_end = range.end() ;
iwork < iwork_end ; iwork += blockDim.y ) {
this-> template exec_range< WorkTag >( iwork , ValueOps::reference( shared_value ) , false );
}
// Reduce and scan, writing out scan of blocks' totals and block-groups' totals.
// Blocks' scan values are written to 'blockIdx.x' location.
// Block-groups' scan values are at: i = ( j * blockDim.y - 1 ) for i < gridDim.x
cuda_single_inter_block_reduce_scan<true,FunctorType,WorkTag>( m_functor , blockIdx.x , gridDim.x , kokkos_impl_cuda_shared_memory<size_type>() , m_scratch_space , m_scratch_flags );
}
//----------------------------------------
__device__ inline
void final(void) const
{
const integral_nonzero_constant< size_type , ValueTraits::StaticValueSize / sizeof(size_type) >
word_count( ValueTraits::value_size( m_functor ) / sizeof(size_type) );
// Use shared memory as an exclusive scan: { 0 , value[0] , value[1] , value[2] , ... }
size_type * const shared_data = kokkos_impl_cuda_shared_memory<size_type>();
size_type * const shared_prefix = shared_data + word_count.value * threadIdx.y ;
size_type * const shared_accum = shared_data + word_count.value * ( blockDim.y + 1 );
// Starting value for this thread block is the previous block's total.
if ( blockIdx.x ) {
size_type * const block_total = m_scratch_space + word_count.value * ( blockIdx.x - 1 );
for ( unsigned i = threadIdx.y ; i < word_count.value ; ++i ) { shared_accum[i] = block_total[i] ; }
}
else if ( 0 == threadIdx.y ) {
ValueInit::init( m_functor , shared_accum );
}
const WorkRange range( m_policy , blockIdx.x , gridDim.x );
for ( typename Policy::member_type iwork_base = range.begin(); iwork_base < range.end() ; iwork_base += blockDim.y ) {
const typename Policy::member_type iwork = iwork_base + threadIdx.y ;
__syncthreads(); // Don't overwrite previous iteration values until they are used
ValueInit::init( m_functor , shared_prefix + word_count.value );
// Copy previous block's accumulation total into thread[0] prefix and inclusive scan value of this block
for ( unsigned i = threadIdx.y ; i < word_count.value ; ++i ) {
shared_data[i + word_count.value] = shared_data[i] = shared_accum[i] ;
}
if ( CudaTraits::WarpSize < word_count.value ) { __syncthreads(); } // Protect against large scan values.
// Call functor to accumulate inclusive scan value for this work item
if ( iwork < range.end() ) {
this-> template exec_range< WorkTag >( iwork , ValueOps::reference( shared_prefix + word_count.value ) , false );
}
// Scan block values into locations shared_data[1..blockDim.y]
cuda_intra_block_reduce_scan<true,FunctorType,WorkTag>( m_functor , typename ValueTraits::pointer_type(shared_data+word_count.value) );
{
size_type * const block_total = shared_data + word_count.value * blockDim.y ;
for ( unsigned i = threadIdx.y ; i < word_count.value ; ++i ) { shared_accum[i] = block_total[i]; }
}
// Call functor with exclusive scan value
if ( iwork < range.end() ) {
this-> template exec_range< WorkTag >( iwork , ValueOps::reference( shared_prefix ) , true );
}
}
}
public:
//----------------------------------------
__device__ inline
void operator()(void) const
{
if ( ! m_final ) {
initial();
}
else {
final();
}
}
// Determine block size constrained by shared memory:
static inline
unsigned local_block_size( const FunctorType & f )
{
// blockDim.y must be power of two = 128 (4 warps) or 256 (8 warps) or 512 (16 warps)
// gridDim.x <= blockDim.y * blockDim.y
//
// 4 warps was 10% faster than 8 warps and 20% faster than 16 warps in unit testing
unsigned n = CudaTraits::WarpSize * 4 ;
while ( n && CudaTraits::SharedMemoryCapacity < cuda_single_inter_block_reduce_scan_shmem<false,FunctorType,WorkTag>( f , n ) ) { n >>= 1 ; }
return n ;
}
inline
void execute()
{
const int nwork = m_policy.end() - m_policy.begin();
if ( nwork ) {
enum { GridMaxComputeCapability_2x = 0x0ffff };
const int block_size = local_block_size( m_functor );
const int grid_max =
( block_size * block_size ) < GridMaxComputeCapability_2x ?
( block_size * block_size ) : GridMaxComputeCapability_2x ;
// At most 'max_grid' blocks:
const int max_grid = std::min( int(grid_max) , int(( nwork + block_size - 1 ) / block_size ));
// How much work per block:
const int work_per_block = ( nwork + max_grid - 1 ) / max_grid ;
// How many block are really needed for this much work:
const int grid_x = ( nwork + work_per_block - 1 ) / work_per_block ;
m_scratch_space = cuda_internal_scratch_space( ValueTraits::value_size( m_functor ) * grid_x );
m_scratch_flags = cuda_internal_scratch_flags( sizeof(size_type) * 1 );
const dim3 grid( grid_x , 1 , 1 );
const dim3 block( 1 , block_size , 1 ); // REQUIRED DIMENSIONS ( 1 , N , 1 )
const int shmem = ValueTraits::value_size( m_functor ) * ( block_size + 2 );
m_final = false ;
CudaParallelLaunch< ParallelScan >( *this, grid, block, shmem ); // copy to device and execute
m_final = true ;
CudaParallelLaunch< ParallelScan >( *this, grid, block, shmem ); // copy to device and execute
}
}
ParallelScan( const FunctorType & arg_functor ,
const Policy & arg_policy )
: m_functor( arg_functor )
, m_policy( arg_policy )
, m_scratch_space( 0 )
, m_scratch_flags( 0 )
, m_final( false )
{ }
};
} // namespace Impl
} // namespace Kokkos
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
namespace Kokkos {
namespace Impl {
template< class FunctorType, class ExecPolicy, class ValueType , class Tag = typename ExecPolicy::work_tag>
struct CudaFunctorAdapter {
const FunctorType f;
typedef ValueType value_type;
CudaFunctorAdapter(const FunctorType& f_):f(f_) {}
__device__ inline
void operator() (typename ExecPolicy::work_tag, const typename ExecPolicy::member_type& i, ValueType& val) const {
//Insert Static Assert with decltype on ValueType equals third argument type of FunctorType::operator()
f(typename ExecPolicy::work_tag(), i,val);
}
};
template< class FunctorType, class ExecPolicy, class ValueType >
struct CudaFunctorAdapter<FunctorType,ExecPolicy,ValueType,void> {
const FunctorType f;
typedef ValueType value_type;
CudaFunctorAdapter(const FunctorType& f_):f(f_) {}
__device__ inline
void operator() (const typename ExecPolicy::member_type& i, ValueType& val) const {
//Insert Static Assert with decltype on ValueType equals second argument type of FunctorType::operator()
f(i,val);
}
__device__ inline
void operator() (typename ExecPolicy::member_type& i, ValueType& val) const {
//Insert Static Assert with decltype on ValueType equals second argument type of FunctorType::operator()
f(i,val);
}
};
template<class FunctorType, class ResultType, class Tag, bool Enable = IsNonTrivialReduceFunctor<FunctorType>::value >
struct FunctorReferenceType {
typedef ResultType& reference_type;
};
template<class FunctorType, class ResultType, class Tag>
struct FunctorReferenceType<FunctorType, ResultType, Tag, true> {
typedef typename Kokkos::Impl::FunctorValueTraits< FunctorType ,Tag >::reference_type reference_type;
};
template< class FunctorTypeIn, class ExecPolicy, class ValueType>
struct ParallelReduceFunctorType<FunctorTypeIn,ExecPolicy,ValueType,Cuda> {
enum {FunctorHasValueType = IsNonTrivialReduceFunctor<FunctorTypeIn>::value };
typedef typename Kokkos::Impl::if_c<FunctorHasValueType, FunctorTypeIn, Impl::CudaFunctorAdapter<FunctorTypeIn,ExecPolicy,ValueType> >::type functor_type;
static functor_type functor(const FunctorTypeIn& functor_in) {
return Impl::if_c<FunctorHasValueType,FunctorTypeIn,functor_type>::select(functor_in,functor_type(functor_in));
}
};
}
} // namespace Kokkos
#endif /* defined( __CUDACC__ ) */
#endif /* #ifndef KOKKOS_CUDA_PARALLEL_HPP */
| ovilab/lammps | lib/kokkos/core/src/Cuda/Kokkos_Cuda_Parallel.hpp | C++ | gpl-2.0 | 67,491 |
<?php
namespace Addwiki\Mediawiki\Api\Tests\Unit\Client\Auth;
use Addwiki\Mediawiki\Api\Client\Auth\UserAndPasswordWithDomain;
use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
/**
* @covers Mediawiki\Api\Client\Auth\UserAndPasswordWithDomain
*/
class UserAndPasswordWithDomainTest extends TestCase {
/**
* @dataProvider provideValidConstruction
*/
public function testValidConstruction( string $user, string $pass, ?string $domain = null ): void {
$userAndPasswordWithDomain = new UserAndPasswordWithDomain( $user, $pass, $domain );
$this->assertSame( $user, $userAndPasswordWithDomain->getUsername() );
$this->assertSame( $pass, $userAndPasswordWithDomain->getPassword() );
$this->assertSame( $domain, $userAndPasswordWithDomain->getDomain() );
}
public function provideValidConstruction(): array {
return [
[ 'user', 'pass' ],
[ 'user', 'pass', 'domain' ],
];
}
/**
* @dataProvider provideInvalidConstruction
*/
public function testInvalidConstruction( string $user, string $pass, ?string $domain = null ): void {
$this->expectException( InvalidArgumentException::class );
new UserAndPasswordWithDomain( $user, $pass, $domain );
}
public function provideInvalidConstruction(): array {
return [
[ 'user', '' ],
[ '', 'pass' ],
[ '', '' ],
[ '', '', '' ],
[ 'aaa', 'aaa', '' ],
];
}
/**
* @dataProvider provideTestEquals
*/
public function testEquals( UserAndPasswordWithDomain $user1, UserAndPasswordWithDomain $user2, bool $shouldEqual ): void {
$this->assertSame( $shouldEqual, $user1->equals( $user2 ) );
$this->assertSame( $shouldEqual, $user2->equals( $user1 ) );
}
public function provideTestEquals(): array {
return [
[ new UserAndPasswordWithDomain( 'usera', 'passa' ), new UserAndPasswordWithDomain( 'usera', 'passa' ), true ],
[ new UserAndPasswordWithDomain( 'usera', 'passa', 'domain' ), new UserAndPasswordWithDomain( 'usera', 'passa', 'domain' ), true ],
[ new UserAndPasswordWithDomain( 'DIFF', 'passa' ), new UserAndPasswordWithDomain( 'usera', 'passa' ), false ],
[ new UserAndPasswordWithDomain( 'usera', 'DIFF' ), new UserAndPasswordWithDomain( 'usera', 'passa' ), false ],
[ new UserAndPasswordWithDomain( 'usera', 'passa' ), new UserAndPasswordWithDomain( 'DIFF', 'passa' ), false ],
[ new UserAndPasswordWithDomain( 'usera', 'passa' ), new UserAndPasswordWithDomain( 'usera', 'DIFF' ), false ],
];
}
}
| addwiki/mediawiki-api-base | tests/unit/Client/Auth/UserAndPasswordWithDomainTest.php | PHP | gpl-2.0 | 2,445 |
/* vim: set sw=4 sts=4 et foldmethod=syntax : */
/*
* Copyright (c) 2006, 2007 Ciaran McCreesh
*
* This file is part of the Paludis package manager. Paludis 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.
*
* Paludis 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 "console_task.hh"
#include "colour.hh"
#include <iostream>
#include <iomanip>
using namespace paludis;
ConsoleTask::ConsoleTask()
{
}
ConsoleTask::~ConsoleTask()
{
}
void
ConsoleTask::output_activity_start_message(const std::string & s) const
{
output_stream() << s << "..." << std::flush;
}
void
ConsoleTask::output_activity_end_message() const
{
output_stream() << std::endl;
}
void
ConsoleTask::output_heading(const std::string & s) const
{
output_stream() << std::endl << colour(cl_heading, s) << std::endl << std::endl;
}
void
ConsoleTask::output_xterm_title(const std::string & s) const
{
output_xterm_stream() << xterm_title(s);
}
void
ConsoleTask::output_starred_item(const std::string & s, const unsigned indent) const
{
if (0 != indent)
output_stream() << std::string(2 * indent, ' ') << "* " << s << std::endl;
else
output_stream() << "* " << s << std::endl;
}
void
ConsoleTask::output_starred_item_no_endl(const std::string & s) const
{
output_stream() << "* " << s;
}
void
ConsoleTask::output_unstarred_item(const std::string & s) const
{
output_stream() << s << std::endl;
}
void
ConsoleTask::output_no_endl(const std::string & s) const
{
output_stream() << s;
}
void
ConsoleTask::output_endl() const
{
output_stream() << std::endl;
}
std::ostream &
ConsoleTask::output_stream() const
{
return std::cout;
}
std::ostream &
ConsoleTask::output_xterm_stream() const
{
return std::cerr;
}
std::string
ConsoleTask::render_as_package_name(const std::string & s) const
{
return colour(cl_package_name, s);
}
std::string
ConsoleTask::render_as_repository_name(const std::string & s) const
{
return colour(cl_repository_name, s);
}
std::string
ConsoleTask::render_as_set_name(const std::string & s) const
{
return colour(cl_package_name, s);
}
std::string
ConsoleTask::render_as_tag(const std::string & s) const
{
return colour(cl_tag, s);
}
std::string
ConsoleTask::render_as_unimportant(const std::string & s) const
{
return colour(cl_unimportant, s);
}
std::string
ConsoleTask::render_as_slot_name(const std::string & s) const
{
return colour(cl_slot, s);
}
std::string
ConsoleTask::render_as_update_mode(const std::string & s) const
{
return colour(cl_updatemode, s);
}
std::string
ConsoleTask::render_as_error(const std::string & s) const
{
return colour(cl_error, s);
}
std::string
ConsoleTask::render_as_masked(const std::string & s) const
{
return colour(cl_masked, s);
}
std::string
ConsoleTask::render_as_visible(const std::string & s) const
{
return colour(cl_visible, s);
}
std::string
ConsoleTask::render_plural(int c, const std::string & s, const std::string & p) const
{
return 1 == c ? s : p;
}
void
ConsoleTask::output_left_column(const std::string & s, const unsigned indent) const
{
output_stream() << " " << std::string(indent, ' ') << std::setw(left_column_width()) << std::left << s << " ";
}
void
ConsoleTask::output_right_column(const std::string & s) const
{
output_stream() << s << std::endl;
}
int
ConsoleTask::left_column_width() const
{
return 24;
}
| pioto/paludis-pioto | src/output/console_task.cc | C++ | gpl-2.0 | 3,939 |
#include <string>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <iomanip>
#include <cmath>
#include <limits>
void int_to_char(int i, std::stringstream & ssc) {
if (isprint(i))
ssc << "'" << static_cast<char>(i) << "'";
else if (isascii(i))
ssc << "Non displayable";
else
ssc << "Impossible";
}
void set_precision(std::string entry, std::stringstream & ssd, std::stringstream & ssf) {
int precision = entry.find(".") == std::string::npos ? 1 : entry.size() - entry.find(".") - 1;
if (entry[entry.size() - 1] == 'f')
precision--;
if (precision == 0)
precision++;
ssf.precision(precision > 7 ? 7 : precision);
ssd.precision(precision > 15 ? 15 : precision);
}
int main(int ac, char **av) {
if (ac > 1) {
std::string entry = av[1];
std::stringstream ssc;
std::stringstream ssf;
std::stringstream ssi;
std::stringstream ssd;
ssf << std::fixed;
ssd << std::fixed;
if (entry[entry.size() - 1] == 'f' && entry.compare("inf") != 0 && entry.compare("-inf") != 0 &&
entry.compare("+inf") != 0) { //si float
std::cout << "Float type detected" << std::endl;
set_precision(entry, ssd, ssf);
float f = static_cast<float>(::atof(entry.c_str()));
if (isinf(f) || isnan(f)) { // si inf ou nan alors int et char impossible
ssc << "Impossible";
ssi << "Impossible";
}
else { // sinon convertion vers int et char
int i = static_cast<int>(f);
if (static_cast<float>(i) == f) {
int_to_char(i, ssc);
}
else
ssc << "Impossible";
if (f >= std::numeric_limits<int>::min() && f <= std::numeric_limits<int>::max())
ssi << i;
else
ssi << "Impossible";
}
ssf << f << "f";
ssd << static_cast<double>(f);
}
else if (entry.find(".") == std::string::npos && entry.find("inf") == std::string::npos &&
entry.find("nan") == std::string::npos && entry.find("NaN") == std::string::npos) { // si int
std::cout << "Int type detected" << std::endl;
ssf.precision(1);
ssd.precision(1);
int i = atoi(entry.c_str());
int_to_char(i, ssc); //conversion to char
ssf << static_cast<float>(i) << "f";
ssd << static_cast<double>(i);
ssi << i;
}
else /* sinon double */ {
std::cout << "Double type detected" << std::endl;
set_precision(entry, ssd, ssf);
double d = ::atof(entry.c_str());
if (isinf(d) || isnan(d)) {
ssc << "Impossible";
ssi << "Impossible";
}
else {
int i = static_cast<int>(d);
if (static_cast<double>(i) == d) {
int_to_char(i, ssc);
}
else
ssc << "Impossible";
if (d >= std::numeric_limits<int>::min() && d <= std::numeric_limits<int>::max())
ssi << i;
else
ssi << "Impossible";
}
ssd << d;
ssf << static_cast<float>(d) << "f";
}
std::cout << "char: " << ssc.str() << std::endl << "int: " << ssi.str() << std::endl << "float: "
<< ssf.str() << std::endl << "double: " << ssd.str() << std::endl;
}
return (0);
}
| ncharret/42 | piscine_cpp/j06/ex00/main.cpp | C++ | gpl-2.0 | 3,680 |
#include <string.h>
// geos
#include <geos/geom/PrecisionModel.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/Point.h>
#include <geos/io/WKTReader.h>
// boost
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace geos;
using namespace geos::io;
using namespace geos::geom;
/*reads in the PAIS data and generates MBB for spatial objects. */
int main(int argc, char** argv)
{
char * tag = NULL;
if (argc>1)
{
tag= argv[1];
}
GeometryFactory *gf = new GeometryFactory(new PrecisionModel(),0);
WKTReader *wkt_reader= new WKTReader(gf);
Geometry *poly ;
string DEL = " ";
vector<string> fields;
double low[2], high[2];
string input_line ;
while(cin && getline(cin, input_line) && !cin.eof())
{
boost::split(fields, input_line, boost::is_any_of("|"));
poly = wkt_reader->read(fields[4]);
const Envelope * env = poly->getEnvelopeInternal();
low [0] = env->getMinX();
low [1] = env->getMinY();
high [0] = env->getMaxX();
high [1] = env->getMaxY();
cout << fields[0]<< "|" << fields[1] << "|" << fields[2] << "|" <<fields[3] << "|";
cout << low[0] << DEL << low[1] << DEL << high[0] << DEL << high[1] << endl;
fields.clear();
}
cout.flush();
return 0;
}
| EmoryUniversity/SATO | step_tear/rtree/pais/GeneratePAISMBB.cc | C++ | gpl-2.0 | 1,417 |
<?php
namespace orangeplus\Five9WebServices\DataTypes;
/**
* Class CRMImportResult
*
* @package Five9WebServices\DataTypes
*/
class CRMImportResult
{
use \orangeplus\Five9WebServices\Castable;
/** @var int */
public $crmRecordsDeleted;
/** @var int */
public $crmRecordsInserted;
/** @var int */
public $crmRecordsUpdated;
/**
* @return int
*/
public function getCrmRecordsInserted()
{
return $this->crmRecordsInserted;
}
/**
* @param int $crmRecordsInserted
*/
public function setCrmRecordsInserted($crmRecordsInserted)
{
$this->crmRecordsInserted = $crmRecordsInserted;
}
/**
* @return int
*/
public function getCrmRecordsUpdated()
{
return $this->crmRecordsUpdated;
}
/**
* @param int $crmRecordsUpdated
*/
public function setCrmRecordsUpdated($crmRecordsUpdated)
{
$this->crmRecordsUpdated = $crmRecordsUpdated;
}
/**
* @return int
*/
public function getCrmRecordsDeleted()
{
return $this->crmRecordsDeleted;
}
/**
* @param int $crmRecordsDeleted
*/
public function setCrmRecordsDeleted($crmRecordsDeleted)
{
$this->crmRecordsDeleted = $crmRecordsDeleted;
}
} | KeithRockhold/Five9ClientLibrary | src/DataTypes/CRMImportResult.php | PHP | gpl-2.0 | 1,202 |
/////////////////////////////////////////////////////////////////////////////
// Name: src/msw/calctrl.cpp
// Purpose: wxCalendarCtrl implementation
// Author: Vadim Zeitlin
// Created: 2008-04-04
// RCS-ID: $Id: calctrl.cpp 66558 2011-01-04 09:14:40Z SC $
// Copyright: (C) 2008 Vadim Zeitlin <vadim@wxwidgets.org>
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_CALENDARCTRL
#ifndef WX_PRECOMP
#include "wx/msw/wrapwin.h"
#include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
#include "wx/msw/private.h"
#endif
#include "wx/calctrl.h"
#include "wx/msw/private/datecontrols.h"
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
namespace
{
// values of week days used by the native control
enum
{
MonthCal_Monday,
MonthCal_Tuesday,
MonthCal_Wednesday,
MonthCal_Thursday,
MonthCal_Friday,
MonthCal_Saturday,
MonthCal_Sunday
};
} // anonymous namespace
// ============================================================================
// implementation
// ============================================================================
// ----------------------------------------------------------------------------
// wxCalendarCtrl creation
// ----------------------------------------------------------------------------
void wxCalendarCtrl::Init()
{
m_marks =
m_holidays = 0;
}
bool
wxCalendarCtrl::Create(wxWindow *parent,
wxWindowID id,
const wxDateTime& dt,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name)
{
if ( !wxMSWDateControls::CheckInitialization() )
return false;
// we need the arrows for the navigation
style |= wxWANTS_CHARS;
// initialize the base class
if ( !CreateControl(parent, id, pos, size, style, wxDefaultValidator, name) )
return false;
// create the native control: this is a bit tricky as we want to receive
// double click events but the MONTHCAL_CLASS doesn't use CS_DBLCLKS style
// and so we create our own copy of it which does
static ClassRegistrar s_clsMonthCal;
if ( !s_clsMonthCal.IsInitialized() )
{
// get a copy of standard class and modify it
WNDCLASS wc;
if ( ::GetClassInfo(NULL, MONTHCAL_CLASS, &wc) )
{
wc.lpszClassName = wxT("_wx_SysMonthCtl32");
wc.style |= CS_DBLCLKS;
s_clsMonthCal.Register(wc);
}
else
{
wxLogLastError(wxT("GetClassInfoEx(SysMonthCal32)"));
}
}
const wxChar * const clsname = s_clsMonthCal.IsRegistered()
? s_clsMonthCal.GetName().wx_str()
: MONTHCAL_CLASS;
if ( !MSWCreateControl(clsname, wxEmptyString, pos, size) )
return false;
// initialize the control
UpdateFirstDayOfWeek();
SetDate(dt.IsValid() ? dt : wxDateTime::Today());
if ( SetHolidayAttrs() )
UpdateMarks();
Connect(wxEVT_LEFT_DOWN,
wxMouseEventHandler(wxCalendarCtrl::MSWOnClick));
Connect(wxEVT_LEFT_DCLICK,
wxMouseEventHandler(wxCalendarCtrl::MSWOnDoubleClick));
return true;
}
WXDWORD wxCalendarCtrl::MSWGetStyle(long style, WXDWORD *exstyle) const
{
WXDWORD styleMSW = wxCalendarCtrlBase::MSWGetStyle(style, exstyle);
// right now we don't support all native styles but we should add wx styles
// corresponding to MCS_NOTODAY and MCS_NOTODAYCIRCLE probably (TODO)
// for compatibility with the other versions, just turn off today display
// unconditionally for now
styleMSW |= MCS_NOTODAY;
// we also need this style for Mark() to work
styleMSW |= MCS_DAYSTATE;
if ( style & wxCAL_SHOW_WEEK_NUMBERS )
styleMSW |= MCS_WEEKNUMBERS;
return styleMSW;
}
void wxCalendarCtrl::SetWindowStyleFlag(long style)
{
const bool hadMondayFirst = HasFlag(wxCAL_MONDAY_FIRST);
wxCalendarCtrlBase::SetWindowStyleFlag(style);
if ( HasFlag(wxCAL_MONDAY_FIRST) != hadMondayFirst )
UpdateFirstDayOfWeek();
}
// ----------------------------------------------------------------------------
// wxCalendarCtrl geometry
// ----------------------------------------------------------------------------
// TODO: handle WM_WININICHANGE
wxSize wxCalendarCtrl::DoGetBestSize() const
{
RECT rc;
if ( !GetHwnd() || !MonthCal_GetMinReqRect(GetHwnd(), &rc) )
{
return wxCalendarCtrlBase::DoGetBestSize();
}
const wxSize best = wxRectFromRECT(rc).GetSize() + GetWindowBorderSize();
CacheBestSize(best);
return best;
}
wxCalendarHitTestResult
wxCalendarCtrl::HitTest(const wxPoint& pos,
wxDateTime *date,
wxDateTime::WeekDay *wd)
{
WinStruct<MCHITTESTINFO> hti;
// Vista and later SDKs add a few extra fields to MCHITTESTINFO which are
// not supported by the previous versions, as we don't use them anyhow we
// should pretend that we always use the old struct format to make the call
// below work on pre-Vista systems (see #11057)
#ifdef MCHITTESTINFO_V1_SIZE
hti.cbSize = MCHITTESTINFO_V1_SIZE;
#endif
hti.pt.x = pos.x;
hti.pt.y = pos.y;
switch ( MonthCal_HitTest(GetHwnd(), &hti) )
{
default:
case MCHT_CALENDARWEEKNUM:
wxFAIL_MSG( "unexpected" );
// fall through
case MCHT_NOWHERE:
case MCHT_CALENDARBK:
case MCHT_TITLEBK:
case MCHT_TITLEMONTH:
case MCHT_TITLEYEAR:
return wxCAL_HITTEST_NOWHERE;
case MCHT_CALENDARDATE:
if ( date )
date->SetFromMSWSysDate(hti.st);
return wxCAL_HITTEST_DAY;
case MCHT_CALENDARDAY:
if ( wd )
{
int day = hti.st.wDayOfWeek;
// the native control returns incorrect day of the week when
// the first day isn't Monday, i.e. the first column is always
// "Monday" even if its label is "Sunday", compensate for it
const int first = LOWORD(MonthCal_GetFirstDayOfWeek(GetHwnd()));
if ( first == MonthCal_Monday )
{
// as MonthCal_Monday is 0 while wxDateTime::Mon is 1,
// normally we need to do this to transform from MSW
// convention to wx one
day++;
day %= 7;
}
//else: but when the first day is MonthCal_Sunday, the native
// control still returns 0 (i.e. MonthCal_Monday) for the
// first column which looks like a bug in it but to work
// around it it's enough to not apply the correction above
*wd = static_cast<wxDateTime::WeekDay>(day);
}
return wxCAL_HITTEST_HEADER;
case MCHT_TITLEBTNNEXT:
return wxCAL_HITTEST_INCMONTH;
case MCHT_TITLEBTNPREV:
return wxCAL_HITTEST_DECMONTH;
case MCHT_CALENDARDATENEXT:
case MCHT_CALENDARDATEPREV:
return wxCAL_HITTEST_SURROUNDING_WEEK;
}
}
// ----------------------------------------------------------------------------
// wxCalendarCtrl operations
// ----------------------------------------------------------------------------
bool wxCalendarCtrl::SetDate(const wxDateTime& dt)
{
wxCHECK_MSG( dt.IsValid(), false, "invalid date" );
SYSTEMTIME st;
dt.GetAsMSWSysDate(&st);
if ( !MonthCal_SetCurSel(GetHwnd(), &st) )
{
wxLogDebug(wxT("DateTime_SetSystemtime() failed"));
return false;
}
m_date = dt.GetDateOnly();
return true;
}
wxDateTime wxCalendarCtrl::GetDate() const
{
#if wxDEBUG_LEVEL
SYSTEMTIME st;
if ( !MonthCal_GetCurSel(GetHwnd(), &st) )
{
wxASSERT_MSG( !m_date.IsValid(), "mismatch between data and control" );
return wxDefaultDateTime;
}
wxDateTime dt;
dt.SetFromMSWSysDate(st);
// Windows XP and earlier didn't include the time component into the
// returned date but Windows 7 does, so we can't compare the full objects
// in the same way under all the Windows versions, just compare their date
// parts
wxASSERT_MSG( dt.IsSameDate(m_date), "mismatch between data and control" );
#endif // wxDEBUG_LEVEL
return m_date;
}
bool wxCalendarCtrl::SetDateRange(const wxDateTime& dt1, const wxDateTime& dt2)
{
SYSTEMTIME st[2];
DWORD flags = 0;
if ( dt1.IsValid() )
{
dt1.GetAsMSWSysTime(st + 0);
flags |= GDTR_MIN;
}
if ( dt2.IsValid() )
{
dt2.GetAsMSWSysTime(st + 1);
flags |= GDTR_MAX;
}
if ( !MonthCal_SetRange(GetHwnd(), flags, st) )
{
wxLogDebug(wxT("MonthCal_SetRange() failed"));
}
return flags != 0;
}
bool wxCalendarCtrl::GetDateRange(wxDateTime *dt1, wxDateTime *dt2) const
{
SYSTEMTIME st[2];
DWORD flags = MonthCal_GetRange(GetHwnd(), st);
if ( dt1 )
{
if ( flags & GDTR_MIN )
dt1->SetFromMSWSysDate(st[0]);
else
*dt1 = wxDefaultDateTime;
}
if ( dt2 )
{
if ( flags & GDTR_MAX )
dt2->SetFromMSWSysDate(st[1]);
else
*dt2 = wxDefaultDateTime;
}
return flags != 0;
}
// ----------------------------------------------------------------------------
// other wxCalendarCtrl operations
// ----------------------------------------------------------------------------
bool wxCalendarCtrl::EnableMonthChange(bool enable)
{
if ( !wxCalendarCtrlBase::EnableMonthChange(enable) )
return false;
wxDateTime dtStart, dtEnd;
if ( !enable )
{
dtStart = GetDate();
dtStart.SetDay(1);
dtEnd = dtStart.GetLastMonthDay();
}
//else: leave them invalid to remove the restriction
SetDateRange(dtStart, dtEnd);
return true;
}
void wxCalendarCtrl::Mark(size_t day, bool mark)
{
wxCHECK_RET( day > 0 && day < 32, "invalid day" );
int mask = 1 << (day - 1);
if ( mark )
m_marks |= mask;
else
m_marks &= ~mask;
// calling Refresh() here is not enough to change the day appearance
UpdateMarks();
}
void wxCalendarCtrl::SetHoliday(size_t day)
{
wxCHECK_RET( day > 0 && day < 32, "invalid day" );
m_holidays |= 1 << (day - 1);
}
void wxCalendarCtrl::UpdateMarks()
{
// we show only one full month but there can be some days from the month
// before it and from the one after it so days from 3 different months can
// be partially shown
MONTHDAYSTATE states[3] = { 0 };
const DWORD nMonths = MonthCal_GetMonthRange(GetHwnd(), GMR_DAYSTATE, NULL);
// although in principle the calendar might not show any days from the
// preceding months, it seems like it always does, consider e.g. Feb 2010
// which starts on Monday and ends on Sunday and so could fit on 4 lines
// without showing any subsequent months -- the standard control still
// shows it on 6 lines and the number of visible months is still 3
//
// OTOH Windows 7 control can show all 12 months or even years or decades
// in its window if you "zoom out" of it by double clicking on free areas
// so the return value can be (much, in case of decades view) greater than
// 3 but in this case marks are not visible anyhow so simply ignore it
if ( nMonths < WXSIZEOF(states) )
{
wxFAIL_MSG("unexpectedly few months shown in the control");
}
else if ( nMonths == WXSIZEOF(states) )
{
// the fully visible month is the one in the middle
states[1] = m_marks | m_holidays;
if ( !MonthCal_SetDayState(GetHwnd(), nMonths, states) )
{
wxLogLastError(wxT("MonthCal_SetDayState"));
}
}
//else: not a month view at all
}
void wxCalendarCtrl::UpdateFirstDayOfWeek()
{
MonthCal_SetFirstDayOfWeek(GetHwnd(),
HasFlag(wxCAL_MONDAY_FIRST) ? MonthCal_Monday
: MonthCal_Sunday);
}
// ----------------------------------------------------------------------------
// wxCalendarCtrl events
// ----------------------------------------------------------------------------
bool wxCalendarCtrl::MSWOnNotify(int idCtrl, WXLPARAM lParam, WXLPARAM *result)
{
NMHDR* hdr = (NMHDR *)lParam;
switch ( hdr->code )
{
case MCN_SELCHANGE:
{
// we need to update m_date first, before calling the user code
// which expects GetDate() to return the new date
const wxDateTime dateOld = m_date;
const NMSELCHANGE * const sch = (NMSELCHANGE *)lParam;
m_date.SetFromMSWSysDate(sch->stSelStart);
// changing the year or the month results in a second dummy
// MCN_SELCHANGE event on this system which doesn't really
// change anything -- filter it out
if ( m_date != dateOld )
{
if ( GenerateAllChangeEvents(dateOld) )
{
// month changed, need to update the holidays if we use
// them
if ( SetHolidayAttrs() )
UpdateMarks();
}
}
}
break;
case MCN_GETDAYSTATE:
{
const NMDAYSTATE * const ds = (NMDAYSTATE *)lParam;
for ( int i = 0; i < ds->cDayState; i++ )
{
ds->prgDayState[i] = m_marks | m_holidays;
}
}
break;
default:
return wxCalendarCtrlBase::MSWOnNotify(idCtrl, lParam, result);
}
*result = 0;
return true;
}
void wxCalendarCtrl::MSWOnDoubleClick(wxMouseEvent& event)
{
if ( HitTest(event.GetPosition()) == wxCAL_HITTEST_DAY )
{
if ( GenerateEvent(wxEVT_CALENDAR_DOUBLECLICKED) )
return; // skip event.Skip() below
}
event.Skip();
}
void wxCalendarCtrl::MSWOnClick(wxMouseEvent& event)
{
// for some reason, the control doesn't get focus on its own when the user
// clicks in it
SetFocus();
event.Skip();
}
#endif // wxUSE_CALENDARCTRL
| flewrain/flewrain-dolphin | Externals/wxWidgets3/src/msw/calctrl.cpp | C++ | gpl-2.0 | 15,091 |
/*
* Created on 13-Dec-2004
* Created by Paul Gardner
* Copyright (C) 2004, 2005, 2006 Aelitis, All Rights Reserved.
*
* 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.
*
* AELITIS, SAS au capital de 46,603.30 euros
* 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France.
*
*/
package com.aelitis.azureus.core.proxy.socks.impl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import org.gudy.azureus2.core3.util.Debug;
import org.gudy.azureus2.core3.util.DirectByteBuffer;
import org.gudy.azureus2.core3.util.DirectByteBufferPool;
import org.gudy.azureus2.core3.util.HostNameToIPResolver;
import com.aelitis.azureus.core.networkmanager.admin.NetworkAdmin;
import com.aelitis.azureus.core.proxy.AEProxyConnection;
import com.aelitis.azureus.core.proxy.socks.AESocksProxy;
import com.aelitis.azureus.core.proxy.socks.AESocksProxyAddress;
import com.aelitis.azureus.core.proxy.socks.AESocksProxyConnection;
import com.aelitis.azureus.core.proxy.socks.AESocksProxyPlugableConnection;
/**
* @author parg
*
*/
public class
AESocksProxyPlugableConnectionDefault
implements AESocksProxyPlugableConnection
{
protected AESocksProxyConnection socks_connection;
protected AEProxyConnection connection;
protected SocketChannel source_channel;
protected SocketChannel target_channel;
protected proxyStateRelayData relay_data_state;
public
AESocksProxyPlugableConnectionDefault(
AESocksProxyConnection _socks_connection )
{
socks_connection = _socks_connection;
connection = socks_connection.getConnection();
source_channel = connection.getSourceChannel();
}
public String
getName()
{
if ( target_channel != null ){
return( target_channel.socket().getInetAddress() + ":" + target_channel.socket().getPort());
}
return( "" );
}
public InetAddress
getLocalAddress()
{
return( target_channel.socket().getInetAddress());
}
public int
getLocalPort()
{
return( target_channel.socket().getPort());
}
public void
connect(
AESocksProxyAddress _address )
throws IOException
{
InetAddress address = _address.getAddress();
if ( address == null ){
if ( socks_connection.areDNSLookupsEnabled()){
try{
address = HostNameToIPResolver.syncResolve( _address.getUnresolvedAddress());
}catch( Throwable e ){
}
}
if ( address == null ){
throw( new IOException( "DNS lookup of '" + _address.getUnresolvedAddress() + "' fails" ));
}
}
new proxyStateRelayConnect( new InetSocketAddress( address, _address.getPort()));
}
public void
relayData()
throws IOException
{
new proxyStateRelayData();
}
public void
close()
{
if ( target_channel != null ){
try{
connection.cancelReadSelect( target_channel );
connection.cancelWriteSelect( target_channel );
target_channel.close();
}catch( Throwable e ){
Debug.printStackTrace(e);
}
}
if ( relay_data_state != null ){
relay_data_state.destroy();
}
}
protected class
proxyStateRelayConnect
extends AESocksProxyState
{
protected InetSocketAddress address;
protected
proxyStateRelayConnect(
InetSocketAddress _address )
throws IOException
{
super( socks_connection );
address = _address;
// OK, we're almost ready to roll. Unregister the read select until we're
// connected
connection.cancelReadSelect( source_channel );
connection.setConnectState( this );
target_channel = SocketChannel.open();
InetAddress bindIP = NetworkAdmin.getSingleton().getMultiHomedOutgoingRoundRobinBindAddress(address.getAddress());
if ( bindIP != null ){
try{
target_channel.socket().bind( new InetSocketAddress( bindIP, 0 ) );
}catch( IOException e ){
if ( bindIP.isAnyLocalAddress()){
// no point in moaning here about this
}else{
// if the address is unresolved then the calculated bind address can be invalid
// (might pick an IPv6 address for example when this is unbindable). In this case
// carry on and attempt to connect as this will fail anyway
if ( ! ( e.getMessage().contains( "not supported" ) && address.isUnresolved())){
throw( e );
}
}
}
}
target_channel.configureBlocking( false );
target_channel.connect( address );
connection.requestConnectSelect( target_channel );
}
protected boolean
connectSupport(
SocketChannel sc )
throws IOException
{
if( !sc.finishConnect()){
throw( new IOException( "finishConnect returned false" ));
}
// if we've got a proxy chain, now's the time to negotiate the connection
AESocksProxy proxy = socks_connection.getProxy();
if ( proxy.getNextSOCKSProxyHost() != null ){
}
socks_connection.connected();
return( true );
}
}
protected class
proxyStateRelayData
extends AESocksProxyState
{
protected DirectByteBuffer source_buffer;
protected DirectByteBuffer target_buffer;
protected long outward_bytes = 0;
protected long inward_bytes = 0;
protected
proxyStateRelayData()
throws IOException
{
super( socks_connection );
source_buffer = DirectByteBufferPool.getBuffer( DirectByteBuffer.AL_PROXY_RELAY, 1024 );
target_buffer = DirectByteBufferPool.getBuffer( DirectByteBuffer.AL_PROXY_RELAY, 1024 );
relay_data_state = this;
if ( connection.isClosed()){
destroy();
throw( new IOException( "connection closed" ));
}
connection.setReadState( this );
connection.setWriteState( this );
connection.requestReadSelect( source_channel );
connection.requestReadSelect( target_channel );
connection.setConnected();
}
protected void
destroy()
{
if ( source_buffer != null ){
source_buffer.returnToPool();
source_buffer = null;
}
if ( target_buffer != null ){
target_buffer.returnToPool();
target_buffer = null;
}
}
protected boolean
readSupport(
SocketChannel sc )
throws IOException
{
connection.setTimeStamp();
SocketChannel chan1 = sc;
SocketChannel chan2 = sc==source_channel?target_channel:source_channel;
DirectByteBuffer read_buffer = sc==source_channel?source_buffer:target_buffer;
int len = read_buffer.read( DirectByteBuffer.SS_PROXY, chan1 );
if ( len == -1 ){
//means that the channel has been shutdown
connection.close();
}else{
if ( read_buffer.position( DirectByteBuffer.SS_PROXY ) > 0 ){
read_buffer.flip(DirectByteBuffer.SS_PROXY);
int written = read_buffer.write( DirectByteBuffer.SS_PROXY, chan2 );
if ( chan1 == source_channel ){
outward_bytes += written;
}else{
inward_bytes += written;
}
if ( read_buffer.hasRemaining(DirectByteBuffer.SS_PROXY)){
connection.cancelReadSelect( chan1 );
connection.requestWriteSelect( chan2 );
}else{
read_buffer.position(DirectByteBuffer.SS_PROXY, 0);
read_buffer.limit( DirectByteBuffer.SS_PROXY, read_buffer.capacity(DirectByteBuffer.SS_PROXY));
}
}
}
return( len > 0 );
}
protected boolean
writeSupport(
SocketChannel sc )
throws IOException
{
// socket SX -> SY via BX
// so if SX = source_channel then BX is target buffer
SocketChannel chan1 = sc;
SocketChannel chan2 = sc==source_channel?target_channel:source_channel;
DirectByteBuffer read_buffer = sc==source_channel?target_buffer:source_buffer;
int written = read_buffer.write( DirectByteBuffer.SS_PROXY, chan1 );
if ( chan1 == target_channel ){
outward_bytes += written;
}else{
inward_bytes += written;
}
if ( read_buffer.hasRemaining(DirectByteBuffer.SS_PROXY)){
connection.requestWriteSelect( chan1 );
}else{
read_buffer.position(DirectByteBuffer.SS_PROXY,0);
read_buffer.limit( DirectByteBuffer.SS_PROXY, read_buffer.capacity(DirectByteBuffer.SS_PROXY));
connection.requestReadSelect( chan2 );
}
return( written > 0 );
}
public String
getStateName()
{
String state = this.getClass().getName();
int pos = state.indexOf( "$");
state = state.substring(pos+1);
return( state +" [out=" + outward_bytes +",in=" + inward_bytes +"] " + source_buffer + " / " + target_buffer );
}
}
}
| AcademicTorrents/AcademicTorrents-Downloader | vuze/com/aelitis/azureus/core/proxy/socks/impl/AESocksProxyPlugableConnectionDefault.java | Java | gpl-2.0 | 9,591 |
// CS0111: A member `C.Foo<U>(U)' is already defined. Rename this member or use different parameter types
// Line : 12
public class C
{
void Foo (int i)
{
}
void Foo<T> (T i)
{
}
void Foo<U> (U i)
{
}
}
| xen2/mcs | errors/cs0111-4.cs | C# | gpl-2.0 | 217 |
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package libcore.java.util.concurrent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
public class ExecutionExceptionTest {
// Adding derived class to be able to test the protected constructors
private class TestExecutionException extends ExecutionException {
public TestExecutionException() {
super();
}
public TestExecutionException(String message) {
super(message);
}
}
/**
* constructor creates exception without any details
*/
@Test
public void testConstructNoMessage() {
ExecutionException exception = new TestExecutionException();
assertNull(exception.getMessage());
assertNull(exception.getCause());
}
/**
* constructor creates exception with detail message
*/
@Test
public void testConstructWithMessage() {
ExecutionException exception = new TestExecutionException("test");
assertEquals("test", exception.getMessage());
assertNull(exception.getCause());
}
/**
* constructor creates exception with detail message and cause
*/
@Test
public void testConstructWithMessageAndCause() {
Throwable cause = new Exception();
ExecutionException exception = new ExecutionException("test", cause);
assertEquals("test", exception.getMessage());
assertEquals(cause, exception.getCause());
}
}
| google/desugar_jdk_libs | jdk11/src/libcore/luni/src/test/java/libcore/java/util/concurrent/ExecutionExceptionTest.java | Java | gpl-2.0 | 2,219 |
<?php
/**
* MailPoet - Contact Form 7 Integration
*
* Add the mailpoet cf7 shortcode
*
* @author Patrick Rauland
* @since 1.0.0
*/
add_action( 'init', 'wpcf7_add_shortcode_mailpoetsignup', 5 );
function wpcf7_add_shortcode_mailpoetsignup() {
if( function_exists('wpcf7_add_shortcode') ) {
wpcf7_add_shortcode( array( 'mailpoetsignup', 'mailpoetsignup*' ),
'wpcf7_mailpoetsignup_shortcode_handler', true );
}
}
function wpcf7_mailpoetsignup_shortcode_handler( $tag ) {
// if cf7 is not active, leave
if( ! class_exists( 'WPCF7_Shortcode' ) )
return;
// create a new tag
$tag = new WPCF7_Shortcode( $tag );
// if the tag doesn't have a name, return empty handed
if( empty( $tag->name ) )
return '';
// check for errors and set the class
$validation_error = wpcf7_get_validation_error( $tag->name );
$class = wpcf7_form_controls_class( $tag->type );
// if there were errors, add class
if( $validation_error )
$class .= ' wpcf7-not-valid';
// init the atts array, add the class and id set in the shortcode
$atts = array();
$atts[ 'class' ] = $tag->get_class_option( $class );
$atts[ 'id' ] = $tag->get_option( 'id', 'id', true );
// get checkbox value
// first get all of the lists
$lists = wpcf7_mailpoetsignup_get_lists();
if( ! empty( $lists ) ) {
$checkbox_values = array();
// go through each list
foreach( $lists as $key => $l ) {
// check if that list was added to the form
if( $tag->has_option( 'mailpoet_list_' . $l[ 'list_id' ] ) ) {
// add the list into the array of checkbox values
$checkbox_values[] = 'mailpoet_list_'. $l[ 'list_id' ];
}
}
}
// do we have any lists?
if( ! empty ( $checkbox_values ) ) {
// implode them all into a comma separated string
$atts[ 'value' ] = implode( $checkbox_values, ',' );
} else {
// we apparently have no lists
// set a 0 so we know to add the user to Mailpoet but not to any specific list
$atts[ 'value' ] = '0';
}
// is it required?
if( $tag->is_required() )
$atts[ 'aria-required' ] = 'true';
// set default checked state
$atts[ 'checked' ] = ( $tag->has_option( 'default:on' ) ) ? 'checked' : '';
// default tag value
$value = (string) reset( $tag->values );
// if the tag has a default value, add it
if( '' !== $tag->content )
$value = $tag->content;
// if the tag has a posted value, add it
if( wpcf7_is_posted() && isset( $_POST[ $tag->name ] ) ) {
// $value = stripslashes_deep( $_POST[ $tag->name ] );
$atts[ 'checked' ] = 'checked';
} elseif ( wpcf7_is_posted() && ! isset( $_POST[ $tag->name ] ) ) {
$atts[ 'checked' ] = '';
}
// set the name and the id of the field
$atts[ 'name' ] = $tag->name;
$id = ( ! empty( $atts[ 'id' ] ) ) ? $atts[ 'id' ] : $atts[ 'name' ];
// put all of the atts into a string for the field
$atts = wpcf7_format_atts( $atts );
// get the content from the tag to make the checkbox label
$label = __( 'Sign up for the newsletter', 'mpcf7' );
$values = $tag->values;
if( isset( $values ) && ! empty( $values ) )
$label = esc_textarea( $values[0] );
// should the label be inside the span?
if( $tag->has_option( 'label-inside-span' ) ) {
// create the field
$html = sprintf(
'<span class="wpcf7-form-control-wrap %1$s"><input type="checkbox" %2$s /> <label for="%3$s">%4$s</label></span> %5$s',
$tag->name, $atts, $id, $value, $validation_error );
} else {
// create the field
$html = sprintf(
'<span class="wpcf7-form-control-wrap %1$s"><input type="checkbox" %2$s /> </span><label for="%3$s">%4$s</label> %5$s',
$tag->name, $atts, $id, $value, $validation_error );
}
return $html;
}
/* Validation filter */
add_filter( 'wpcf7_validate_mailpoetsignup', 'wpcf7_mailpoetsignup_validation_filter', 10, 2 );
add_filter( 'wpcf7_validate_mailpoetsignup*', 'wpcf7_mailpoetsignup_validation_filter', 10, 2 );
function wpcf7_mailpoetsignup_validation_filter( $result, $tag ) {
// make sure that CF7 is installed and active
if( ! class_exists( 'WPCF7_Shortcode' ) )
return;
//
$tag = new WPCF7_Shortcode( $tag );
// get the type and name
$type = $tag->type;
$name = $tag->name;
// if the tag was posted, set it
$value = isset( $_POST[ $name ] ) ? ( string ) $_POST[ $name ] : '';
// if it's required
if( 'mailpoetsignup*' == $type ) {
// and empty
if( '' == $value ) {
// then fail it
$result[ 'valid' ] = false;
$result[ 'reason' ][ $name ] = wpcf7_get_message( 'invalid_required' );
}
}
return $result;
}
/* Tag generator */
add_action( 'admin_init', 'wpcf7_add_tag_generator_mailpoetsignup', 20 );
function wpcf7_add_tag_generator_mailpoetsignup() {
if( ! class_exists( 'WPCF7_TagGenerator' ) )
return;
$tag_generator = WPCF7_TagGenerator::get_instance();
$tag_generator->add( 'mailpoetsignup', __( 'Mailpoet Signup', 'mpcf7' ),
'wpcf7_tg_pane_mailpoetsignup' );
}
function wpcf7_tg_pane_mailpoetsignup( $contact_form, $args = '' ) {
$args = wp_parse_args( $args, array() );
$type = 'mailpoetsignup';
$description = __( "Mailpoet Signup Form.", 'mpcf7' );
$desc_link = '';
?>
<div class="control-box">
<fieldset>
<legend><?php echo esc_html( $description ); ?></legend>
<table class="form-table">
<tbody>
<tr>
<th scope="row"><?php echo esc_html( __( 'Field type', 'contact-form-7' ) ); ?></th>
<td>
<fieldset>
<legend class="screen-reader-text"><?php echo esc_html( __( 'Field type', 'contact-form-7' ) ); ?></legend>
<label><input type="checkbox" name="required" /> <?php echo esc_html( __( 'Required field', 'contact-form-7' ) ); ?></label>
</fieldset>
</td>
</tr>
<tr>
<th scope="row"><?php echo esc_html( __( 'MailPoet Lists', 'contact-form-7' ) ); ?></th>
<td>
<?php
// print mailpoet lists
echo wpcf7_mailpoetsignup_get_list_inputs();
?>
</td>
</tr>
<tr>
<th scope="row"><label for="<?php echo esc_attr( $args[ 'content' ] . '-default:on' ); ?>"><?php echo esc_html( __( 'Checked by Default', 'contact-form-7' ) ); ?></label></th>
<td><input type="checkbox" name="default:on" class="option" /> <?php echo esc_html( __( "Make this checkbox checked by default?", 'contact-form-7' ) ); ?></td>
</tr>
<tr>
<th scope="row"><label for="<?php echo esc_attr( $args[ 'content' ] . '-values' ); ?>"><?php echo esc_html( __( 'Checkbox Label', 'contact-form-7' ) ); ?></label></th>
<td><input type="text" name="values" class="oneline" id="<?php echo esc_attr( $args[ 'content' ] . '-values' ); ?>" /><br />
</tr>
<tr>
<th scope="row"><label for="<?php echo esc_attr( $args[ 'content' ] . '-label-inside-span' ); ?>"><?php echo esc_html( __( 'Label Inside Span', 'contact-form-7' ) ); ?></label></th>
<td><input type="checkbox" name="label-inside-span" class="option" /> <?php echo esc_html( __( "Place the label inside the control wrap span?", 'contact-form-7' ) ); ?></td>
</tr>
<tr>
<th scope="row"><label for="<?php echo esc_attr( $args[ 'content' ] . '-name' ); ?>"><?php echo esc_html( __( 'Name', 'contact-form-7' ) ); ?></label></th>
<td><input type="text" name="name" class="tg-name oneline" id="<?php echo esc_attr( $args[ 'content' ] . '-name' ); ?>" /></td>
</tr>
<tr>
<th scope="row"><label for="<?php echo esc_attr( $args[ 'content' ] . '-id' ); ?>"><?php echo esc_html( __( 'Id attribute', 'contact-form-7' ) ); ?></label></th>
<td><input type="text" name="id" class="idvalue oneline option" id="<?php echo esc_attr( $args[ 'content' ] . '-id' ); ?>" /></td>
</tr>
<tr>
<th scope="row"><label for="<?php echo esc_attr( $args[ 'content' ] . '-class' ); ?>"><?php echo esc_html( __( 'Class attribute', 'contact-form-7' ) ); ?></label></th>
<td><input type="text" name="class" class="classvalue oneline option" id="<?php echo esc_attr( $args[ 'content' ] . '-class' ); ?>" /></td>
</tr>
</tbody>
</table>
</fieldset>
</div>
<div class="insert-box">
<input type="text" name="<?php echo $type; ?>" class="tag code" readonly="readonly" onfocus="this.select()" />
<div class="submitbox">
<input type="button" class="button button-primary insert-tag" value="<?php echo esc_attr( __( 'Insert Tag', 'contact-form-7' ) ); ?>" />
</div>
<br class="clear" />
<p class="description mail-tag"><label for="<?php echo esc_attr( $args[ 'content' ] . '-mailtag' ); ?>"><?php echo sprintf( esc_html( __( "To use the value input through this field in a mail field, you need to insert the corresponding mail-tag (%s) into the field on the Mail tab.", 'contact-form-7' ) ), '<strong><span class="mail-tag"></span></strong>' ); ?><input type="text" class="mail-tag code hidden" readonly="readonly" id="<?php echo esc_attr( $args[ 'content' ] . '-mailtag' ); ?>" /></label></p>
</div>
<?php
}
/* Process the form field */
add_action( 'wpcf7_before_send_mail', 'wpcf7_mailpoet_before_send_mail' );
function wpcf7_mailpoet_before_send_mail( $contactform ) {
// make sure the user has Mailpoet (Wysija) and CF7 installed & active
if( ! class_exists( 'WYSIJA' ) || ! class_exists( 'WPCF7_Submission' ) )
return;
//
if( ! empty( $contactform->skip_mail ) )
return;
//
$posted_data = null;
// get the instance that was submitted and the posted data
$submission = WPCF7_Submission::get_instance();
$posted_data = ( $submission ) ? $submission->get_posted_data() : null;
// and make sure they have something in their contact form
if( empty( $posted_data ) )
return;
// get the tags that are in the form
$manager = WPCF7_ShortcodeManager::get_instance();
$scanned_tags = $manager->get_scanned_tags();
// let's go add the user
wpcf7_mailpoet_subscribe_to_lists( $posted_data, $scanned_tags );
}
function wpcf7_mailpoet_subscribe_to_lists( $posted_data, $scanned_tags = array() ) {
// set defaults for mailpoet user data
$user_data = array(
'email' => '',
'firstname' => '',
'lastname' => ''
);
// get form data
$user_data[ 'email' ] = isset( $posted_data[ 'your-email' ] ) ? trim( $posted_data[ 'your-email' ] ) : '';
$user_data[ 'firstname' ] = isset( $posted_data[ 'your-name' ] ) ? trim( $posted_data[ 'your-name' ] ) : '';
if( isset( $posted_data[ 'your-first-name' ] ) && ! empty( $posted_data[ 'your-first-name' ] ) )
$user_data[ 'firstname' ] = trim( $posted_data[ 'your-first-name' ] );
if( isset( $posted_data[ 'your-last-name' ] ) && ! empty( $posted_data[ 'your-last-name' ] ) )
$user_data[ 'lastname' ] = trim( $posted_data[ 'your-last-name' ] );
// set up our arrays
$mailpoet_signups = array();
$mailpoet_lists = array();
// go through each tag and find our tags
foreach( $scanned_tags as $tag ) {
// if it's our tag, add it to the array
if( $tag[ 'basetype' ] == 'mailpoetsignup' )
$mailpoet_signups[] = $tag[ 'name' ];
}
// if we have signup fields
if( ! empty( $mailpoet_signups ) ) {
// go through each field
foreach( $mailpoet_signups as $mailpoet_signup_field ) {
// trim off our extra data
$_field = str_replace( 'mailpoet_list_', '', trim( $posted_data[ $mailpoet_signup_field ] ) );
// add the list id to the array
if( ! empty ( $_field ) )
$mailpoet_lists = array_unique( array_merge( $mailpoet_lists, explode( ',', $_field ) ) );
}
}
// if we have no lists, exit
if( empty( $mailpoet_lists ) )
return;
// configure the list
$data = array(
'user' => $user_data,
'user_list' => array( 'list_ids' => $mailpoet_lists )
);
// if akismet is set make sure it's valid
$akismet = isset( $contactform->akismet ) ? (array) $contactform->akismet : null;
$akismet = $akismet; // temporarily, not in use!
// add the subscriber to the Wysija list
$user_helper = WYSIJA::get( 'user', 'helper' );
$user_helper->addSubscriber( $data );
}
/**
* Create a formatted list of input's for the CF7 tag generator
*
* @return string
*/
function wpcf7_mailpoetsignup_get_list_inputs ( ) {
$html = '';
// get lists
$lists = wpcf7_mailpoetsignup_get_lists();
if ( is_array( $lists ) && ! empty( $lists ) ) {
foreach ( $lists as $key => $l ) {
// add input to returned html
$input_name = wpcf7_mailpoetsignup_get_list_input_field_name();
$input = "<input type='checkbox' name='" . $input_name . "' class='option' />%s<br />";
$html .= sprintf( $input, $l[ 'list_id' ], $l[ 'name' ] );
}
}
return $html;
}
/**
* Create input name for both the form processing & tag generation
*
* @return string
*/
function wpcf7_mailpoetsignup_get_list_input_field_name ( ) {
return 'mailpoet_list_%d';
}
add_filter( 'wpcf7_mail_tag_replaced', 'wpcf7_mail_tag_replaced_mailpoetsignup', 10, 2 );
/**
*
* @param string $replaced modifier
* @param string $submitted submitted value from contact form
* @return string
*/
function wpcf7_mail_tag_replaced_mailpoetsignup($replaced, $submitted) {
if (wpcf7_is_mailpoetsignup_element($submitted)) {
$list_names = wpcf7_get_list_names(explode(',', $submitted));
$replaced = implode(', ', $list_names);
}
return $replaced;
}
/**
* Get name of lists based on their ids
* @param array $list_ids
*/
function wpcf7_get_list_names(Array $list_ids = array()) {
// make sure we have the class loaded
$mailpoet_lists = array();
if (class_exists( 'WYSIJA' )) {
// get MailPoet / Wysija lists
$model_list = WYSIJA::get('list','model');
$result = $model_list->get( array( 'name' ), array( 'list_id' => $list_ids) );
foreach ($result as $list) {
$mailpoet_lists[] = $list[ 'name' ];
}
}
return $mailpoet_lists;
}
/**
* Make sure the current element is mailpoetsignup
* @param string $submitted submitted value from contact form
* @return boolean
*/
function wpcf7_is_mailpoetsignup_element( $submitted ) {
// for Contact-Form-7 3.9 and above, http://contactform7.com/2014/07/02/contact-form-7-39-beta/
if( class_exists( 'WPCF7_Submission' ) ) {
// get the submission object
$submission = WPCF7_Submission::get_instance();
// if there's an object, get the posted data
if( $submission )
$posted_data = $submission->get_posted_data();
} else {
// if they are on an old version of cf7, get straight _POST data
$posted_data = $_POST;
}
// if we have data
if( ! empty( $posted_data ) ) {
// find all of the keys in $posted_data that belong to mailpoet-cf7's plugin
$keys = array_keys( $posted_data );
$mailpoet_signups = preg_grep( '/^mailpoetsignup.*/', $keys );
// if we have posted fields
if( ! empty( $mailpoet_signups ) ) {
// go through each one
foreach( $mailpoet_signups as $mailpoet_signup_field ) {
// get the value
$_field = trim( $posted_data[ $mailpoet_signup_field ] );
// and see if it matches
if( $_field == $submitted )
return true;
}
}
}
return false;
}
// that's all folks! | jessepearson/mailpoet-contact-form-7 | modules/mailpoet-signup.php | PHP | gpl-2.0 | 15,418 |
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2014 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "dated_copy.h"
#include "dirname.h"
#include "basename.h"
#include <ctime>
#include <fstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
IGL_INLINE bool igl::dated_copy(const std::string & src_path, const std::string & dir)
{
using namespace std;
using namespace igl;
// Get time and date as string
char buffer[80];
time_t rawtime;
struct tm * timeinfo;
time (&rawtime);
timeinfo = localtime (&rawtime);
// ISO 8601 format with hyphens instead of colons and no timezone offset
strftime (buffer,80,"%Y-%m-%dT%H-%M-%S",timeinfo);
string src_basename = basename(src_path);
string dst_basename = src_basename+"-"+buffer;
string dst_path = dir+"/"+dst_basename;
cerr<<"Saving binary to "<<dst_path;
{
// http://stackoverflow.com/a/10195497/148668
ifstream src(src_path,ios::binary);
if (!src.is_open())
{
cerr<<" failed."<<endl;
return false;
}
ofstream dst(dst_path,ios::binary);
if(!dst.is_open())
{
cerr<<" failed."<<endl;
return false;
}
dst << src.rdbuf();
}
cerr<<" succeeded."<<endl;
cerr<<"Setting permissions of "<<dst_path;
{
int src_posix = fileno(fopen(src_path.c_str(),"r"));
if(src_posix == -1)
{
cerr<<" failed."<<endl;
return false;
}
struct stat fst;
fstat(src_posix,&fst);
int dst_posix = fileno(fopen(dst_path.c_str(),"r"));
if(dst_posix == -1)
{
cerr<<" failed."<<endl;
return false;
}
//update to the same uid/gid
if(fchown(dst_posix,fst.st_uid,fst.st_gid))
{
cerr<<" failed."<<endl;
return false;
}
//update the permissions
if(fchmod(dst_posix,fst.st_mode) == -1)
{
cerr<<" failed."<<endl;
return false;
}
cerr<<" succeeded."<<endl;
}
return true;
}
IGL_INLINE bool igl::dated_copy(const std::string & src_path)
{
return dated_copy(src_path,dirname(src_path));
}
| tlgimenes/SparseModelingOfIntrinsicCorrespondences | external/igl/dated_copy.cpp | C++ | gpl-2.0 | 2,314 |
///////////////////////////////////////////////////////////////////////////////
// For information as to what this class does, see the Javadoc, below. //
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, //
// 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph //
// Ramsey, and Clark Glymour. //
// //
// 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 //
///////////////////////////////////////////////////////////////////////////////
package edu.cmu.tetrad.search;
import edu.cmu.tetrad.data.DataModel;
import edu.cmu.tetrad.data.DataSet;
import edu.cmu.tetrad.data.DiscreteVariable;
import edu.cmu.tetrad.data.ICovarianceMatrix;
import edu.cmu.tetrad.graph.IndependenceFact;
import edu.cmu.tetrad.graph.Node;
import edu.cmu.tetrad.util.TetradMatrix;
import edu.pitt.dbmi.algo.bayesian.constraint.inference.BCInference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Uses BCInference by Cooper and Bui to calculate probabilistic conditional independence judgments.
*
* @author Joseph Ramsey 3/2014
*/
public class ProbabilisticMAPIndependence implements IndependenceTest {
/**
* Calculates probabilities of independence for conditional independence facts.
*/
private final BCInference bci;
/**
* The data set for which conditional independence judgments are requested.
*/
private final DataSet data;
/**
* The nodes of the data set.
*/
private List<Node> nodes;
/**
* Indices of the nodes.
*/
private Map<Node, Integer> indices;
/**
* A map from independence facts to their probabilities of independence.
*/
private Map<IndependenceFact, Double> H;
private double posterior;
/**
* Initializes the test using a discrete data sets.
*/
public ProbabilisticMAPIndependence(DataSet dataSet) {
this.data = dataSet;
int[] counts = new int[dataSet.getNumColumns() + 2];
for (int j = 0; j < dataSet.getNumColumns(); j++) {
counts[j + 1] = ((DiscreteVariable) (dataSet.getVariable(j))).getNumCategories();
}
if (!dataSet.isDiscrete()) {
throw new IllegalArgumentException("Not a discrete data set.");
}
int[][] cases = new int[dataSet.getNumRows() + 1][dataSet.getNumColumns() + 2];
for (int i = 0; i < dataSet.getNumRows(); i++) {
for (int j = 0; j < dataSet.getNumColumns(); j++) {
cases[i + 1][j + 1] = dataSet.getInt(i, j) + 1;
}
}
bci = new BCInference(cases, counts);
nodes = dataSet.getVariables();
indices = new HashMap<Node, Integer>();
for (int i = 0; i < nodes.size(); i++) {
indices.put(nodes.get(i), i);
}
this.H = new HashMap<IndependenceFact, Double>();
}
@Override
public IndependenceTest indTestSubset(List<Node> vars) {
throw new UnsupportedOperationException();
}
@Override
public boolean isIndependent(Node x, Node y, List<Node> z) {
Node[] _z = z.toArray(new Node[z.size()]);
return isIndependent(x, y, _z);
}
@Override
public boolean isIndependent(Node x, Node y, Node... z) {
// IndependenceFact key = new IndependenceFact(x, y, z);
//
// if (!H.containsKey(key)) {
double pInd = probConstraint(BCInference.OP.independent, x, y, z);
// H.put(key, pInd);
// }
//
// double pInd = H.get(key);
double p = probOp(BCInference.OP.independent, pInd);
this.posterior = p;
return p > 0.5;
// if (RandomUtil.getInstance().nextDouble() < p) {
// return true;
// }
// else {
// return false;
// }
}
public double probConstraint(BCInference.OP op, Node x, Node y, Node[] z) {
int _x = indices.get(x) + 1;
int _y = indices.get(y) + 1;
int[] _z = new int[z.length + 1];
_z[0] = z.length;
for (int i = 0; i < z.length; i++) _z[i + 1] = indices.get(z[i]) + 1;
return bci.probConstraint(op, _x, _y, _z);
}
@Override
public boolean isDependent(Node x, Node y, List<Node> z) {
Node[] _z = z.toArray(new Node[z.size()]);
return !isIndependent(x, y, _z);
}
@Override
public boolean isDependent(Node x, Node y, Node... z) {
return !isIndependent(x, y, z);
}
@Override
public double getPValue() {
return posterior;
}
@Override
public List<Node> getVariables() {
return nodes;
}
@Override
public Node getVariable(String name) {
for (Node node : nodes) {
if (name.equals(node.getName())) return node;
}
return null;
}
@Override
public List<String> getVariableNames() {
List<String> names = new ArrayList<String>();
for (Node node : nodes) {
names.add(node.getName());
}
return names;
}
@Override
public boolean determines(List<Node> z, Node y) {
throw new UnsupportedOperationException();
}
@Override
public double getAlpha() {
throw new UnsupportedOperationException();
}
@Override
public void setAlpha(double alpha) {
throw new UnsupportedOperationException();
}
@Override
public DataModel getData() {
return data;
}
@Override
public ICovarianceMatrix getCov() {
return null;
}
@Override
public List<DataSet> getDataSets() {
return null;
}
@Override
public int getSampleSize() {
return 0;
}
@Override
public List<TetradMatrix> getCovMatrices() {
return null;
}
@Override
public double getScore() {
return getPValue();
}
public Map<IndependenceFact, Double> getH() {
return new HashMap<IndependenceFact, Double>(H);
}
private double probOp(BCInference.OP type, double pInd) {
double probOp;
if (BCInference.OP.independent == type) {
probOp = pInd;
} else {
probOp = 1.0 - pInd;
}
return probOp;
}
public double getPosterior() {
return posterior;
}
}
| ajsedgewick/tetrad | tetrad-lib/src/main/java/edu/cmu/tetrad/search/ProbabilisticMAPIndependence.java | Java | gpl-2.0 | 7,454 |
namespace Shadowsocks.View
{
partial class LogForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.LogMessageTextBox = new System.Windows.Forms.TextBox();
this.MainMenu = new System.Windows.Forms.MainMenu(this.components);
this.FileMenuItem = new System.Windows.Forms.MenuItem();
this.OpenLocationMenuItem = new System.Windows.Forms.MenuItem();
this.ExitMenuItem = new System.Windows.Forms.MenuItem();
this.ViewMenuItem = new System.Windows.Forms.MenuItem();
this.CleanLogsMenuItem = new System.Windows.Forms.MenuItem();
this.ChangeFontMenuItem = new System.Windows.Forms.MenuItem();
this.WrapTextMenuItem = new System.Windows.Forms.MenuItem();
this.TopMostMenuItem = new System.Windows.Forms.MenuItem();
this.MenuItemSeparater = new System.Windows.Forms.MenuItem();
this.ShowToolbarMenuItem = new System.Windows.Forms.MenuItem();
this.TopMostCheckBox = new System.Windows.Forms.CheckBox();
this.ChangeFontButton = new System.Windows.Forms.Button();
this.CleanLogsButton = new System.Windows.Forms.Button();
this.WrapTextCheckBox = new System.Windows.Forms.CheckBox();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.ToolbarFlowLayoutPanel = new System.Windows.Forms.FlowLayoutPanel();
this.tableLayoutPanel1.SuspendLayout();
this.ToolbarFlowLayoutPanel.SuspendLayout();
this.SuspendLayout();
//
// LogMessageTextBox
//
this.LogMessageTextBox.BackColor = System.Drawing.Color.Black;
this.LogMessageTextBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.LogMessageTextBox.Font = new System.Drawing.Font("Consolas", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.LogMessageTextBox.ForeColor = System.Drawing.Color.White;
this.LogMessageTextBox.Location = new System.Drawing.Point(3, 38);
this.LogMessageTextBox.MaxLength = 2147483647;
this.LogMessageTextBox.Multiline = true;
this.LogMessageTextBox.Name = "LogMessageTextBox";
this.LogMessageTextBox.ReadOnly = true;
this.LogMessageTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.LogMessageTextBox.Size = new System.Drawing.Size(584, 377);
this.LogMessageTextBox.TabIndex = 0;
//
// MainMenu
//
this.MainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.FileMenuItem,
this.ViewMenuItem});
//
// FileMenuItem
//
this.FileMenuItem.Index = 0;
this.FileMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.OpenLocationMenuItem,
this.ExitMenuItem});
this.FileMenuItem.Text = "&File";
//
// OpenLocationMenuItem
//
this.OpenLocationMenuItem.Index = 0;
this.OpenLocationMenuItem.Text = "&Open Location";
this.OpenLocationMenuItem.Click += new System.EventHandler(this.OpenLocationMenuItem_Click);
//
// ExitMenuItem
//
this.ExitMenuItem.Index = 1;
this.ExitMenuItem.Text = "E&xit";
this.ExitMenuItem.Click += new System.EventHandler(this.ExitMenuItem_Click);
//
// ViewMenuItem
//
this.ViewMenuItem.Index = 1;
this.ViewMenuItem.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.CleanLogsMenuItem,
this.ChangeFontMenuItem,
this.WrapTextMenuItem,
this.TopMostMenuItem,
this.MenuItemSeparater,
this.ShowToolbarMenuItem});
this.ViewMenuItem.Text = "&View";
//
// CleanLogsMenuItem
//
this.CleanLogsMenuItem.Index = 0;
this.CleanLogsMenuItem.Text = "&Clean Logs";
this.CleanLogsMenuItem.Click += new System.EventHandler(this.CleanLogsMenuItem_Click);
//
// ChangeFontMenuItem
//
this.ChangeFontMenuItem.Index = 1;
this.ChangeFontMenuItem.Text = "Change &Font";
this.ChangeFontMenuItem.Click += new System.EventHandler(this.ChangeFontMenuItem_Click);
//
// WrapTextMenuItem
//
this.WrapTextMenuItem.Index = 2;
this.WrapTextMenuItem.Text = "&Wrap Text";
this.WrapTextMenuItem.Click += new System.EventHandler(this.WrapTextMenuItem_Click);
//
// TopMostMenuItem
//
this.TopMostMenuItem.Index = 3;
this.TopMostMenuItem.Text = "&Top Most";
this.TopMostMenuItem.Click += new System.EventHandler(this.TopMostMenuItem_Click);
//
// MenuItemSeparater
//
this.MenuItemSeparater.Index = 4;
this.MenuItemSeparater.Text = "-";
//
// ShowToolbarMenuItem
//
this.ShowToolbarMenuItem.Index = 5;
this.ShowToolbarMenuItem.Text = "&Show Toolbar";
this.ShowToolbarMenuItem.Click += new System.EventHandler(this.ShowToolbarMenuItem_Click);
//
// TopMostCheckBox
//
this.TopMostCheckBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.TopMostCheckBox.AutoSize = true;
this.TopMostCheckBox.Location = new System.Drawing.Point(249, 3);
this.TopMostCheckBox.Name = "TopMostCheckBox";
this.TopMostCheckBox.Size = new System.Drawing.Size(72, 23);
this.TopMostCheckBox.TabIndex = 3;
this.TopMostCheckBox.Text = "&Top Most";
this.TopMostCheckBox.UseVisualStyleBackColor = true;
this.TopMostCheckBox.CheckedChanged += new System.EventHandler(this.TopMostCheckBox_CheckedChanged);
//
// ChangeFontButton
//
this.ChangeFontButton.AutoSize = true;
this.ChangeFontButton.Location = new System.Drawing.Point(84, 3);
this.ChangeFontButton.Name = "ChangeFontButton";
this.ChangeFontButton.Size = new System.Drawing.Size(75, 23);
this.ChangeFontButton.TabIndex = 2;
this.ChangeFontButton.Text = "&Font";
this.ChangeFontButton.UseVisualStyleBackColor = true;
this.ChangeFontButton.Click += new System.EventHandler(this.ChangeFontButton_Click);
//
// CleanLogsButton
//
this.CleanLogsButton.AutoSize = true;
this.CleanLogsButton.Location = new System.Drawing.Point(3, 3);
this.CleanLogsButton.Name = "CleanLogsButton";
this.CleanLogsButton.Size = new System.Drawing.Size(75, 23);
this.CleanLogsButton.TabIndex = 1;
this.CleanLogsButton.Text = "&Clean Logs";
this.CleanLogsButton.UseVisualStyleBackColor = true;
this.CleanLogsButton.Click += new System.EventHandler(this.CleanLogsButton_Click);
//
// WrapTextCheckBox
//
this.WrapTextCheckBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.WrapTextCheckBox.AutoSize = true;
this.WrapTextCheckBox.Location = new System.Drawing.Point(165, 3);
this.WrapTextCheckBox.Name = "WrapTextCheckBox";
this.WrapTextCheckBox.Size = new System.Drawing.Size(78, 23);
this.WrapTextCheckBox.TabIndex = 0;
this.WrapTextCheckBox.Text = "&Wrap Text";
this.WrapTextCheckBox.UseVisualStyleBackColor = true;
this.WrapTextCheckBox.CheckedChanged += new System.EventHandler(this.WrapTextCheckBox_CheckedChanged);
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Controls.Add(this.LogMessageTextBox, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.ToolbarFlowLayoutPanel, 0, 0);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 2;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.Size = new System.Drawing.Size(590, 418);
this.tableLayoutPanel1.TabIndex = 2;
//
// ToolbarFlowLayoutPanel
//
this.ToolbarFlowLayoutPanel.AutoSize = true;
this.ToolbarFlowLayoutPanel.Controls.Add(this.CleanLogsButton);
this.ToolbarFlowLayoutPanel.Controls.Add(this.ChangeFontButton);
this.ToolbarFlowLayoutPanel.Controls.Add(this.WrapTextCheckBox);
this.ToolbarFlowLayoutPanel.Controls.Add(this.TopMostCheckBox);
this.ToolbarFlowLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.ToolbarFlowLayoutPanel.Location = new System.Drawing.Point(3, 3);
this.ToolbarFlowLayoutPanel.Name = "ToolbarFlowLayoutPanel";
this.ToolbarFlowLayoutPanel.Size = new System.Drawing.Size(584, 29);
this.ToolbarFlowLayoutPanel.TabIndex = 2;
//
// LogForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(590, 418);
this.Controls.Add(this.tableLayoutPanel1);
this.Menu = this.MainMenu;
this.Name = "LogForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Log Viewer";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.LogForm_FormClosing);
this.Load += new System.EventHandler(this.LogForm_Load);
this.Shown += new System.EventHandler(this.LogForm_Shown);
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.ToolbarFlowLayoutPanel.ResumeLayout(false);
this.ToolbarFlowLayoutPanel.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TextBox LogMessageTextBox;
private System.Windows.Forms.MainMenu MainMenu;
private System.Windows.Forms.MenuItem FileMenuItem;
private System.Windows.Forms.MenuItem OpenLocationMenuItem;
private System.Windows.Forms.MenuItem ExitMenuItem;
private System.Windows.Forms.CheckBox WrapTextCheckBox;
private System.Windows.Forms.Button CleanLogsButton;
private System.Windows.Forms.Button ChangeFontButton;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.CheckBox TopMostCheckBox;
private System.Windows.Forms.MenuItem ViewMenuItem;
private System.Windows.Forms.MenuItem CleanLogsMenuItem;
private System.Windows.Forms.MenuItem ChangeFontMenuItem;
private System.Windows.Forms.MenuItem WrapTextMenuItem;
private System.Windows.Forms.MenuItem TopMostMenuItem;
private System.Windows.Forms.FlowLayoutPanel ToolbarFlowLayoutPanel;
private System.Windows.Forms.MenuItem MenuItemSeparater;
private System.Windows.Forms.MenuItem ShowToolbarMenuItem;
}
} | NeilQ/shadowsocks-windows | shadowsocks-csharp/View/LogForm.Designer.cs | C# | gpl-2.0 | 13,541 |
/*global define*/
define(['jquery', 'i18n!nls/common'], function ($, Common) {
'use strict';
return $.extend(true, {}, Common, {
/*
"compare_data": "Comparer Données",
"add_filter": "Add Filter",
"chart_title": "Timeseries on selected data",
"select_a_timerange": "Select a timerange",
"filter_box_title": "(Filter Box)"
*/
compare_data: "Comparer les données",
add_filter: "Ajouter un filtre",
chart_title: "Timeseries sur les données sélectionnées",
select_a_timerange: "Sélectionner une série de temps",
filter_box_title: "(Boîte à filtre)"
});
}); | FAOSTAT4/faostat4-ui | i18n/fr/compare.js | JavaScript | gpl-2.0 | 673 |
/************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
*
* Copyright 2008, 2010 Oracle and/or its affiliates. All rights reserved.
*
* Use is subject to license terms.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0. You can also
* obtain a copy of the License at http://odftoolkit.org/docs/license.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
************************************************************************/
/*
* This file is automatically generated.
* Don't edit manually.
*/
package org.odftoolkit.odfdom.dom.attribute.dr3d;
import org.odftoolkit.odfdom.dom.OdfDocumentNamespace;
import org.odftoolkit.odfdom.pkg.OdfAttribute;
import org.odftoolkit.odfdom.pkg.OdfFileDom;
import org.odftoolkit.odfdom.pkg.OdfName;
/**
* DOM implementation of OpenDocument attribute {@odf.attribute dr3d:backface-culling}.
*
*/
public class Dr3dBackfaceCullingAttribute extends OdfAttribute {
public static final OdfName ATTRIBUTE_NAME = OdfName.newName(OdfDocumentNamespace.DR3D, "backface-culling");
/**
* Create the instance of OpenDocument attribute {@odf.attribute dr3d:backface-culling}.
*
* @param ownerDocument The type is <code>OdfFileDom</code>
*/
public Dr3dBackfaceCullingAttribute(OdfFileDom ownerDocument) {
super(ownerDocument, ATTRIBUTE_NAME);
}
/**
* Returns the attribute name.
*
* @return the <code>OdfName</code> for {@odf.attribute dr3d:backface-culling}.
*/
@Override
public OdfName getOdfName() {
return ATTRIBUTE_NAME;
}
/**
* @return Returns the name of this attribute.
*/
@Override
public String getName() {
return ATTRIBUTE_NAME.getLocalName();
}
/**
* The value set of {@odf.attribute dr3d:backface-culling}.
*/
public enum Value {
DISABLED("disabled"), ENABLED("enabled") ;
private String mValue;
Value(String value) {
mValue = value;
}
@Override
public String toString() {
return mValue;
}
public static Value enumValueOf(String value) {
for(Value aIter : values()) {
if (value.equals(aIter.toString())) {
return aIter;
}
}
return null;
}
}
/**
* @param attrValue The <code>Enum</code> value of the attribute.
*/
public void setEnumValue(Value attrValue) {
setValue(attrValue.toString());
}
/**
* @return Returns the <code>Enum</code> value of the attribute
*/
public Value getEnumValue() {
return Value.enumValueOf(this.getValue());
}
/**
* Returns the default value of {@odf.attribute dr3d:backface-culling}.
*
* @return the default value as <code>String</code> dependent of its element name
* return <code>null</code> if the default value does not exist
*/
@Override
public String getDefault() {
return null;
}
/**
* Default value indicator. As the attribute default value is dependent from its element, the attribute has only a default, when a parent element exists.
*
* @return <code>true</code> if {@odf.attribute dr3d:backface-culling} has an element parent
* otherwise return <code>false</code> as undefined.
*/
@Override
public boolean hasDefault() {
return false;
}
/**
* @return Returns whether this attribute is known to be of type ID (i.e. xml:id ?)
*/
@Override
public boolean isId() {
return false;
}
}
| jbjonesjr/geoproponis | external/odfdom-java-0.8.10-incubating-sources/org/odftoolkit/odfdom/dom/attribute/dr3d/Dr3dBackfaceCullingAttribute.java | Java | gpl-2.0 | 3,795 |
// arm.cc -- arm target support for gold.
// Copyright 2009 Free Software Foundation, Inc.
// Written by Doug Kwan <dougkwan@google.com> based on the i386 code
// by Ian Lance Taylor <iant@google.com>.
// This file is part of gold.
// 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 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
// MA 02110-1301, USA.
#include "gold.h"
#include <cstring>
#include <limits>
#include <cstdio>
#include <string>
#include "elfcpp.h"
#include "parameters.h"
#include "reloc.h"
#include "arm.h"
#include "object.h"
#include "symtab.h"
#include "layout.h"
#include "output.h"
#include "copy-relocs.h"
#include "target.h"
#include "target-reloc.h"
#include "target-select.h"
#include "tls.h"
#include "defstd.h"
namespace
{
using namespace gold;
template<bool big_endian>
class Output_data_plt_arm;
// The arm target class.
//
// This is a very simple port of gold for ARM-EABI. It is intended for
// supporting Android only for the time being. Only these relocation types
// are supported.
//
// R_ARM_NONE
// R_ARM_ABS32
// R_ARM_REL32
// R_ARM_THM_CALL
// R_ARM_COPY
// R_ARM_GLOB_DAT
// R_ARM_BASE_PREL
// R_ARM_JUMP_SLOT
// R_ARM_RELATIVE
// R_ARM_GOTOFF32
// R_ARM_GOT_BREL
// R_ARM_PLT32
// R_ARM_CALL
// R_ARM_JUMP24
// R_ARM_TARGET1
// R_ARM_PREL31
//
// Coming soon (pending patches):
// - Defining section symbols __exidx_start and __exidx_stop.
// - Support interworking.
// - Mergeing all .ARM.xxx.yyy sections into .ARM.xxx. Currently, they
// are incorrectly merged into an .ARM section.
//
// TODOs:
// - Create a PT_ARM_EXIDX program header for a shared object that
// might throw an exception.
// - Support more relocation types as needed.
// - Make PLTs more flexible for different architecture features like
// Thumb-2 and BE8.
// Utilities for manipulating integers of up to 32-bits
namespace utils
{
// Sign extend an n-bit unsigned integer stored in an uint32_t into
// an int32_t. NO_BITS must be between 1 to 32.
template<int no_bits>
static inline int32_t
sign_extend(uint32_t bits)
{
gold_assert(no_bits >= 0 && no_bits <= 32);
if (no_bits == 32)
return static_cast<int32_t>(bits);
uint32_t mask = (~((uint32_t) 0)) >> (32 - no_bits);
bits &= mask;
uint32_t top_bit = 1U << (no_bits - 1);
int32_t as_signed = static_cast<int32_t>(bits);
return (bits & top_bit) ? as_signed + (-top_bit * 2) : as_signed;
}
// Detects overflow of an NO_BITS integer stored in a uint32_t.
template<int no_bits>
static inline bool
has_overflow(uint32_t bits)
{
gold_assert(no_bits >= 0 && no_bits <= 32);
if (no_bits == 32)
return false;
int32_t max = (1 << (no_bits - 1)) - 1;
int32_t min = -(1 << (no_bits - 1));
int32_t as_signed = static_cast<int32_t>(bits);
return as_signed > max || as_signed < min;
}
// Select bits from A and B using bits in MASK. For each n in [0..31],
// the n-th bit in the result is chosen from the n-th bits of A and B.
// A zero selects A and a one selects B.
static inline uint32_t
bit_select(uint32_t a, uint32_t b, uint32_t mask)
{ return (a & ~mask) | (b & mask); }
};
template<bool big_endian>
class Target_arm : public Sized_target<32, big_endian>
{
public:
typedef Output_data_reloc<elfcpp::SHT_REL, true, 32, big_endian>
Reloc_section;
Target_arm()
: Sized_target<32, big_endian>(&arm_info),
got_(NULL), plt_(NULL), got_plt_(NULL), rel_dyn_(NULL),
copy_relocs_(elfcpp::R_ARM_COPY), dynbss_(NULL)
{ }
// Process the relocations to determine unreferenced sections for
// garbage collection.
void
gc_process_relocs(const General_options& options,
Symbol_table* symtab,
Layout* layout,
Sized_relobj<32, big_endian>* object,
unsigned int data_shndx,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
size_t local_symbol_count,
const unsigned char* plocal_symbols);
// Scan the relocations to look for symbol adjustments.
void
scan_relocs(const General_options& options,
Symbol_table* symtab,
Layout* layout,
Sized_relobj<32, big_endian>* object,
unsigned int data_shndx,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
size_t local_symbol_count,
const unsigned char* plocal_symbols);
// Finalize the sections.
void
do_finalize_sections(Layout*);
// Return the value to use for a dynamic symbol which requires special
// treatment.
uint64_t
do_dynsym_value(const Symbol*) const;
// Relocate a section.
void
relocate_section(const Relocate_info<32, big_endian>*,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
unsigned char* view,
elfcpp::Elf_types<32>::Elf_Addr view_address,
section_size_type view_size);
// Scan the relocs during a relocatable link.
void
scan_relocatable_relocs(const General_options& options,
Symbol_table* symtab,
Layout* layout,
Sized_relobj<32, big_endian>* object,
unsigned int data_shndx,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
size_t local_symbol_count,
const unsigned char* plocal_symbols,
Relocatable_relocs*);
// Relocate a section during a relocatable link.
void
relocate_for_relocatable(const Relocate_info<32, big_endian>*,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
off_t offset_in_output_section,
const Relocatable_relocs*,
unsigned char* view,
elfcpp::Elf_types<32>::Elf_Addr view_address,
section_size_type view_size,
unsigned char* reloc_view,
section_size_type reloc_view_size);
// Return whether SYM is defined by the ABI.
bool
do_is_defined_by_abi(Symbol* sym) const
{ return strcmp(sym->name(), "__tls_get_addr") == 0; }
// Return the size of the GOT section.
section_size_type
got_size()
{
gold_assert(this->got_ != NULL);
return this->got_->data_size();
}
// Map platform-specific reloc types
static unsigned int
get_real_reloc_type (unsigned int r_type);
private:
// The class which scans relocations.
class Scan
{
public:
Scan()
: issued_non_pic_error_(false)
{ }
inline void
local(const General_options& options, Symbol_table* symtab,
Layout* layout, Target_arm* target,
Sized_relobj<32, big_endian>* object,
unsigned int data_shndx,
Output_section* output_section,
const elfcpp::Rel<32, big_endian>& reloc, unsigned int r_type,
const elfcpp::Sym<32, big_endian>& lsym);
inline void
global(const General_options& options, Symbol_table* symtab,
Layout* layout, Target_arm* target,
Sized_relobj<32, big_endian>* object,
unsigned int data_shndx,
Output_section* output_section,
const elfcpp::Rel<32, big_endian>& reloc, unsigned int r_type,
Symbol* gsym);
private:
static void
unsupported_reloc_local(Sized_relobj<32, big_endian>*,
unsigned int r_type);
static void
unsupported_reloc_global(Sized_relobj<32, big_endian>*,
unsigned int r_type, Symbol*);
void
check_non_pic(Relobj*, unsigned int r_type);
// Almost identical to Symbol::needs_plt_entry except that it also
// handles STT_ARM_TFUNC.
static bool
symbol_needs_plt_entry(const Symbol* sym)
{
// An undefined symbol from an executable does not need a PLT entry.
if (sym->is_undefined() && !parameters->options().shared())
return false;
return (!parameters->doing_static_link()
&& (sym->type() == elfcpp::STT_FUNC
|| sym->type() == elfcpp::STT_ARM_TFUNC)
&& (sym->is_from_dynobj()
|| sym->is_undefined()
|| sym->is_preemptible()));
}
// Whether we have issued an error about a non-PIC compilation.
bool issued_non_pic_error_;
};
// The class which implements relocation.
class Relocate
{
public:
Relocate()
{ }
~Relocate()
{ }
// Return whether the static relocation needs to be applied.
inline bool
should_apply_static_reloc(const Sized_symbol<32>* gsym,
int ref_flags,
bool is_32bit,
Output_section* output_section);
// Do a relocation. Return false if the caller should not issue
// any warnings about this relocation.
inline bool
relocate(const Relocate_info<32, big_endian>*, Target_arm*,
Output_section*, size_t relnum,
const elfcpp::Rel<32, big_endian>&,
unsigned int r_type, const Sized_symbol<32>*,
const Symbol_value<32>*,
unsigned char*, elfcpp::Elf_types<32>::Elf_Addr,
section_size_type);
// Return whether we want to pass flag NON_PIC_REF for this
// reloc.
static inline bool
reloc_is_non_pic (unsigned int r_type)
{
switch (r_type)
{
case elfcpp::R_ARM_REL32:
case elfcpp::R_ARM_THM_CALL:
case elfcpp::R_ARM_CALL:
case elfcpp::R_ARM_JUMP24:
case elfcpp::R_ARM_PREL31:
return true;
default:
return false;
}
}
};
// A class which returns the size required for a relocation type,
// used while scanning relocs during a relocatable link.
class Relocatable_size_for_reloc
{
public:
unsigned int
get_size_for_reloc(unsigned int, Relobj*);
};
// Get the GOT section, creating it if necessary.
Output_data_got<32, big_endian>*
got_section(Symbol_table*, Layout*);
// Get the GOT PLT section.
Output_data_space*
got_plt_section() const
{
gold_assert(this->got_plt_ != NULL);
return this->got_plt_;
}
// Create a PLT entry for a global symbol.
void
make_plt_entry(Symbol_table*, Layout*, Symbol*);
// Get the PLT section.
const Output_data_plt_arm<big_endian>*
plt_section() const
{
gold_assert(this->plt_ != NULL);
return this->plt_;
}
// Get the dynamic reloc section, creating it if necessary.
Reloc_section*
rel_dyn_section(Layout*);
// Return true if the symbol may need a COPY relocation.
// References from an executable object to non-function symbols
// defined in a dynamic object may need a COPY relocation.
bool
may_need_copy_reloc(Symbol* gsym)
{
return (!parameters->options().shared()
&& gsym->is_from_dynobj()
&& gsym->type() != elfcpp::STT_FUNC
&& gsym->type() != elfcpp::STT_ARM_TFUNC);
}
// Add a potential copy relocation.
void
copy_reloc(Symbol_table* symtab, Layout* layout,
Sized_relobj<32, big_endian>* object,
unsigned int shndx, Output_section* output_section,
Symbol* sym, const elfcpp::Rel<32, big_endian>& reloc)
{
this->copy_relocs_.copy_reloc(symtab, layout,
symtab->get_sized_symbol<32>(sym),
object, shndx, output_section, reloc,
this->rel_dyn_section(layout));
}
// Information about this specific target which we pass to the
// general Target structure.
static const Target::Target_info arm_info;
// The types of GOT entries needed for this platform.
enum Got_type
{
GOT_TYPE_STANDARD = 0 // GOT entry for a regular symbol
};
// The GOT section.
Output_data_got<32, big_endian>* got_;
// The PLT section.
Output_data_plt_arm<big_endian>* plt_;
// The GOT PLT section.
Output_data_space* got_plt_;
// The dynamic reloc section.
Reloc_section* rel_dyn_;
// Relocs saved to avoid a COPY reloc.
Copy_relocs<elfcpp::SHT_REL, 32, big_endian> copy_relocs_;
// Space for variables copied with a COPY reloc.
Output_data_space* dynbss_;
};
template<bool big_endian>
const Target::Target_info Target_arm<big_endian>::arm_info =
{
32, // size
big_endian, // is_big_endian
elfcpp::EM_ARM, // machine_code
false, // has_make_symbol
false, // has_resolve
false, // has_code_fill
true, // is_default_stack_executable
'\0', // wrap_char
"/usr/lib/libc.so.1", // dynamic_linker
0x8000, // default_text_segment_address
0x1000, // abi_pagesize (overridable by -z max-page-size)
0x1000, // common_pagesize (overridable by -z common-page-size)
elfcpp::SHN_UNDEF, // small_common_shndx
elfcpp::SHN_UNDEF, // large_common_shndx
0, // small_common_section_flags
0 // large_common_section_flags
};
// Arm relocate functions class
//
template<bool big_endian>
class Arm_relocate_functions : public Relocate_functions<32, big_endian>
{
public:
typedef enum
{
STATUS_OKAY, // No error during relocation.
STATUS_OVERFLOW, // Relocation oveflow.
STATUS_BAD_RELOC // Relocation cannot be applied.
} Status;
private:
typedef Relocate_functions<32, big_endian> Base;
typedef Arm_relocate_functions<big_endian> This;
// Get an symbol value of *PSYMVAL with an ADDEND. This is a wrapper
// to Symbol_value::value(). If HAS_THUMB_BIT is true, that LSB is used
// to distinguish ARM and THUMB functions and it is treated specially.
static inline Symbol_value<32>::Value
arm_symbol_value (const Sized_relobj<32, big_endian> *object,
const Symbol_value<32>* psymval,
Symbol_value<32>::Value addend,
bool has_thumb_bit)
{
typedef Symbol_value<32>::Value Valtype;
if (has_thumb_bit)
{
Valtype raw = psymval->value(object, 0);
Valtype thumb_bit = raw & 1;
return ((raw & ~((Valtype) 1)) + addend) | thumb_bit;
}
else
return psymval->value(object, addend);
}
// FIXME: This probably only works for Android on ARM v5te. We should
// following GNU ld for the general case.
template<unsigned r_type>
static inline typename This::Status
arm_branch_common(unsigned char *view,
const Sized_relobj<32, big_endian>* object,
const Symbol_value<32>* psymval,
elfcpp::Elf_types<32>::Elf_Addr address,
bool has_thumb_bit)
{
typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<32, big_endian>::readval(wv);
bool insn_is_b = (((val >> 28) & 0xf) <= 0xe)
&& ((val & 0x0f000000UL) == 0x0a000000UL);
bool insn_is_uncond_bl = (val & 0xff000000UL) == 0xeb000000UL;
bool insn_is_cond_bl = (((val >> 28) & 0xf) < 0xe)
&& ((val & 0x0f000000UL) == 0x0b000000UL);
bool insn_is_blx = (val & 0xfe000000UL) == 0xfa000000UL;
bool insn_is_any_branch = (val & 0x0e000000UL) == 0x0a000000UL;
if (r_type == elfcpp::R_ARM_CALL)
{
if (!insn_is_uncond_bl && !insn_is_blx)
return This::STATUS_BAD_RELOC;
}
else if (r_type == elfcpp::R_ARM_JUMP24)
{
if (!insn_is_b && !insn_is_cond_bl)
return This::STATUS_BAD_RELOC;
}
else if (r_type == elfcpp::R_ARM_PLT32)
{
if (!insn_is_any_branch)
return This::STATUS_BAD_RELOC;
}
else
gold_unreachable();
Valtype addend = utils::sign_extend<26>(val << 2);
Valtype x = (This::arm_symbol_value(object, psymval, addend, has_thumb_bit)
- address);
// If target has thumb bit set, we need to either turn the BL
// into a BLX (for ARMv5 or above) or generate a stub.
if (x & 1)
{
// Turn BL to BLX.
if (insn_is_uncond_bl)
val = (val & 0xffffff) | 0xfa000000 | ((x & 2) << 23);
else
return This::STATUS_BAD_RELOC;
}
else
gold_assert(!insn_is_blx);
val = utils::bit_select(val, (x >> 2), 0xffffffUL);
elfcpp::Swap<32, big_endian>::writeval(wv, val);
return (utils::has_overflow<26>(x)
? This::STATUS_OVERFLOW : This::STATUS_OKAY);
}
public:
// R_ARM_ABS32: (S + A) | T
static inline typename This::Status
abs32(unsigned char *view,
const Sized_relobj<32, big_endian>* object,
const Symbol_value<32>* psymval,
bool has_thumb_bit)
{
typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype addend = elfcpp::Swap<32, big_endian>::readval(wv);
Valtype x = This::arm_symbol_value(object, psymval, addend, has_thumb_bit);
elfcpp::Swap<32, big_endian>::writeval(wv, x);
return This::STATUS_OKAY;
}
// R_ARM_REL32: (S + A) | T - P
static inline typename This::Status
rel32(unsigned char *view,
const Sized_relobj<32, big_endian>* object,
const Symbol_value<32>* psymval,
elfcpp::Elf_types<32>::Elf_Addr address,
bool has_thumb_bit)
{
typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype addend = elfcpp::Swap<32, big_endian>::readval(wv);
Valtype x = (This::arm_symbol_value(object, psymval, addend, has_thumb_bit)
- address);
elfcpp::Swap<32, big_endian>::writeval(wv, x);
return This::STATUS_OKAY;
}
// R_ARM_THM_CALL: (S + A) | T - P
static inline typename This::Status
thm_call(unsigned char *view,
const Sized_relobj<32, big_endian>* object,
const Symbol_value<32>* psymval,
elfcpp::Elf_types<32>::Elf_Addr address,
bool has_thumb_bit)
{
// A thumb call consists of two instructions.
typedef typename elfcpp::Swap<16, big_endian>::Valtype Valtype;
typedef typename elfcpp::Swap<32, big_endian>::Valtype Reltype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype hi = elfcpp::Swap<16, big_endian>::readval(wv);
Valtype lo = elfcpp::Swap<16, big_endian>::readval(wv + 1);
// Must be a BL instruction. lo == 11111xxxxxxxxxxx.
gold_assert((lo & 0xf800) == 0xf800);
Reltype addend = utils::sign_extend<23>(((hi & 0x7ff) << 12)
| ((lo & 0x7ff) << 1));
Reltype x = (This::arm_symbol_value(object, psymval, addend, has_thumb_bit)
- address);
// If target has no thumb bit set, we need to either turn the BL
// into a BLX (for ARMv5 or above) or generate a stub.
if ((x & 1) == 0)
{
// This only works for ARMv5 and above with interworking enabled.
lo &= 0xefff;
}
hi = utils::bit_select(hi, (x >> 12), 0x7ffU);
lo = utils::bit_select(lo, (x >> 1), 0x7ffU);
elfcpp::Swap<16, big_endian>::writeval(wv, hi);
elfcpp::Swap<16, big_endian>::writeval(wv + 1, lo);
return (utils::has_overflow<23>(x)
? This::STATUS_OVERFLOW
: This::STATUS_OKAY);
}
// R_ARM_BASE_PREL: B(S) + A - P
static inline typename This::Status
base_prel(unsigned char* view,
elfcpp::Elf_types<32>::Elf_Addr origin,
elfcpp::Elf_types<32>::Elf_Addr address)
{
Base::rel32(view, origin - address);
return STATUS_OKAY;
}
// R_ARM_GOT_BREL: GOT(S) + A - GOT_ORG
static inline typename This::Status
got_brel(unsigned char* view,
typename elfcpp::Swap<32, big_endian>::Valtype got_offset)
{
Base::rel32(view, got_offset);
return This::STATUS_OKAY;
}
// R_ARM_PLT32: (S + A) | T - P
static inline typename This::Status
plt32(unsigned char *view,
const Sized_relobj<32, big_endian>* object,
const Symbol_value<32>* psymval,
elfcpp::Elf_types<32>::Elf_Addr address,
bool has_thumb_bit)
{
return arm_branch_common<elfcpp::R_ARM_PLT32>(view, object, psymval,
address, has_thumb_bit);
}
// R_ARM_CALL: (S + A) | T - P
static inline typename This::Status
call(unsigned char *view,
const Sized_relobj<32, big_endian>* object,
const Symbol_value<32>* psymval,
elfcpp::Elf_types<32>::Elf_Addr address,
bool has_thumb_bit)
{
return arm_branch_common<elfcpp::R_ARM_CALL>(view, object, psymval,
address, has_thumb_bit);
}
// R_ARM_JUMP24: (S + A) | T - P
static inline typename This::Status
jump24(unsigned char *view,
const Sized_relobj<32, big_endian>* object,
const Symbol_value<32>* psymval,
elfcpp::Elf_types<32>::Elf_Addr address,
bool has_thumb_bit)
{
return arm_branch_common<elfcpp::R_ARM_JUMP24>(view, object, psymval,
address, has_thumb_bit);
}
// R_ARM_PREL: (S + A) | T - P
static inline typename This::Status
prel31(unsigned char *view,
const Sized_relobj<32, big_endian>* object,
const Symbol_value<32>* psymval,
elfcpp::Elf_types<32>::Elf_Addr address,
bool has_thumb_bit)
{
typedef typename elfcpp::Swap<32, big_endian>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<32, big_endian>::readval(wv);
Valtype addend = utils::sign_extend<31>(val);
Valtype x = (This::arm_symbol_value(object, psymval, addend, has_thumb_bit)
- address);
val = utils::bit_select(val, x, 0x7fffffffU);
elfcpp::Swap<32, big_endian>::writeval(wv, val);
return (utils::has_overflow<31>(x) ?
This::STATUS_OVERFLOW : This::STATUS_OKAY);
}
};
// Get the GOT section, creating it if necessary.
template<bool big_endian>
Output_data_got<32, big_endian>*
Target_arm<big_endian>::got_section(Symbol_table* symtab, Layout* layout)
{
if (this->got_ == NULL)
{
gold_assert(symtab != NULL && layout != NULL);
this->got_ = new Output_data_got<32, big_endian>();
Output_section* os;
os = layout->add_output_section_data(".got", elfcpp::SHT_PROGBITS,
(elfcpp::SHF_ALLOC
| elfcpp::SHF_WRITE),
this->got_);
os->set_is_relro();
// The old GNU linker creates a .got.plt section. We just
// create another set of data in the .got section. Note that we
// always create a PLT if we create a GOT, although the PLT
// might be empty.
this->got_plt_ = new Output_data_space(4, "** GOT PLT");
os = layout->add_output_section_data(".got", elfcpp::SHT_PROGBITS,
(elfcpp::SHF_ALLOC
| elfcpp::SHF_WRITE),
this->got_plt_);
os->set_is_relro();
// The first three entries are reserved.
this->got_plt_->set_current_data_size(3 * 4);
// Define _GLOBAL_OFFSET_TABLE_ at the start of the PLT.
symtab->define_in_output_data("_GLOBAL_OFFSET_TABLE_", NULL,
this->got_plt_,
0, 0, elfcpp::STT_OBJECT,
elfcpp::STB_LOCAL,
elfcpp::STV_HIDDEN, 0,
false, false);
}
return this->got_;
}
// Get the dynamic reloc section, creating it if necessary.
template<bool big_endian>
typename Target_arm<big_endian>::Reloc_section*
Target_arm<big_endian>::rel_dyn_section(Layout* layout)
{
if (this->rel_dyn_ == NULL)
{
gold_assert(layout != NULL);
this->rel_dyn_ = new Reloc_section(parameters->options().combreloc());
layout->add_output_section_data(".rel.dyn", elfcpp::SHT_REL,
elfcpp::SHF_ALLOC, this->rel_dyn_);
}
return this->rel_dyn_;
}
// A class to handle the PLT data.
template<bool big_endian>
class Output_data_plt_arm : public Output_section_data
{
public:
typedef Output_data_reloc<elfcpp::SHT_REL, true, 32, big_endian>
Reloc_section;
Output_data_plt_arm(Layout*, Output_data_space*);
// Add an entry to the PLT.
void
add_entry(Symbol* gsym);
// Return the .rel.plt section data.
const Reloc_section*
rel_plt() const
{ return this->rel_; }
protected:
void
do_adjust_output_section(Output_section* os);
// Write to a map file.
void
do_print_to_mapfile(Mapfile* mapfile) const
{ mapfile->print_output_data(this, _("** PLT")); }
private:
// Template for the first PLT entry.
static const uint32_t first_plt_entry[5];
// Template for subsequent PLT entries.
static const uint32_t plt_entry[3];
// Set the final size.
void
set_final_data_size()
{
this->set_data_size(sizeof(first_plt_entry)
+ this->count_ * sizeof(plt_entry));
}
// Write out the PLT data.
void
do_write(Output_file*);
// The reloc section.
Reloc_section* rel_;
// The .got.plt section.
Output_data_space* got_plt_;
// The number of PLT entries.
unsigned int count_;
};
// Create the PLT section. The ordinary .got section is an argument,
// since we need to refer to the start. We also create our own .got
// section just for PLT entries.
template<bool big_endian>
Output_data_plt_arm<big_endian>::Output_data_plt_arm(Layout* layout,
Output_data_space* got_plt)
: Output_section_data(4), got_plt_(got_plt), count_(0)
{
this->rel_ = new Reloc_section(false);
layout->add_output_section_data(".rel.plt", elfcpp::SHT_REL,
elfcpp::SHF_ALLOC, this->rel_);
}
template<bool big_endian>
void
Output_data_plt_arm<big_endian>::do_adjust_output_section(Output_section* os)
{
os->set_entsize(0);
}
// Add an entry to the PLT.
template<bool big_endian>
void
Output_data_plt_arm<big_endian>::add_entry(Symbol* gsym)
{
gold_assert(!gsym->has_plt_offset());
// Note that when setting the PLT offset we skip the initial
// reserved PLT entry.
gsym->set_plt_offset((this->count_) * sizeof(plt_entry)
+ sizeof(first_plt_entry));
++this->count_;
section_offset_type got_offset = this->got_plt_->current_data_size();
// Every PLT entry needs a GOT entry which points back to the PLT
// entry (this will be changed by the dynamic linker, normally
// lazily when the function is called).
this->got_plt_->set_current_data_size(got_offset + 4);
// Every PLT entry needs a reloc.
gsym->set_needs_dynsym_entry();
this->rel_->add_global(gsym, elfcpp::R_ARM_JUMP_SLOT, this->got_plt_,
got_offset);
// Note that we don't need to save the symbol. The contents of the
// PLT are independent of which symbols are used. The symbols only
// appear in the relocations.
}
// ARM PLTs.
// FIXME: This is not very flexible. Right now this has only been tested
// on armv5te. If we are to support additional architecture features like
// Thumb-2 or BE8, we need to make this more flexible like GNU ld.
// The first entry in the PLT.
template<bool big_endian>
const uint32_t Output_data_plt_arm<big_endian>::first_plt_entry[5] =
{
0xe52de004, // str lr, [sp, #-4]!
0xe59fe004, // ldr lr, [pc, #4]
0xe08fe00e, // add lr, pc, lr
0xe5bef008, // ldr pc, [lr, #8]!
0x00000000, // &GOT[0] - .
};
// Subsequent entries in the PLT.
template<bool big_endian>
const uint32_t Output_data_plt_arm<big_endian>::plt_entry[3] =
{
0xe28fc600, // add ip, pc, #0xNN00000
0xe28cca00, // add ip, ip, #0xNN000
0xe5bcf000, // ldr pc, [ip, #0xNNN]!
};
// Write out the PLT. This uses the hand-coded instructions above,
// and adjusts them as needed. This is all specified by the arm ELF
// Processor Supplement.
template<bool big_endian>
void
Output_data_plt_arm<big_endian>::do_write(Output_file* of)
{
const off_t offset = this->offset();
const section_size_type oview_size =
convert_to_section_size_type(this->data_size());
unsigned char* const oview = of->get_output_view(offset, oview_size);
const off_t got_file_offset = this->got_plt_->offset();
const section_size_type got_size =
convert_to_section_size_type(this->got_plt_->data_size());
unsigned char* const got_view = of->get_output_view(got_file_offset,
got_size);
unsigned char* pov = oview;
elfcpp::Elf_types<32>::Elf_Addr plt_address = this->address();
elfcpp::Elf_types<32>::Elf_Addr got_address = this->got_plt_->address();
// Write first PLT entry. All but the last word are constants.
const size_t num_first_plt_words = (sizeof(first_plt_entry)
/ sizeof(plt_entry[0]));
for (size_t i = 0; i < num_first_plt_words - 1; i++)
elfcpp::Swap<32, big_endian>::writeval(pov + i * 4, first_plt_entry[i]);
// Last word in first PLT entry is &GOT[0] - .
elfcpp::Swap<32, big_endian>::writeval(pov + 16,
got_address - (plt_address + 16));
pov += sizeof(first_plt_entry);
unsigned char* got_pov = got_view;
memset(got_pov, 0, 12);
got_pov += 12;
const int rel_size = elfcpp::Elf_sizes<32>::rel_size;
unsigned int plt_offset = sizeof(first_plt_entry);
unsigned int plt_rel_offset = 0;
unsigned int got_offset = 12;
const unsigned int count = this->count_;
for (unsigned int i = 0;
i < count;
++i,
pov += sizeof(plt_entry),
got_pov += 4,
plt_offset += sizeof(plt_entry),
plt_rel_offset += rel_size,
got_offset += 4)
{
// Set and adjust the PLT entry itself.
int32_t offset = ((got_address + got_offset)
- (plt_address + plt_offset + 8));
gold_assert(offset >= 0 && offset < 0x0fffffff);
uint32_t plt_insn0 = plt_entry[0] | ((offset >> 20) & 0xff);
elfcpp::Swap<32, big_endian>::writeval(pov, plt_insn0);
uint32_t plt_insn1 = plt_entry[1] | ((offset >> 12) & 0xff);
elfcpp::Swap<32, big_endian>::writeval(pov + 4, plt_insn1);
uint32_t plt_insn2 = plt_entry[2] | (offset & 0xfff);
elfcpp::Swap<32, big_endian>::writeval(pov + 8, plt_insn2);
// Set the entry in the GOT.
elfcpp::Swap<32, big_endian>::writeval(got_pov, plt_address);
}
gold_assert(static_cast<section_size_type>(pov - oview) == oview_size);
gold_assert(static_cast<section_size_type>(got_pov - got_view) == got_size);
of->write_output_view(offset, oview_size, oview);
of->write_output_view(got_file_offset, got_size, got_view);
}
// Create a PLT entry for a global symbol.
template<bool big_endian>
void
Target_arm<big_endian>::make_plt_entry(Symbol_table* symtab, Layout* layout,
Symbol* gsym)
{
if (gsym->has_plt_offset())
return;
if (this->plt_ == NULL)
{
// Create the GOT sections first.
this->got_section(symtab, layout);
this->plt_ = new Output_data_plt_arm<big_endian>(layout, this->got_plt_);
layout->add_output_section_data(".plt", elfcpp::SHT_PROGBITS,
(elfcpp::SHF_ALLOC
| elfcpp::SHF_EXECINSTR),
this->plt_);
}
this->plt_->add_entry(gsym);
}
// Report an unsupported relocation against a local symbol.
template<bool big_endian>
void
Target_arm<big_endian>::Scan::unsupported_reloc_local(
Sized_relobj<32, big_endian>* object,
unsigned int r_type)
{
gold_error(_("%s: unsupported reloc %u against local symbol"),
object->name().c_str(), r_type);
}
// We are about to emit a dynamic relocation of type R_TYPE. If the
// dynamic linker does not support it, issue an error. The GNU linker
// only issues a non-PIC error for an allocated read-only section.
// Here we know the section is allocated, but we don't know that it is
// read-only. But we check for all the relocation types which the
// glibc dynamic linker supports, so it seems appropriate to issue an
// error even if the section is not read-only.
template<bool big_endian>
void
Target_arm<big_endian>::Scan::check_non_pic(Relobj* object,
unsigned int r_type)
{
switch (r_type)
{
// These are the relocation types supported by glibc for ARM.
case elfcpp::R_ARM_RELATIVE:
case elfcpp::R_ARM_COPY:
case elfcpp::R_ARM_GLOB_DAT:
case elfcpp::R_ARM_JUMP_SLOT:
case elfcpp::R_ARM_ABS32:
case elfcpp::R_ARM_PC24:
// FIXME: The following 3 types are not supported by Android's dynamic
// linker.
case elfcpp::R_ARM_TLS_DTPMOD32:
case elfcpp::R_ARM_TLS_DTPOFF32:
case elfcpp::R_ARM_TLS_TPOFF32:
return;
default:
// This prevents us from issuing more than one error per reloc
// section. But we can still wind up issuing more than one
// error per object file.
if (this->issued_non_pic_error_)
return;
object->error(_("requires unsupported dynamic reloc; "
"recompile with -fPIC"));
this->issued_non_pic_error_ = true;
return;
case elfcpp::R_ARM_NONE:
gold_unreachable();
}
}
// Scan a relocation for a local symbol.
// FIXME: This only handles a subset of relocation types used by Android
// on ARM v5te devices.
template<bool big_endian>
inline void
Target_arm<big_endian>::Scan::local(const General_options&,
Symbol_table* symtab,
Layout* layout,
Target_arm* target,
Sized_relobj<32, big_endian>* object,
unsigned int data_shndx,
Output_section* output_section,
const elfcpp::Rel<32, big_endian>& reloc,
unsigned int r_type,
const elfcpp::Sym<32, big_endian>&)
{
r_type = get_real_reloc_type(r_type);
switch (r_type)
{
case elfcpp::R_ARM_NONE:
break;
case elfcpp::R_ARM_ABS32:
// If building a shared library (or a position-independent
// executable), we need to create a dynamic relocation for
// this location. The relocation applied at link time will
// apply the link-time value, so we flag the location with
// an R_ARM_RELATIVE relocation so the dynamic loader can
// relocate it easily.
if (parameters->options().output_is_position_independent())
{
Reloc_section* rel_dyn = target->rel_dyn_section(layout);
unsigned int r_sym = elfcpp::elf_r_sym<32>(reloc.get_r_info());
// If we are to add more other reloc types than R_ARM_ABS32,
// we need to add check_non_pic(object, r_type) here.
rel_dyn->add_local_relative(object, r_sym, elfcpp::R_ARM_RELATIVE,
output_section, data_shndx,
reloc.get_r_offset());
}
break;
case elfcpp::R_ARM_REL32:
case elfcpp::R_ARM_THM_CALL:
case elfcpp::R_ARM_CALL:
case elfcpp::R_ARM_PREL31:
case elfcpp::R_ARM_JUMP24:
case elfcpp::R_ARM_PLT32:
break;
case elfcpp::R_ARM_GOTOFF32:
// We need a GOT section:
target->got_section(symtab, layout);
break;
case elfcpp::R_ARM_BASE_PREL:
// FIXME: What about this?
break;
case elfcpp::R_ARM_GOT_BREL:
{
// The symbol requires a GOT entry.
Output_data_got<32, big_endian>* got =
target->got_section(symtab, layout);
unsigned int r_sym = elfcpp::elf_r_sym<32>(reloc.get_r_info());
if (got->add_local(object, r_sym, GOT_TYPE_STANDARD))
{
// If we are generating a shared object, we need to add a
// dynamic RELATIVE relocation for this symbol's GOT entry.
if (parameters->options().output_is_position_independent())
{
Reloc_section* rel_dyn = target->rel_dyn_section(layout);
unsigned int r_sym = elfcpp::elf_r_sym<32>(reloc.get_r_info());
rel_dyn->add_local_relative(
object, r_sym, elfcpp::R_ARM_RELATIVE, got,
object->local_got_offset(r_sym, GOT_TYPE_STANDARD));
}
}
}
break;
case elfcpp::R_ARM_TARGET1:
// This should have been mapped to another type already.
// Fall through.
case elfcpp::R_ARM_COPY:
case elfcpp::R_ARM_GLOB_DAT:
case elfcpp::R_ARM_JUMP_SLOT:
case elfcpp::R_ARM_RELATIVE:
// These are relocations which should only be seen by the
// dynamic linker, and should never be seen here.
gold_error(_("%s: unexpected reloc %u in object file"),
object->name().c_str(), r_type);
break;
default:
unsupported_reloc_local(object, r_type);
break;
}
}
// Report an unsupported relocation against a global symbol.
template<bool big_endian>
void
Target_arm<big_endian>::Scan::unsupported_reloc_global(
Sized_relobj<32, big_endian>* object,
unsigned int r_type,
Symbol* gsym)
{
gold_error(_("%s: unsupported reloc %u against global symbol %s"),
object->name().c_str(), r_type, gsym->demangled_name().c_str());
}
// Scan a relocation for a global symbol.
// FIXME: This only handles a subset of relocation types used by Android
// on ARM v5te devices.
template<bool big_endian>
inline void
Target_arm<big_endian>::Scan::global(const General_options&,
Symbol_table* symtab,
Layout* layout,
Target_arm* target,
Sized_relobj<32, big_endian>* object,
unsigned int data_shndx,
Output_section* output_section,
const elfcpp::Rel<32, big_endian>& reloc,
unsigned int r_type,
Symbol* gsym)
{
r_type = get_real_reloc_type(r_type);
switch (r_type)
{
case elfcpp::R_ARM_NONE:
break;
case elfcpp::R_ARM_ABS32:
{
// Make a dynamic relocation if necessary.
if (gsym->needs_dynamic_reloc(Symbol::ABSOLUTE_REF))
{
if (target->may_need_copy_reloc(gsym))
{
target->copy_reloc(symtab, layout, object,
data_shndx, output_section, gsym, reloc);
}
else if (gsym->can_use_relative_reloc(false))
{
// If we are to add more other reloc types than R_ARM_ABS32,
// we need to add check_non_pic(object, r_type) here.
Reloc_section* rel_dyn = target->rel_dyn_section(layout);
rel_dyn->add_global_relative(gsym, elfcpp::R_ARM_RELATIVE,
output_section, object,
data_shndx, reloc.get_r_offset());
}
else
{
// If we are to add more other reloc types than R_ARM_ABS32,
// we need to add check_non_pic(object, r_type) here.
Reloc_section* rel_dyn = target->rel_dyn_section(layout);
rel_dyn->add_global(gsym, r_type, output_section, object,
data_shndx, reloc.get_r_offset());
}
}
}
break;
case elfcpp::R_ARM_REL32:
case elfcpp::R_ARM_PREL31:
{
// Make a dynamic relocation if necessary.
int flags = Symbol::NON_PIC_REF;
if (gsym->needs_dynamic_reloc(flags))
{
if (target->may_need_copy_reloc(gsym))
{
target->copy_reloc(symtab, layout, object,
data_shndx, output_section, gsym, reloc);
}
else
{
check_non_pic(object, r_type);
Reloc_section* rel_dyn = target->rel_dyn_section(layout);
rel_dyn->add_global(gsym, r_type, output_section, object,
data_shndx, reloc.get_r_offset());
}
}
}
break;
case elfcpp::R_ARM_JUMP24:
case elfcpp::R_ARM_THM_CALL:
case elfcpp::R_ARM_CALL:
{
if (Target_arm<big_endian>::Scan::symbol_needs_plt_entry(gsym))
target->make_plt_entry(symtab, layout, gsym);
// Make a dynamic relocation if necessary.
int flags = Symbol::NON_PIC_REF;
if (gsym->type() == elfcpp::STT_FUNC
|| gsym->type() == elfcpp::STT_ARM_TFUNC)
flags |= Symbol::FUNCTION_CALL;
if (gsym->needs_dynamic_reloc(flags))
{
if (target->may_need_copy_reloc(gsym))
{
target->copy_reloc(symtab, layout, object,
data_shndx, output_section, gsym,
reloc);
}
else
{
check_non_pic(object, r_type);
Reloc_section* rel_dyn = target->rel_dyn_section(layout);
rel_dyn->add_global(gsym, r_type, output_section, object,
data_shndx, reloc.get_r_offset());
}
}
}
break;
case elfcpp::R_ARM_PLT32:
// If the symbol is fully resolved, this is just a relative
// local reloc. Otherwise we need a PLT entry.
if (gsym->final_value_is_known())
break;
// If building a shared library, we can also skip the PLT entry
// if the symbol is defined in the output file and is protected
// or hidden.
if (gsym->is_defined()
&& !gsym->is_from_dynobj()
&& !gsym->is_preemptible())
break;
target->make_plt_entry(symtab, layout, gsym);
break;
case elfcpp::R_ARM_GOTOFF32:
// We need a GOT section.
target->got_section(symtab, layout);
break;
case elfcpp::R_ARM_BASE_PREL:
// FIXME: What about this?
break;
case elfcpp::R_ARM_GOT_BREL:
{
// The symbol requires a GOT entry.
Output_data_got<32, big_endian>* got =
target->got_section(symtab, layout);
if (gsym->final_value_is_known())
got->add_global(gsym, GOT_TYPE_STANDARD);
else
{
// If this symbol is not fully resolved, we need to add a
// GOT entry with a dynamic relocation.
Reloc_section* rel_dyn = target->rel_dyn_section(layout);
if (gsym->is_from_dynobj()
|| gsym->is_undefined()
|| gsym->is_preemptible())
got->add_global_with_rel(gsym, GOT_TYPE_STANDARD,
rel_dyn, elfcpp::R_ARM_GLOB_DAT);
else
{
if (got->add_global(gsym, GOT_TYPE_STANDARD))
rel_dyn->add_global_relative(
gsym, elfcpp::R_ARM_RELATIVE, got,
gsym->got_offset(GOT_TYPE_STANDARD));
}
}
}
break;
case elfcpp::R_ARM_TARGET1:
// This should have been mapped to another type already.
// Fall through.
case elfcpp::R_ARM_COPY:
case elfcpp::R_ARM_GLOB_DAT:
case elfcpp::R_ARM_JUMP_SLOT:
case elfcpp::R_ARM_RELATIVE:
// These are relocations which should only be seen by the
// dynamic linker, and should never be seen here.
gold_error(_("%s: unexpected reloc %u in object file"),
object->name().c_str(), r_type);
break;
default:
unsupported_reloc_global(object, r_type, gsym);
break;
}
}
// Process relocations for gc.
template<bool big_endian>
void
Target_arm<big_endian>::gc_process_relocs(const General_options& options,
Symbol_table* symtab,
Layout* layout,
Sized_relobj<32, big_endian>* object,
unsigned int data_shndx,
unsigned int,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
size_t local_symbol_count,
const unsigned char* plocal_symbols)
{
typedef Target_arm<big_endian> Arm;
typedef typename Target_arm<big_endian>::Scan Scan;
gold::gc_process_relocs<32, big_endian, Arm, elfcpp::SHT_REL, Scan>(
options,
symtab,
layout,
this,
object,
data_shndx,
prelocs,
reloc_count,
output_section,
needs_special_offset_handling,
local_symbol_count,
plocal_symbols);
}
// Scan relocations for a section.
template<bool big_endian>
void
Target_arm<big_endian>::scan_relocs(const General_options& options,
Symbol_table* symtab,
Layout* layout,
Sized_relobj<32, big_endian>* object,
unsigned int data_shndx,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
size_t local_symbol_count,
const unsigned char* plocal_symbols)
{
typedef typename Target_arm<big_endian>::Scan Scan;
if (sh_type == elfcpp::SHT_RELA)
{
gold_error(_("%s: unsupported RELA reloc section"),
object->name().c_str());
return;
}
gold::scan_relocs<32, big_endian, Target_arm, elfcpp::SHT_REL, Scan>(
options,
symtab,
layout,
this,
object,
data_shndx,
prelocs,
reloc_count,
output_section,
needs_special_offset_handling,
local_symbol_count,
plocal_symbols);
}
// Finalize the sections.
template<bool big_endian>
void
Target_arm<big_endian>::do_finalize_sections(Layout* layout)
{
// Fill in some more dynamic tags.
Output_data_dynamic* const odyn = layout->dynamic_data();
if (odyn != NULL)
{
if (this->got_plt_ != NULL)
odyn->add_section_address(elfcpp::DT_PLTGOT, this->got_plt_);
if (this->plt_ != NULL)
{
const Output_data* od = this->plt_->rel_plt();
odyn->add_section_size(elfcpp::DT_PLTRELSZ, od);
odyn->add_section_address(elfcpp::DT_JMPREL, od);
odyn->add_constant(elfcpp::DT_PLTREL, elfcpp::DT_REL);
}
if (this->rel_dyn_ != NULL)
{
const Output_data* od = this->rel_dyn_;
odyn->add_section_address(elfcpp::DT_REL, od);
odyn->add_section_size(elfcpp::DT_RELSZ, od);
odyn->add_constant(elfcpp::DT_RELENT,
elfcpp::Elf_sizes<32>::rel_size);
}
if (!parameters->options().shared())
{
// The value of the DT_DEBUG tag is filled in by the dynamic
// linker at run time, and used by the debugger.
odyn->add_constant(elfcpp::DT_DEBUG, 0);
}
}
// Emit any relocs we saved in an attempt to avoid generating COPY
// relocs.
if (this->copy_relocs_.any_saved_relocs())
this->copy_relocs_.emit(this->rel_dyn_section(layout));
}
// Return whether a direct absolute static relocation needs to be applied.
// In cases where Scan::local() or Scan::global() has created
// a dynamic relocation other than R_ARM_RELATIVE, the addend
// of the relocation is carried in the data, and we must not
// apply the static relocation.
template<bool big_endian>
inline bool
Target_arm<big_endian>::Relocate::should_apply_static_reloc(
const Sized_symbol<32>* gsym,
int ref_flags,
bool is_32bit,
Output_section* output_section)
{
// If the output section is not allocated, then we didn't call
// scan_relocs, we didn't create a dynamic reloc, and we must apply
// the reloc here.
if ((output_section->flags() & elfcpp::SHF_ALLOC) == 0)
return true;
// For local symbols, we will have created a non-RELATIVE dynamic
// relocation only if (a) the output is position independent,
// (b) the relocation is absolute (not pc- or segment-relative), and
// (c) the relocation is not 32 bits wide.
if (gsym == NULL)
return !(parameters->options().output_is_position_independent()
&& (ref_flags & Symbol::ABSOLUTE_REF)
&& !is_32bit);
// For global symbols, we use the same helper routines used in the
// scan pass. If we did not create a dynamic relocation, or if we
// created a RELATIVE dynamic relocation, we should apply the static
// relocation.
bool has_dyn = gsym->needs_dynamic_reloc(ref_flags);
bool is_rel = (ref_flags & Symbol::ABSOLUTE_REF)
&& gsym->can_use_relative_reloc(ref_flags
& Symbol::FUNCTION_CALL);
return !has_dyn || is_rel;
}
// Perform a relocation.
template<bool big_endian>
inline bool
Target_arm<big_endian>::Relocate::relocate(
const Relocate_info<32, big_endian>* relinfo,
Target_arm* target,
Output_section *output_section,
size_t relnum,
const elfcpp::Rel<32, big_endian>& rel,
unsigned int r_type,
const Sized_symbol<32>* gsym,
const Symbol_value<32>* psymval,
unsigned char* view,
elfcpp::Elf_types<32>::Elf_Addr address,
section_size_type /* view_size */ )
{
typedef Arm_relocate_functions<big_endian> Arm_relocate_functions;
r_type = get_real_reloc_type(r_type);
// If this the symbol may be a Thumb function, set thumb bit to 1.
bool has_thumb_bit = ((gsym != NULL)
&& (gsym->type() == elfcpp::STT_FUNC
|| gsym->type() == elfcpp::STT_ARM_TFUNC));
// Pick the value to use for symbols defined in shared objects.
Symbol_value<32> symval;
if (gsym != NULL
&& gsym->use_plt_offset(reloc_is_non_pic(r_type)))
{
symval.set_output_value(target->plt_section()->address()
+ gsym->plt_offset());
psymval = &symval;
has_thumb_bit = 0;
}
const Sized_relobj<32, big_endian>* object = relinfo->object;
// Get the GOT offset if needed.
// The GOT pointer points to the end of the GOT section.
// We need to subtract the size of the GOT section to get
// the actual offset to use in the relocation.
bool have_got_offset = false;
unsigned int got_offset = 0;
switch (r_type)
{
case elfcpp::R_ARM_GOT_BREL:
if (gsym != NULL)
{
gold_assert(gsym->has_got_offset(GOT_TYPE_STANDARD));
got_offset = (gsym->got_offset(GOT_TYPE_STANDARD)
- target->got_size());
}
else
{
unsigned int r_sym = elfcpp::elf_r_sym<32>(rel.get_r_info());
gold_assert(object->local_has_got_offset(r_sym, GOT_TYPE_STANDARD));
got_offset = (object->local_got_offset(r_sym, GOT_TYPE_STANDARD)
- target->got_size());
}
have_got_offset = true;
break;
default:
break;
}
typename Arm_relocate_functions::Status reloc_status =
Arm_relocate_functions::STATUS_OKAY;
switch (r_type)
{
case elfcpp::R_ARM_NONE:
break;
case elfcpp::R_ARM_ABS32:
if (should_apply_static_reloc(gsym, Symbol::ABSOLUTE_REF, true,
output_section))
reloc_status = Arm_relocate_functions::abs32(view, object, psymval,
has_thumb_bit);
break;
case elfcpp::R_ARM_REL32:
reloc_status = Arm_relocate_functions::rel32(view, object, psymval,
address, has_thumb_bit);
break;
case elfcpp::R_ARM_THM_CALL:
reloc_status = Arm_relocate_functions::thm_call(view, object, psymval,
address, has_thumb_bit);
break;
case elfcpp::R_ARM_GOTOFF32:
{
elfcpp::Elf_types<32>::Elf_Addr got_origin;
got_origin = target->got_plt_section()->address();
reloc_status = Arm_relocate_functions::rel32(view, object, psymval,
got_origin, has_thumb_bit);
}
break;
case elfcpp::R_ARM_BASE_PREL:
{
uint32_t origin;
// Get the addressing origin of the output segment defining the
// symbol gsym (AAELF 4.6.1.2 Relocation types)
gold_assert(gsym != NULL);
if (gsym->source() == Symbol::IN_OUTPUT_SEGMENT)
origin = gsym->output_segment()->vaddr();
else if (gsym->source () == Symbol::IN_OUTPUT_DATA)
origin = gsym->output_data()->address();
else
{
gold_error_at_location(relinfo, relnum, rel.get_r_offset(),
_("cannot find origin of R_ARM_BASE_PREL"));
return true;
}
reloc_status = Arm_relocate_functions::base_prel(view, origin, address);
}
break;
case elfcpp::R_ARM_GOT_BREL:
gold_assert(have_got_offset);
reloc_status = Arm_relocate_functions::got_brel(view, got_offset);
break;
case elfcpp::R_ARM_PLT32:
gold_assert(gsym == NULL
|| gsym->has_plt_offset()
|| gsym->final_value_is_known()
|| (gsym->is_defined()
&& !gsym->is_from_dynobj()
&& !gsym->is_preemptible()));
reloc_status = Arm_relocate_functions::plt32(view, object, psymval,
address, has_thumb_bit);
break;
case elfcpp::R_ARM_CALL:
reloc_status = Arm_relocate_functions::call(view, object, psymval,
address, has_thumb_bit);
break;
case elfcpp::R_ARM_JUMP24:
reloc_status = Arm_relocate_functions::jump24(view, object, psymval,
address, has_thumb_bit);
break;
case elfcpp::R_ARM_PREL31:
reloc_status = Arm_relocate_functions::prel31(view, object, psymval,
address, has_thumb_bit);
break;
case elfcpp::R_ARM_TARGET1:
// This should have been mapped to another type already.
// Fall through.
case elfcpp::R_ARM_COPY:
case elfcpp::R_ARM_GLOB_DAT:
case elfcpp::R_ARM_JUMP_SLOT:
case elfcpp::R_ARM_RELATIVE:
// These are relocations which should only be seen by the
// dynamic linker, and should never be seen here.
gold_error_at_location(relinfo, relnum, rel.get_r_offset(),
_("unexpected reloc %u in object file"),
r_type);
break;
default:
gold_error_at_location(relinfo, relnum, rel.get_r_offset(),
_("unsupported reloc %u"),
r_type);
break;
}
// Report any errors.
switch (reloc_status)
{
case Arm_relocate_functions::STATUS_OKAY:
break;
case Arm_relocate_functions::STATUS_OVERFLOW:
gold_error_at_location(relinfo, relnum, rel.get_r_offset(),
_("relocation overflow in relocation %u"),
r_type);
break;
case Arm_relocate_functions::STATUS_BAD_RELOC:
gold_error_at_location(
relinfo,
relnum,
rel.get_r_offset(),
_("unexpected opcode while processing relocation %u"),
r_type);
break;
default:
gold_unreachable();
}
return true;
}
// Relocate section data.
template<bool big_endian>
void
Target_arm<big_endian>::relocate_section(
const Relocate_info<32, big_endian>* relinfo,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
unsigned char* view,
elfcpp::Elf_types<32>::Elf_Addr address,
section_size_type view_size)
{
typedef typename Target_arm<big_endian>::Relocate Arm_relocate;
gold_assert(sh_type == elfcpp::SHT_REL);
gold::relocate_section<32, big_endian, Target_arm, elfcpp::SHT_REL,
Arm_relocate>(
relinfo,
this,
prelocs,
reloc_count,
output_section,
needs_special_offset_handling,
view,
address,
view_size);
}
// Return the size of a relocation while scanning during a relocatable
// link.
template<bool big_endian>
unsigned int
Target_arm<big_endian>::Relocatable_size_for_reloc::get_size_for_reloc(
unsigned int r_type,
Relobj* object)
{
r_type = get_real_reloc_type(r_type);
switch (r_type)
{
case elfcpp::R_ARM_NONE:
return 0;
case elfcpp::R_ARM_ABS32:
case elfcpp::R_ARM_REL32:
case elfcpp::R_ARM_THM_CALL:
case elfcpp::R_ARM_GOTOFF32:
case elfcpp::R_ARM_BASE_PREL:
case elfcpp::R_ARM_GOT_BREL:
case elfcpp::R_ARM_PLT32:
case elfcpp::R_ARM_CALL:
case elfcpp::R_ARM_JUMP24:
case elfcpp::R_ARM_PREL31:
return 4;
case elfcpp::R_ARM_TARGET1:
// This should have been mapped to another type already.
// Fall through.
case elfcpp::R_ARM_COPY:
case elfcpp::R_ARM_GLOB_DAT:
case elfcpp::R_ARM_JUMP_SLOT:
case elfcpp::R_ARM_RELATIVE:
// These are relocations which should only be seen by the
// dynamic linker, and should never be seen here.
gold_error(_("%s: unexpected reloc %u in object file"),
object->name().c_str(), r_type);
return 0;
default:
object->error(_("unsupported reloc %u in object file"), r_type);
return 0;
}
}
// Scan the relocs during a relocatable link.
template<bool big_endian>
void
Target_arm<big_endian>::scan_relocatable_relocs(
const General_options& options,
Symbol_table* symtab,
Layout* layout,
Sized_relobj<32, big_endian>* object,
unsigned int data_shndx,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
size_t local_symbol_count,
const unsigned char* plocal_symbols,
Relocatable_relocs* rr)
{
gold_assert(sh_type == elfcpp::SHT_REL);
typedef gold::Default_scan_relocatable_relocs<elfcpp::SHT_REL,
Relocatable_size_for_reloc> Scan_relocatable_relocs;
gold::scan_relocatable_relocs<32, big_endian, elfcpp::SHT_REL,
Scan_relocatable_relocs>(
options,
symtab,
layout,
object,
data_shndx,
prelocs,
reloc_count,
output_section,
needs_special_offset_handling,
local_symbol_count,
plocal_symbols,
rr);
}
// Relocate a section during a relocatable link.
template<bool big_endian>
void
Target_arm<big_endian>::relocate_for_relocatable(
const Relocate_info<32, big_endian>* relinfo,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
off_t offset_in_output_section,
const Relocatable_relocs* rr,
unsigned char* view,
elfcpp::Elf_types<32>::Elf_Addr view_address,
section_size_type view_size,
unsigned char* reloc_view,
section_size_type reloc_view_size)
{
gold_assert(sh_type == elfcpp::SHT_REL);
gold::relocate_for_relocatable<32, big_endian, elfcpp::SHT_REL>(
relinfo,
prelocs,
reloc_count,
output_section,
offset_in_output_section,
rr,
view,
view_address,
view_size,
reloc_view,
reloc_view_size);
}
// Return the value to use for a dynamic symbol which requires special
// treatment. This is how we support equality comparisons of function
// pointers across shared library boundaries, as described in the
// processor specific ABI supplement.
template<bool big_endian>
uint64_t
Target_arm<big_endian>::do_dynsym_value(const Symbol* gsym) const
{
gold_assert(gsym->is_from_dynobj() && gsym->has_plt_offset());
return this->plt_section()->address() + gsym->plt_offset();
}
// Map platform-specific relocs to real relocs
//
template<bool big_endian>
unsigned int
Target_arm<big_endian>::get_real_reloc_type (unsigned int r_type)
{
switch (r_type)
{
case elfcpp::R_ARM_TARGET1:
// This is either R_ARM_ABS32 or R_ARM_REL32;
return elfcpp::R_ARM_ABS32;
case elfcpp::R_ARM_TARGET2:
// This can be any reloc type but ususally is R_ARM_GOT_PREL
return elfcpp::R_ARM_GOT_PREL;
default:
return r_type;
}
}
// The selector for arm object files.
template<bool big_endian>
class Target_selector_arm : public Target_selector
{
public:
Target_selector_arm()
: Target_selector(elfcpp::EM_ARM, 32, big_endian,
(big_endian ? "elf32-bigarm" : "elf32-littlearm"))
{ }
Target*
do_instantiate_target()
{ return new Target_arm<big_endian>(); }
};
Target_selector_arm<false> target_selector_arm;
Target_selector_arm<true> target_selector_armbe;
} // End anonymous namespace.
| wanghao-xznu/vte | openlibs/binutils-2.19.51.0.12/gold/arm.cc | C++ | gpl-2.0 | 57,169 |
//=============================================================================
//=== Copyright (C) 2001-2005 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== This library is free software; you can redistribute it and/or
//=== modify it under the terms of the GNU Lesser General Public
//=== License as published by the Free Software Foundation; either
//=== version 2.1 of the License, or (at your option) any later version.
//===
//=== This library is distributed in the hope that it will be useful,
//=== but WITHOUT ANY WARRANTY; without even the implied warranty of
//=== MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//=== Lesser General Public License for more details.
//===
//=== You should have received a copy of the GNU Lesser General Public
//=== License along with this library; if not, write to the Free Software
//=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: GeoNetwork@fao.org
//==============================================================================
package jeeves.server.sources;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import jeeves.constants.Jeeves;
import jeeves.utils.Xml;
import org.jdom.Document;
import org.jdom.Element;
//=============================================================================
/** A ServiceRequest is a generic request for a service
*/
public class ServiceRequest
{
public enum InputMethod { GET, POST, XML, SOAP, JSON }
public enum OutputMethod { DEFAULT, XML, SOAP, JSON }
//---------------------------------------------------------------------------
protected String service = null;
protected String language = null;
protected Element params = new Element(Jeeves.Elem.REQUEST);
protected boolean debug = false;
protected OutputStream outStream = null;
protected String address = "0.0.0.0";
protected int statusCode= 200;
protected InputMethod input = InputMethod.GET;
protected OutputMethod output = OutputMethod.DEFAULT;
private Map<String, String> headers = new HashMap<String, String>();
//---------------------------------------------------------------------------
public ServiceRequest() {}
//---------------------------------------------------------------------------
//---
//--- API
//---
//---------------------------------------------------------------------------
/** Name of the requested service */
public String getService() { return service; }
//---------------------------------------------------------------------------
/** requesting language (eg. 'en') */
public String getLanguage() { return language; }
//---------------------------------------------------------------------------
/** requesting parameters*/
public Element getParams() { return params; }
//---------------------------------------------------------------------------
/**
* @return Map of the request headers
*/
public Map<String, String> getHeaders() { return headers; }
//---------------------------------------------------------------------------
/** true if the request has the debug option turned on */
public boolean hasDebug() { return debug; }
//---------------------------------------------------------------------------
/** gets the output stream of this request to output data */
public OutputStream getOutputStream() throws IOException { return outStream; }
//---------------------------------------------------------------------------
/** gets the ip address of the request (if any) */
public String getAddress() { return address; }
//---------------------------------------------------------------------------
public InputMethod getInputMethod() { return input; }
public OutputMethod getOutputMethod() { return output; }
//---------------------------------------------------------------------------
public void setService (String newService) { service = newService; }
public void setLanguage(String newLang) { language = newLang; }
public void setParams (Element newParams) { params = newParams; }
public void setHeaders (Map<String, String> newHeaders) { headers = newHeaders; }
public void setAddress (String newAddress) { address = newAddress; }
public void setStatusCode(int code) { statusCode = code; }
public void setInputMethod (InputMethod m) { input = m; }
public void setOutputMethod(OutputMethod m) { output = m; }
//---------------------------------------------------------------------------
public void setOutputStream(OutputStream os) { outStream = os; }
//---------------------------------------------------------------------------
public void setDebug(boolean yesno) { debug = yesno; }
//---------------------------------------------------------------------------
public void write(Element response) throws IOException
{
Xml.writeResponse(new Document(response), getOutputStream());
endStream();
}
//---------------------------------------------------------------------------
/** called when the system starts streaming data */
public void beginStream(String contentType, boolean cache) {}
//---------------------------------------------------------------------------
public void beginStream(String contentType, int contentLength, String contentDisp,
boolean cache) {}
//---------------------------------------------------------------------------
/** called when the system ends streaming data*/
public void endStream() throws IOException {}
}
//=============================================================================
| OpenWIS/openwis | openwis-metadataportal/jeeves/src/main/java/jeeves/server/sources/ServiceRequest.java | Java | gpl-3.0 | 5,868 |
package com.pelter.common.entities;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
/**
* Simple JavaBean domain object adds a name property to <code>BaseEntity</code>.
* Used as a base class for objects
* needing these properties.
*
* @author Janssens Luc
* @year 2017
*/
@MappedSuperclass
public class NamedEntity extends BaseEntity {
@Column(name = "name")
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return this.getName();
}
} | JanssensLuc/Pelter | src/main/java/com/pelter/common/entities/NamedEntity.java | Java | gpl-3.0 | 680 |
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <cstdlib>
using namespace std;
class Solution {
private:
map<string, vector<int>> memo;
public:
int compute(int a, int b, char op) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
}
return 1;
}
vector<int> diffWaysToCompute(string input) {
if (memo.count(input)) {
return memo[input];
}
int val = 0, idx = 0;
while (idx < input.length() && isdigit(input[idx])) {
val *= 10;
val += input[idx++] - '0';
}
if (idx == input.length()) return {val};
vector<int> res;
vector<int> left, right;
for (int i = 0; i < input.length(); ++i) {
if (!isdigit(input[i])) {
left = diffWaysToCompute(input.substr(0, i));
right = diffWaysToCompute(input.substr(i + 1, input.length() -1 - i));
for (int j = 0; j < left.size(); ++j) {
for (int k = 0; k < right.size(); ++k) {
res.push_back(compute(left[j], right[k], input[i]));
}
}
}
}
return memo[input] = res;
}
};
int main() {
Solution sol;
for (int i : sol.diffWaysToCompute("2-1-1")) {
cout << i << endl;
}
for (int i : sol.diffWaysToCompute("2*3-4*5")) {
cout << i << endl;
}
return 0;
}
| asraf209/leetcode | src/different_ways_to_add_parentheses/main.cpp | C++ | gpl-3.0 | 1,339 |
//===------ utils/wasm2yaml.cpp - obj2yaml conversion tool ------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "obj2yaml.h"
#include "llvm/Object/COFF.h"
#include "llvm/ObjectYAML/WasmYAML.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/YAMLTraits.h"
using namespace llvm;
using object::WasmSection;
namespace {
class WasmDumper {
const object::WasmObjectFile &Obj;
public:
WasmDumper(const object::WasmObjectFile &O) : Obj(O) {}
ErrorOr<WasmYAML::Object *> dump();
std::unique_ptr<WasmYAML::CustomSection>
dumpCustomSection(const WasmSection &WasmSec);
};
} // namespace
static WasmYAML::Limits makeLimits(const wasm::WasmLimits &Limits) {
WasmYAML::Limits L;
L.Flags = Limits.Flags;
L.Initial = Limits.Initial;
L.Maximum = Limits.Maximum;
return L;
}
static WasmYAML::Table makeTable(uint32_t Index,
const wasm::WasmTableType &Type) {
WasmYAML::Table T;
T.Index = Index;
T.ElemType = Type.ElemType;
T.TableLimits = makeLimits(Type.Limits);
return T;
}
std::unique_ptr<WasmYAML::CustomSection>
WasmDumper::dumpCustomSection(const WasmSection &WasmSec) {
std::unique_ptr<WasmYAML::CustomSection> CustomSec;
if (WasmSec.Name == "dylink") {
std::unique_ptr<WasmYAML::DylinkSection> DylinkSec =
std::make_unique<WasmYAML::DylinkSection>();
const wasm::WasmDylinkInfo& Info = Obj.dylinkInfo();
DylinkSec->MemorySize = Info.MemorySize;
DylinkSec->MemoryAlignment = Info.MemoryAlignment;
DylinkSec->TableSize = Info.TableSize;
DylinkSec->TableAlignment = Info.TableAlignment;
DylinkSec->Needed = Info.Needed;
CustomSec = std::move(DylinkSec);
} else if (WasmSec.Name == "name") {
std::unique_ptr<WasmYAML::NameSection> NameSec =
std::make_unique<WasmYAML::NameSection>();
for (const llvm::wasm::WasmDebugName &Name : Obj.debugNames()) {
WasmYAML::NameEntry NameEntry;
NameEntry.Name = Name.Name;
NameEntry.Index = Name.Index;
if (Name.Type == llvm::wasm::NameType::FUNCTION) {
NameSec->FunctionNames.push_back(NameEntry);
} else if (Name.Type == llvm::wasm::NameType::GLOBAL) {
NameSec->GlobalNames.push_back(NameEntry);
} else {
assert(Name.Type == llvm::wasm::NameType::DATA_SEGMENT);
NameSec->DataSegmentNames.push_back(NameEntry);
}
}
CustomSec = std::move(NameSec);
} else if (WasmSec.Name == "linking") {
std::unique_ptr<WasmYAML::LinkingSection> LinkingSec =
std::make_unique<WasmYAML::LinkingSection>();
LinkingSec->Version = Obj.linkingData().Version;
ArrayRef<StringRef> Comdats = Obj.linkingData().Comdats;
for (StringRef ComdatName : Comdats)
LinkingSec->Comdats.emplace_back(WasmYAML::Comdat{ComdatName, {}});
for (auto &Func : Obj.functions()) {
if (Func.Comdat != UINT32_MAX) {
LinkingSec->Comdats[Func.Comdat].Entries.emplace_back(
WasmYAML::ComdatEntry{wasm::WASM_COMDAT_FUNCTION, Func.Index});
}
}
uint32_t SegmentIndex = 0;
for (const object::WasmSegment &Segment : Obj.dataSegments()) {
if (!Segment.Data.Name.empty()) {
WasmYAML::SegmentInfo SegmentInfo;
SegmentInfo.Name = Segment.Data.Name;
SegmentInfo.Index = SegmentIndex;
SegmentInfo.Alignment = Segment.Data.Alignment;
SegmentInfo.Flags = Segment.Data.LinkerFlags;
LinkingSec->SegmentInfos.push_back(SegmentInfo);
}
if (Segment.Data.Comdat != UINT32_MAX) {
LinkingSec->Comdats[Segment.Data.Comdat].Entries.emplace_back(
WasmYAML::ComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
}
SegmentIndex++;
}
uint32_t SectionIndex = 0;
for (const auto &Sec : Obj.sections()) {
const WasmSection &WasmSec = Obj.getWasmSection(Sec);
if (WasmSec.Comdat != UINT32_MAX)
LinkingSec->Comdats[WasmSec.Comdat].Entries.emplace_back(
WasmYAML::ComdatEntry{wasm::WASM_COMDAT_SECTION, SectionIndex});
SectionIndex++;
}
uint32_t SymbolIndex = 0;
for (const wasm::WasmSymbolInfo &Symbol : Obj.linkingData().SymbolTable) {
WasmYAML::SymbolInfo Info;
Info.Index = SymbolIndex++;
Info.Kind = static_cast<uint32_t>(Symbol.Kind);
Info.Name = Symbol.Name;
Info.Flags = Symbol.Flags;
switch (Symbol.Kind) {
case wasm::WASM_SYMBOL_TYPE_DATA:
Info.DataRef = Symbol.DataRef;
break;
case wasm::WASM_SYMBOL_TYPE_FUNCTION:
case wasm::WASM_SYMBOL_TYPE_GLOBAL:
case wasm::WASM_SYMBOL_TYPE_TABLE:
case wasm::WASM_SYMBOL_TYPE_EVENT:
Info.ElementIndex = Symbol.ElementIndex;
break;
case wasm::WASM_SYMBOL_TYPE_SECTION:
Info.ElementIndex = Symbol.ElementIndex;
break;
}
LinkingSec->SymbolTable.emplace_back(Info);
}
for (const wasm::WasmInitFunc &Func : Obj.linkingData().InitFunctions) {
WasmYAML::InitFunction F{Func.Priority, Func.Symbol};
LinkingSec->InitFunctions.emplace_back(F);
}
CustomSec = std::move(LinkingSec);
} else if (WasmSec.Name == "producers") {
std::unique_ptr<WasmYAML::ProducersSection> ProducersSec =
std::make_unique<WasmYAML::ProducersSection>();
const llvm::wasm::WasmProducerInfo &Info = Obj.getProducerInfo();
for (auto &E : Info.Languages) {
WasmYAML::ProducerEntry Producer;
Producer.Name = E.first;
Producer.Version = E.second;
ProducersSec->Languages.push_back(Producer);
}
for (auto &E : Info.Tools) {
WasmYAML::ProducerEntry Producer;
Producer.Name = E.first;
Producer.Version = E.second;
ProducersSec->Tools.push_back(Producer);
}
for (auto &E : Info.SDKs) {
WasmYAML::ProducerEntry Producer;
Producer.Name = E.first;
Producer.Version = E.second;
ProducersSec->SDKs.push_back(Producer);
}
CustomSec = std::move(ProducersSec);
} else if (WasmSec.Name == "target_features") {
std::unique_ptr<WasmYAML::TargetFeaturesSection> TargetFeaturesSec =
std::make_unique<WasmYAML::TargetFeaturesSection>();
for (auto &E : Obj.getTargetFeatures()) {
WasmYAML::FeatureEntry Feature;
Feature.Prefix = E.Prefix;
Feature.Name = E.Name;
TargetFeaturesSec->Features.push_back(Feature);
}
CustomSec = std::move(TargetFeaturesSec);
} else {
CustomSec = std::make_unique<WasmYAML::CustomSection>(WasmSec.Name);
}
CustomSec->Payload = yaml::BinaryRef(WasmSec.Content);
return CustomSec;
}
ErrorOr<WasmYAML::Object *> WasmDumper::dump() {
auto Y = std::make_unique<WasmYAML::Object>();
// Dump header
Y->Header.Version = Obj.getHeader().Version;
// Dump sections
for (const auto &Sec : Obj.sections()) {
const WasmSection &WasmSec = Obj.getWasmSection(Sec);
std::unique_ptr<WasmYAML::Section> S;
switch (WasmSec.Type) {
case wasm::WASM_SEC_CUSTOM: {
if (WasmSec.Name.startswith("reloc.")) {
// Relocations are attached the sections they apply to rather than
// being represented as a custom section in the YAML output.
continue;
}
S = dumpCustomSection(WasmSec);
break;
}
case wasm::WASM_SEC_TYPE: {
auto TypeSec = std::make_unique<WasmYAML::TypeSection>();
uint32_t Index = 0;
for (const auto &FunctionSig : Obj.types()) {
WasmYAML::Signature Sig;
Sig.Index = Index++;
for (const auto &ParamType : FunctionSig.Params)
Sig.ParamTypes.emplace_back(static_cast<uint32_t>(ParamType));
for (const auto &ReturnType : FunctionSig.Returns)
Sig.ReturnTypes.emplace_back(static_cast<uint32_t>(ReturnType));
TypeSec->Signatures.push_back(Sig);
}
S = std::move(TypeSec);
break;
}
case wasm::WASM_SEC_IMPORT: {
auto ImportSec = std::make_unique<WasmYAML::ImportSection>();
for (auto &Import : Obj.imports()) {
WasmYAML::Import Im;
Im.Module = Import.Module;
Im.Field = Import.Field;
Im.Kind = Import.Kind;
switch (Im.Kind) {
case wasm::WASM_EXTERNAL_FUNCTION:
Im.SigIndex = Import.SigIndex;
break;
case wasm::WASM_EXTERNAL_GLOBAL:
Im.GlobalImport.Type = Import.Global.Type;
Im.GlobalImport.Mutable = Import.Global.Mutable;
break;
case wasm::WASM_EXTERNAL_EVENT:
Im.EventImport.Attribute = Import.Event.Attribute;
Im.EventImport.SigIndex = Import.Event.SigIndex;
break;
case wasm::WASM_EXTERNAL_TABLE:
// FIXME: Currently we always output an index of 0 for any imported
// table.
Im.TableImport = makeTable(0, Import.Table);
break;
case wasm::WASM_EXTERNAL_MEMORY:
Im.Memory = makeLimits(Import.Memory);
break;
}
ImportSec->Imports.push_back(Im);
}
S = std::move(ImportSec);
break;
}
case wasm::WASM_SEC_FUNCTION: {
auto FuncSec = std::make_unique<WasmYAML::FunctionSection>();
for (const auto &Func : Obj.functionTypes()) {
FuncSec->FunctionTypes.push_back(Func);
}
S = std::move(FuncSec);
break;
}
case wasm::WASM_SEC_TABLE: {
auto TableSec = std::make_unique<WasmYAML::TableSection>();
for (const wasm::WasmTable &Table : Obj.tables()) {
TableSec->Tables.push_back(makeTable(Table.Index, Table.Type));
}
S = std::move(TableSec);
break;
}
case wasm::WASM_SEC_MEMORY: {
auto MemorySec = std::make_unique<WasmYAML::MemorySection>();
for (const wasm::WasmLimits &Memory : Obj.memories()) {
MemorySec->Memories.push_back(makeLimits(Memory));
}
S = std::move(MemorySec);
break;
}
case wasm::WASM_SEC_EVENT: {
auto EventSec = std::make_unique<WasmYAML::EventSection>();
for (auto &Event : Obj.events()) {
WasmYAML::Event E;
E.Index = Event.Index;
E.Attribute = Event.Type.Attribute;
E.SigIndex = Event.Type.SigIndex;
EventSec->Events.push_back(E);
}
S = std::move(EventSec);
break;
}
case wasm::WASM_SEC_GLOBAL: {
auto GlobalSec = std::make_unique<WasmYAML::GlobalSection>();
for (auto &Global : Obj.globals()) {
WasmYAML::Global G;
G.Index = Global.Index;
G.Type = Global.Type.Type;
G.Mutable = Global.Type.Mutable;
G.InitExpr = Global.InitExpr;
GlobalSec->Globals.push_back(G);
}
S = std::move(GlobalSec);
break;
}
case wasm::WASM_SEC_START: {
auto StartSec = std::make_unique<WasmYAML::StartSection>();
StartSec->StartFunction = Obj.startFunction();
S = std::move(StartSec);
break;
}
case wasm::WASM_SEC_EXPORT: {
auto ExportSec = std::make_unique<WasmYAML::ExportSection>();
for (auto &Export : Obj.exports()) {
WasmYAML::Export Ex;
Ex.Name = Export.Name;
Ex.Kind = Export.Kind;
Ex.Index = Export.Index;
ExportSec->Exports.push_back(Ex);
}
S = std::move(ExportSec);
break;
}
case wasm::WASM_SEC_ELEM: {
auto ElemSec = std::make_unique<WasmYAML::ElemSection>();
for (auto &Segment : Obj.elements()) {
WasmYAML::ElemSegment Seg;
Seg.TableIndex = Segment.TableIndex;
Seg.Offset = Segment.Offset;
for (auto &Func : Segment.Functions) {
Seg.Functions.push_back(Func);
}
ElemSec->Segments.push_back(Seg);
}
S = std::move(ElemSec);
break;
}
case wasm::WASM_SEC_CODE: {
auto CodeSec = std::make_unique<WasmYAML::CodeSection>();
for (auto &Func : Obj.functions()) {
WasmYAML::Function Function;
Function.Index = Func.Index;
for (auto &Local : Func.Locals) {
WasmYAML::LocalDecl LocalDecl;
LocalDecl.Type = Local.Type;
LocalDecl.Count = Local.Count;
Function.Locals.push_back(LocalDecl);
}
Function.Body = yaml::BinaryRef(Func.Body);
CodeSec->Functions.push_back(Function);
}
S = std::move(CodeSec);
break;
}
case wasm::WASM_SEC_DATA: {
auto DataSec = std::make_unique<WasmYAML::DataSection>();
for (const object::WasmSegment &Segment : Obj.dataSegments()) {
WasmYAML::DataSegment Seg;
Seg.SectionOffset = Segment.SectionOffset;
Seg.InitFlags = Segment.Data.InitFlags;
Seg.MemoryIndex = Segment.Data.MemoryIndex;
Seg.Offset = Segment.Data.Offset;
Seg.Content = yaml::BinaryRef(Segment.Data.Content);
DataSec->Segments.push_back(Seg);
}
S = std::move(DataSec);
break;
}
case wasm::WASM_SEC_DATACOUNT: {
auto DataCountSec = std::make_unique<WasmYAML::DataCountSection>();
DataCountSec->Count = Obj.dataSegments().size();
S = std::move(DataCountSec);
break;
}
default:
llvm_unreachable("Unknown section type");
break;
}
for (const wasm::WasmRelocation &Reloc : WasmSec.Relocations) {
WasmYAML::Relocation R;
R.Type = Reloc.Type;
R.Index = Reloc.Index;
R.Offset = Reloc.Offset;
R.Addend = Reloc.Addend;
S->Relocations.push_back(R);
}
Y->Sections.push_back(std::move(S));
}
return Y.release();
}
std::error_code wasm2yaml(raw_ostream &Out, const object::WasmObjectFile &Obj) {
WasmDumper Dumper(Obj);
ErrorOr<WasmYAML::Object *> YAMLOrErr = Dumper.dump();
if (std::error_code EC = YAMLOrErr.getError())
return EC;
std::unique_ptr<WasmYAML::Object> YAML(YAMLOrErr.get());
yaml::Output Yout(Out);
Yout << *YAML;
return std::error_code();
}
| sabel83/metashell | 3rd/templight/llvm/tools/obj2yaml/wasm2yaml.cpp | C++ | gpl-3.0 | 14,053 |
//
// srecord - manipulate eprom load files
// Copyright (C) 1998, 1999, 2001, 2002, 2004, 2006-2010 Peter Miller
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//
#include <cstring>
#include <srecord/interval.h>
#include <srecord/input/filter/fill.h>
#include <srecord/record.h>
srecord::input_filter_fill::~input_filter_fill()
{
delete [] filler_block;
}
srecord::input_filter_fill::input_filter_fill(const input::pointer &a1,
int a2, const interval &a3) :
input_filter(a1),
filler_value(a2),
filler_block(0),
range(a3)
{
}
srecord::input::pointer
srecord::input_filter_fill::create(const input::pointer &a_deeper,
int a_value, const interval &a_range)
{
return pointer(new input_filter_fill(a_deeper, a_value, a_range));
}
bool
srecord::input_filter_fill::generate(record &result)
{
if (range.empty())
return false;
interval::data_t lo = range.get_lowest();
size_t rec_len = record::maximum_data_length(lo);
interval::data_t hi = lo + rec_len;
interval chunk(lo, hi);
chunk *= range;
chunk.first_interval_only();
size_t fill_block_size = 256;
if (!filler_block)
{
filler_block = new unsigned char [fill_block_size];
memset(filler_block, filler_value, fill_block_size);
}
rec_len = chunk.get_highest() - chunk.get_lowest();
assert(rec_len <= fill_block_size);
result = record(record::type_data, lo, filler_block, rec_len);
range -= chunk;
return true;
}
bool
srecord::input_filter_fill::read(record &result)
{
if (!input_filter::read(result))
return generate(result);
if (result.get_type() == record::type_data)
{
range -=
interval
(
result.get_address(),
result.get_address() + result.get_length()
);
}
return true;
}
| freyc/SRecord | srecord/input/filter/fill.cc | C++ | gpl-3.0 | 2,486 |
<?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;
return [
'reference_id' => $reference_id, // '609',
'sex' => $sex,
'firstName' => $test,
'lastName' => $faker->lastName,
'firstName' => $faker->firstName,
'email' => $faker->unique()->safeEmail,
'reference_id' => $faker->randomDigit(10),
'password' => $password ?: $password = bcrypt('secret'),
'remember_token' => str_random(10),
];
});
| CodeforAustralia/vhs | database/factories/ModelFactory.php | PHP | gpl-3.0 | 955 |
"use strict";
var path_1 = require('path');
var errors_1 = require('./errors');
var fs_extra_1 = require('fs-extra');
var osName = require('os-name');
var _context;
var cachedAppScriptsPackageJson;
function getAppScriptsPackageJson() {
if (!cachedAppScriptsPackageJson) {
try {
cachedAppScriptsPackageJson = fs_extra_1.readJsonSync(path_1.join(__dirname, '..', '..', 'package.json'));
}
catch (e) { }
}
return cachedAppScriptsPackageJson;
}
exports.getAppScriptsPackageJson = getAppScriptsPackageJson;
function getAppScriptsVersion() {
var appScriptsPackageJson = getAppScriptsPackageJson();
return (appScriptsPackageJson && appScriptsPackageJson.version) ? appScriptsPackageJson.version : '';
}
exports.getAppScriptsVersion = getAppScriptsVersion;
function getUserPackageJson(userRootDir) {
try {
return fs_extra_1.readJsonSync(path_1.join(userRootDir, 'package.json'));
}
catch (e) { }
return null;
}
function getSystemInfo(userRootDir) {
var d = [];
var ionicAppScripts = getAppScriptsVersion();
var ionicFramework = null;
var ionicNative = null;
var angularCore = null;
var angularCompilerCli = null;
try {
var userPackageJson = getUserPackageJson(userRootDir);
if (userPackageJson) {
var userDependencies = userPackageJson.dependencies;
if (userDependencies) {
ionicFramework = userDependencies['ionic-angular'];
ionicNative = userDependencies['ionic-native'];
angularCore = userDependencies['@angular/core'];
angularCompilerCli = userDependencies['@angular/compiler-cli'];
}
}
}
catch (e) { }
d.push("Ionic Framework: " + ionicFramework);
if (ionicNative) {
d.push("Ionic Native: " + ionicNative);
}
d.push("Ionic App Scripts: " + ionicAppScripts);
d.push("Angular Core: " + angularCore);
d.push("Angular Compiler CLI: " + angularCompilerCli);
d.push("Node: " + process.version.replace('v', ''));
d.push("OS Platform: " + osName());
return d;
}
exports.getSystemInfo = getSystemInfo;
function splitLineBreaks(sourceText) {
if (!sourceText)
return [];
sourceText = sourceText.replace(/\\r/g, '\n');
return sourceText.split('\n');
}
exports.splitLineBreaks = splitLineBreaks;
exports.objectAssign = (Object.assign) ? Object.assign : function (target, source) {
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
source = arguments[index];
if (source !== undefined && source !== null) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
output[key] = source[key];
}
}
}
}
return output;
};
function titleCase(str) {
return str.charAt(0).toUpperCase() + str.substr(1);
}
exports.titleCase = titleCase;
function writeFileAsync(filePath, content) {
return new Promise(function (resolve, reject) {
fs_extra_1.writeFile(filePath, content, function (err) {
if (err) {
return reject(new errors_1.BuildError(err));
}
return resolve();
});
});
}
exports.writeFileAsync = writeFileAsync;
function readFileAsync(filePath) {
return new Promise(function (resolve, reject) {
fs_extra_1.readFile(filePath, 'utf-8', function (err, buffer) {
if (err) {
return reject(new errors_1.BuildError(err));
}
return resolve(buffer);
});
});
}
exports.readFileAsync = readFileAsync;
function unlinkAsync(filePath) {
return new Promise(function (resolve, reject) {
fs_extra_1.unlink(filePath, function (err) {
if (err) {
return reject(new errors_1.BuildError(err));
}
return resolve();
});
});
}
exports.unlinkAsync = unlinkAsync;
function rimRafAsync(directoryPath) {
return new Promise(function (resolve, reject) {
fs_extra_1.remove(directoryPath, function (err) {
if (err) {
return reject(err);
}
return resolve();
});
});
}
exports.rimRafAsync = rimRafAsync;
function copyFileAsync(srcPath, destPath) {
return new Promise(function (resolve, reject) {
var writeStream = fs_extra_1.createWriteStream(destPath);
writeStream.on('error', function (err) {
reject(err);
});
writeStream.on('close', function () {
resolve();
});
fs_extra_1.createReadStream(srcPath).pipe(writeStream);
});
}
exports.copyFileAsync = copyFileAsync;
function createFileObject(filePath) {
var content = fs_extra_1.readFileSync(filePath).toString();
return {
content: content,
path: filePath,
timestamp: Date.now()
};
}
exports.createFileObject = createFileObject;
function setContext(context) {
_context = context;
}
exports.setContext = setContext;
function getContext() {
return _context;
}
exports.getContext = getContext;
function transformSrcPathToTmpPath(originalPath, context) {
return originalPath.replace(context.srcDir, context.tmpDir);
}
exports.transformSrcPathToTmpPath = transformSrcPathToTmpPath;
function transformTmpPathToSrcPath(originalPath, context) {
return originalPath.replace(context.tmpDir, context.srcDir);
}
exports.transformTmpPathToSrcPath = transformTmpPathToSrcPath;
function changeExtension(filePath, newExtension) {
var dir = path_1.dirname(filePath);
var extension = path_1.extname(filePath);
var extensionlessfileName = path_1.basename(filePath, extension);
var newFileName = extensionlessfileName + newExtension;
return path_1.join(dir, newFileName);
}
exports.changeExtension = changeExtension;
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
exports.escapeHtml = escapeHtml;
function rangeReplace(source, startIndex, endIndex, newContent) {
return source.substring(0, startIndex) + newContent + source.substring(endIndex);
}
exports.rangeReplace = rangeReplace;
function stringSplice(source, startIndex, numToDelete, newContent) {
return source.slice(0, startIndex) + newContent + source.slice(startIndex + Math.abs(numToDelete));
}
exports.stringSplice = stringSplice;
function toUnixPath(filePath) {
return filePath.replace(/\\/g, '/');
}
exports.toUnixPath = toUnixPath;
| kfrerichs/roleplay | node_modules/@ionic/app-scripts/dist/util/helpers.js | JavaScript | gpl-3.0 | 6,661 |
/*
Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments
Copyright (C) ITsysCOM GmbH
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 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 migrator
import (
"fmt"
"strings"
"time"
"github.com/cgrates/cgrates/engine"
"github.com/cgrates/cgrates/utils"
)
type v1ActionTrigger struct {
Id string // for visual identification
ThresholdType string //*min_counter, *max_counter, *min_balance, *max_balance
ThresholdValue float64
Recurrent bool // reset eexcuted flag each run
MinSleep time.Duration // Minimum duration between two executions in case of recurrent triggers
BalanceId string
BalanceType string
BalanceDirection string
BalanceDestinationIds string // filter for balance
BalanceWeight float64 // filter for balance
BalanceExpirationDate time.Time // filter for balance
BalanceTimingTags string // filter for balance
BalanceRatingSubject string // filter for balance
BalanceCategory string // filter for balance
BalanceSharedGroup string // filter for balance
Weight float64
ActionsId string
MinQueuedItems int // Trigger actions only if this number is hit (stats only)
Executed bool
lastExecutionTime time.Time
}
type v1ActionTriggers []*v1ActionTrigger
func (m *Migrator) migrateCurrentActionTrigger() (err error) {
var ids []string
ids, err = m.dmIN.DataDB().GetKeysForPrefix(utils.ACTION_TRIGGER_PREFIX)
if err != nil {
return err
}
for _, id := range ids {
idg := strings.TrimPrefix(id, utils.ACTION_TRIGGER_PREFIX)
acts, err := m.dmIN.GetActionTriggers(idg, true, utils.NonTransactional)
if err != nil {
return err
}
if acts != nil {
if m.dryRun != true {
if err := m.dmOut.SetActionTriggers(idg, acts, utils.NonTransactional); err != nil {
return err
}
}
}
}
return
}
func (m *Migrator) migrateV1ActionTrigger() (err error) {
var v1ACTs *v1ActionTriggers
var acts engine.ActionTriggers
for {
v1ACTs, err = m.oldDataDB.getV1ActionTriggers()
if err != nil && err != utils.ErrNoMoreData {
return err
}
if err == utils.ErrNoMoreData {
break
}
if *v1ACTs != nil {
for _, v1ac := range *v1ACTs {
act := v1ac.AsActionTrigger()
acts = append(acts, act)
}
if !m.dryRun {
if err := m.dmOut.SetActionTriggers(acts[0].ID, acts, utils.NonTransactional); err != nil {
return err
}
m.stats[utils.ActionTriggers] += 1
}
}
}
if !m.dryRun {
// All done, update version wtih current one
vrs := engine.Versions{utils.ActionTriggers: engine.CurrentDataDBVersions()[utils.ActionTriggers]}
if err = m.dmOut.DataDB().SetVersions(vrs, false); err != nil {
return utils.NewCGRError(utils.Migrator,
utils.ServerErrorCaps,
err.Error(),
fmt.Sprintf("error: <%s> when updating ActionTriggers version into DataDB", err.Error()))
}
}
return
}
func (m *Migrator) migrateActionTriggers() (err error) {
var vrs engine.Versions
current := engine.CurrentDataDBVersions()
vrs, err = m.dmOut.DataDB().GetVersions(utils.TBLVersions)
if err != nil {
return utils.NewCGRError(utils.Migrator,
utils.ServerErrorCaps,
err.Error(),
fmt.Sprintf("error: <%s> when querying oldDataDB for versions", err.Error()))
} else if len(vrs) == 0 {
return utils.NewCGRError(utils.Migrator,
utils.MandatoryIEMissingCaps,
utils.UndefinedVersion,
"version number is not defined for ActionTriggers model")
}
switch vrs[utils.ActionTriggers] {
case current[utils.ActionTriggers]:
if m.sameDataDB {
return
}
if err := m.migrateCurrentActionTrigger(); err != nil {
return err
}
return
case 1:
if err := m.migrateV1ActionTrigger(); err != nil {
return err
}
}
return
}
func (v1Act v1ActionTrigger) AsActionTrigger() (at *engine.ActionTrigger) {
at = &engine.ActionTrigger{
ID: v1Act.Id,
ThresholdType: v1Act.ThresholdType,
ThresholdValue: v1Act.ThresholdValue,
Recurrent: v1Act.Recurrent,
MinSleep: v1Act.MinSleep,
Weight: v1Act.Weight,
ActionsID: v1Act.ActionsId,
MinQueuedItems: v1Act.MinQueuedItems,
Executed: v1Act.Executed,
}
bf := &engine.BalanceFilter{}
if v1Act.BalanceId != "" {
bf.ID = utils.StringPointer(v1Act.BalanceId)
}
if v1Act.BalanceType != "" {
bf.Type = utils.StringPointer(v1Act.BalanceType)
}
if v1Act.BalanceRatingSubject != "" {
bf.RatingSubject = utils.StringPointer(v1Act.BalanceRatingSubject)
}
if v1Act.BalanceDirection != "" {
bf.Directions = utils.StringMapPointer(utils.ParseStringMap(v1Act.BalanceDirection))
}
if v1Act.BalanceDestinationIds != "" {
bf.DestinationIDs = utils.StringMapPointer(utils.ParseStringMap(v1Act.BalanceDestinationIds))
}
if v1Act.BalanceTimingTags != "" {
bf.TimingIDs = utils.StringMapPointer(utils.ParseStringMap(v1Act.BalanceTimingTags))
}
if v1Act.BalanceCategory != "" {
bf.Categories = utils.StringMapPointer(utils.ParseStringMap(v1Act.BalanceCategory))
}
if v1Act.BalanceSharedGroup != "" {
bf.SharedGroups = utils.StringMapPointer(utils.ParseStringMap(v1Act.BalanceSharedGroup))
}
if v1Act.BalanceWeight != 0 {
bf.Weight = utils.Float64Pointer(v1Act.BalanceWeight)
}
if !v1Act.BalanceExpirationDate.IsZero() {
bf.ExpirationDate = utils.TimePointer(v1Act.BalanceExpirationDate)
at.ExpirationDate = v1Act.BalanceExpirationDate
at.LastExecutionTime = v1Act.BalanceExpirationDate
at.ActivationDate = v1Act.BalanceExpirationDate
}
at.Balance = bf
if at.ThresholdType == "*min_counter" ||
at.ThresholdType == "*max_counter" {
at.ThresholdType = strings.Replace(at.ThresholdType, "_", "_event_", 1)
}
return
}
| Edwardro22/cgrates | migrator/action_trigger.go | GO | gpl-3.0 | 6,331 |
/*******************************************************************************
* Copyright (c) 2011-2014 SirSengir.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Various Contributors including, but not limited to:
* SirSengir (original work), CovertJaguar, Player, Binnie, MysteriousAges
******************************************************************************/
package forestry.lepidopterology.entities;
import forestry.lepidopterology.entities.EntityButterfly.EnumButterflyState;
public class AIButterflyRise extends AIButterflyMovement {
public AIButterflyRise(EntityButterfly entity) {
super(entity);
setMutexBits(1);
}
@Override
public boolean shouldExecute() {
if (entity.getDestination() != null) {
return false;
}
if (!entity.isCollidedHorizontally && entity.getRNG().nextInt(64) != 0) {
return false;
}
flightTarget = getRandomDestinationUpwards();
if (flightTarget == null) {
if (entity.getState().doesMovement) {
entity.setState(EnumButterflyState.HOVER);
}
return false;
}
entity.setDestination(flightTarget);
entity.setState(EnumButterflyState.RISING);
return true;
}
@Override
public boolean continueExecuting() {
if (entity.getState() != EntityButterfly.EnumButterflyState.RISING) {
return false;
}
if (flightTarget == null) {
return false;
}
// Abort if the flight target changed on us.
if (entity.getDestination() == null || !entity.getDestination().equals(flightTarget)) {
return false;
}
// Continue if we have not yet reached the destination.
if (entity.getDestination().getDistanceSquared((int) entity.posX, (int) entity.posY, (int) entity.posZ) > 2.0f) {
return true;
}
entity.setDestination(null);
return false;
}
@Override
public void updateTask() {
if (entity.isInWater()) {
flightTarget = getRandomDestinationUpwards();
} else if (entity.isCollidedVertically && entity.getRNG().nextInt(62) == 0) {
flightTarget = null;
}
entity.setDestination(flightTarget);
entity.changeExhaustion(1);
}
}
| AnodeCathode/ForestryMC | src/main/java/forestry/lepidopterology/entities/AIButterflyRise.java | Java | gpl-3.0 | 2,251 |
/*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. All rights
* reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
namespace PingPong
{
public class ping
{
public static void Main (String[] args)
{
pinger pinger_instance = new pinger();
pinger_instance.run (args);
}
}
}
| PrismTech/opensplice | examples/dcps/PingPong/cs/src/ping.cs | C# | gpl-3.0 | 1,045 |
<?php
/* Copyright (C) 2005 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2005-2009 Regis Houssin <regis.houssin@capnetworks.com>
*
* 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 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/>.
* or see http://www.gnu.org/
*/
/**
* \file htdocs/core/modules/mailings/fraise.modules.php
* \ingroup mailing
* \brief File of class to generate target according to rule Fraise
*/
include_once DOL_DOCUMENT_ROOT.'/core/modules/mailings/modules_mailings.php';
include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
/**
* \class mailing_fraise
* \brief Class to generate target according to rule Fraise
*/
class mailing_fraise extends MailingTargets
{
// CHANGE THIS: Put here a name not already used
var $name='FundationMembers'; // Identifiant du module mailing
// CHANGE THIS: Put here a description of your selector module.
// This label is used if no translation found for key MailingModuleDescXXX where XXX=name is found
var $desc='Foundation members with emails (by status)';
// CHANGE THIS: Set to 1 if selector is available for admin users only
var $require_admin=0;
var $require_module=array('adherent');
var $picto='user';
var $db;
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
function __construct($db = '')
{
$this->db=$db;
}
/**
* On the main mailing area, there is a box with statistics.
* If you want to add a line in this report you must provide an
* array of SQL request that returns two field:
* One called "label", One called "nb".
*
* @return array Array with SQL requests
*/
function getSqlArrayForStats()
{
global $langs;
$langs->load("members");
// Array for requests for statistics board
$statssql=array();
$statssql[0] ="SELECT '".$this->db->escape($langs->trans("FundationMembers"))."' as label, count(*) as nb";
$statssql[0].=" FROM ".MAIN_DB_PREFIX."adherent where statut = 1";
return $statssql;
}
/*
* \brief Return here number of distinct emails returned by your selector.
* For example if this selector is used to extract 500 different
* emails from a text file, this function must return 500.
* \return int
*/
function getNbOfRecipients()
{
$sql = "SELECT count(distinct(a.email)) as nb";
$sql .= " FROM ".MAIN_DB_PREFIX."adherent as a";
$sql .= " WHERE (a.email IS NOT NULL AND a.email != '')";
// La requete doit retourner un champ "nb" pour etre comprise
// par parent::getNbOfRecipients
return parent::getNbOfRecipients($sql);
}
/**
* Affiche formulaire de filtre qui apparait dans page de selection des destinataires de mailings
*
* @return string Retourne zone select
*/
function formFilter()
{
global $langs;
$langs->load("members");
$form=new Form($this->db);
$s='';
$s.=$langs->trans("Status").': ';
$s.='<select name="filter" class="flat">';
$s.='<option value="none"> </option>';
$s.='<option value="-1">'.$langs->trans("MemberStatusDraft").'</option>';
$s.='<option value="1a">'.$langs->trans("MemberStatusActiveShort").' ('.$langs->trans("MemberStatusPaidShort").')</option>';
$s.='<option value="1b">'.$langs->trans("MemberStatusActiveShort").' ('.$langs->trans("MemberStatusActiveLateShort").')</option>';
$s.='<option value="0">'.$langs->trans("MemberStatusResiliatedShort").'</option>';
$s.='</select>';
$s.='<br>';
$s.=$langs->trans("DateEndSubscription").': ';
$s.=$langs->trans("After").' > '.$form->select_date(-1,'subscriptionafter',0,0,1,'fraise',1,0,1,0);
$s.=' ';
$s.=$langs->trans("Before").' < '.$form->select_date(-1,'subscriptionbefore',0,0,1,'fraise',1,0,1,0);
return $s;
}
/**
* Renvoie url lien vers fiche de la source du destinataire du mailing
*
* @param int $id ID
* @return string Url lien
*/
function url($id)
{
return '<a href="'.DOL_URL_ROOT.'/adherents/fiche.php?rowid='.$id.'">'.img_object('',"user").'</a>';
}
/**
* Ajoute destinataires dans table des cibles
*
* @param int $mailing_id Id of emailing
* @param array $filtersarray Param to filter sql request. Deprecated. Should use $_POST instead.
* @return int < 0 si erreur, nb ajout si ok
*/
function add_to_target($mailing_id,$filtersarray=array())
{
global $langs,$_POST;
$langs->load("members");
$langs->load("companies");
$cibles = array();
$now=dol_now();
$dateendsubscriptionafter=dol_mktime($_POST['subscriptionafterhour'],$_POST['subscriptionaftermin'],$_POST['subscriptionaftersec'],$_POST['subscriptionaftermonth'],$_POST['subscriptionafterday'],$_POST['subscriptionafteryear']);
$dateendsubscriptionbefore=dol_mktime($_POST['subscriptionbeforehour'],$_POST['subscriptionbeforemin'],$_POST['subscriptionbeforesec'],$_POST['subscriptionbeforemonth'],$_POST['subscriptionbeforeday'],$_POST['subscriptionbeforeyear']);
// La requete doit retourner: id, email, fk_contact, name, firstname
$sql = "SELECT a.rowid as id, a.email as email, null as fk_contact, ";
$sql.= " a.nom as name, a.prenom as firstname,";
$sql.= " a.datefin, a.civilite, a.login, a.societe"; // Other fields
$sql.= " FROM ".MAIN_DB_PREFIX."adherent as a";
$sql.= " WHERE a.email IS NOT NULL";
if (isset($_POST["filter"]) && $_POST["filter"] == '-1') $sql.= " AND a.statut=-1";
if (isset($_POST["filter"]) && $_POST["filter"] == '1a') $sql.= " AND a.statut=1 AND a.datefin >= '".$this->db->idate($now)."'";
if (isset($_POST["filter"]) && $_POST["filter"] == '1b') $sql.= " AND a.statut=1 AND (a.datefin IS NULL or a.datefin < '".$this->db->idate($now)."')";
if (isset($_POST["filter"]) && $_POST["filter"] == '0') $sql.= " AND a.statut=0";
if ($dateendsubscriptionafter > 0) $sql.=" AND datefin > '".$this->db->idate($dateendsubscriptionafter)."'";
if ($dateendsubscriptionbefore > 0) $sql.=" AND datefin < '".$this->db->idate($dateendsubscriptionbefore)."'";
$sql.= " ORDER BY a.email";
//print $sql;
// Add targets into table
dol_syslog(get_class($this)."::add_to_target sql=".$sql);
$result=$this->db->query($sql);
if ($result)
{
$num = $this->db->num_rows($result);
$i = 0;
$j = 0;
dol_syslog(get_class($this)."::add_to_target mailing ".$num." targets found");
$old = '';
while ($i < $num)
{
$obj = $this->db->fetch_object($result);
if ($old <> $obj->email)
{
$cibles[$j] = array(
'email' => $obj->email,
'fk_contact' => $obj->fk_contact,
'name' => $obj->name,
'firstname' => $obj->firstname,
'other' =>
($langs->transnoentities("Login").'='.$obj->login).';'.
($langs->transnoentities("UserTitle").'='.($obj->civilite?$langs->transnoentities("Civility".$obj->civilite):'')).';'.
($langs->transnoentities("DateEnd").'='.dol_print_date($this->db->jdate($obj->datefin),'day')).';'.
($langs->transnoentities("Company").'='.$obj->societe),
'source_url' => $this->url($obj->id),
'source_id' => $obj->id,
'source_type' => 'member'
);
$old = $obj->email;
$j++;
}
$i++;
}
}
else
{
dol_syslog($this->db->error());
$this->error=$this->db->error();
return -1;
}
return parent::add_to_target($mailing_id, $cibles);
}
}
?>
| woakes070048/crm-php | htdocs/core/modules/mailings/fraise.modules.php | PHP | gpl-3.0 | 8,880 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: ClearCanvas.Common.Plugin]
// 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("ClearCanvas.HL7")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ClearCanvas.HL7")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[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("afc6d1e3-d76d-4a52-8ae7-56e9550ae9a3")]
// 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")]
| mayioit/MacroMedicalSystem | HL7/Properties/AssemblyInfo.cs | C# | gpl-3.0 | 1,464 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="es" sourcelanguage="en">
<context>
<name>ConnectionManager</name>
<message>
<source>Connection Manager</source>
<translation>Gestor de conexión</translation>
</message>
<message>
<source>Allows to use different types of connections to a Jabber server</source>
<translation>Permite usar diferentes tipos de conexiones a un servidor Jabber</translation>
</message>
<message>
<source><No Proxy></source>
<translation><Sin proxy></translation>
</message>
<message>
<source>New Proxy</source>
<translation>Nuevo proxy</translation>
</message>
<message>
<source>Connection error</source>
<translation>Error de conexión</translation>
</message>
<message>
<source>Name: %1</source>
<translation>Nombre: %1</translation>
</message>
<message>
<source>Organization: %1</source>
<translation>Organización: %1</translation>
</message>
<message>
<source>Subunit: %1</source>
<translation>Subdivisión: %1</translation>
</message>
<message>
<source>Country: %1</source>
<translation>País: %1</translation>
</message>
<message>
<source>Locality: %1</source>
<translation>Ubicación: %1</translation>
</message>
<message>
<source>State/Province: %1</source>
<translation>Estado/Provincia: %1</translation>
</message>
<message>
<source><b>Certificate holder:</b></source>
<translation><b>Certificado expedido:</b></translation>
</message>
<message>
<source><b>Certificate issuer:</b></source>
<translation><b>Certificado emitido:</b></translation>
</message>
<message>
<source><b>Certificate details:</b></source>
<translation><b>Detalles del certificado:</b></translation>
</message>
<message>
<source>Effective from: %1</source>
<translation>Válido desde: %1</translation>
</message>
<message>
<source>Expired at: %1</source>
<translation>Válido hasta: %1</translation>
</message>
<message>
<source>Serial number: %1</source>
<translation>Número de serie: %1</translation>
</message>
</context>
<context>
<name>ConnectionOptionsWidgetClass</name>
<message>
<source>Connection</source>
<translation>Conexión</translation>
</message>
<message>
<source>Connection:</source>
<translation>Conexión:</translation>
</message>
</context>
<context>
<name>EditProxyDialog</name>
<message>
<source>HTTP Proxy</source>
<translation>Proxy HTTP</translation>
</message>
<message>
<source>Socks5 Proxy</source>
<translation>Proxy Socks5</translation>
</message>
<message>
<source>New Proxy</source>
<translation>Nuevo proxy</translation>
</message>
</context>
<context>
<name>EditProxyDialogClass</name>
<message>
<source>Proxy Manager</source>
<translation>Gestor de proxy</translation>
</message>
<message>
<source>Name:</source>
<translation>Nombre:</translation>
</message>
<message>
<source>Type:</source>
<translation>Tipo:</translation>
</message>
<message>
<source>Host:</source>
<translation>Host:</translation>
</message>
<message>
<source>Port:</source>
<translation>Puerto:</translation>
</message>
<message>
<source>User:</source>
<translation>Usuario:</translation>
</message>
<message>
<source>Password:</source>
<translation>Contraseña:</translation>
</message>
<message>
<source>Add</source>
<translation>Añadir</translation>
</message>
<message>
<source>Delete</source>
<translation>Eliminar</translation>
</message>
</context>
<context>
<name>ProxySettingsWidget</name>
<message>
<source><Default Proxy></source>
<translation><Proxy por defecto></translation>
</message>
<message>
<source>Default proxy:</source>
<translation>Proxy por defecto:</translation>
</message>
</context>
<context>
<name>ProxySettingsWidgetClass</name>
<message>
<source>Proxy:</source>
<translation>Proxy:</translation>
</message>
<message>
<source>Edit</source>
<translation>Editar</translation>
</message>
</context>
</TS>
| sanchay160887/vacuum-im | src/translations/es/connectionmanager.ts | TypeScript | gpl-3.0 | 4,742 |
package com.totsp.crossword.io.versions;
import com.totsp.crossword.io.IO;
import com.totsp.crossword.puz.Box;
import com.totsp.crossword.puz.Puzzle;
import com.totsp.crossword.puz.PuzzleMeta;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Date;
public class IOVersion1 implements IOVersion {
public void read(Puzzle puz, DataInputStream dis) throws IOException {
PuzzleMeta meta = readMeta(dis);
applyMeta(puz, meta);
Box[][] boxes = puz.getBoxes();
for(Box[] row : boxes ){
for(Box b : row){
if(b == null){
continue;
}
b.setCheated(dis.readBoolean());
b.setResponder(IO.readNullTerminatedString(dis));
}
}
try{
puz.setTime(dis.readLong());
}catch(IOException ioe){
ioe.printStackTrace();
}
}
protected void applyMeta(Puzzle puz, PuzzleMeta meta){
//System.out.println("Applying V1 Meta");
puz.setSource(meta.source);
puz.setDate(meta.date);
}
public PuzzleMeta readMeta(DataInputStream dis) throws IOException {
//System.out.println("Read V1");
PuzzleMeta meta = new PuzzleMeta();
meta.author = IO.readNullTerminatedString(dis);
meta.source = IO.readNullTerminatedString(dis);
meta.title = IO.readNullTerminatedString(dis);
meta.date = new Date( dis.readLong() );
meta.percentComplete = dis.readInt();
return meta;
}
public void write(Puzzle puz, DataOutputStream dos) throws IOException {
IO.writeNullTerminatedString(dos, puz.getAuthor());
IO.writeNullTerminatedString(dos, puz.getSource());
IO.writeNullTerminatedString(dos, puz.getTitle());
dos.writeLong(puz.getDate() == null ? 0 : puz.getDate().getTime());
dos.writeInt(puz.getPercentComplete());
//System.out.println("Meta written.");
Box[][] boxes = puz.getBoxes();
for(Box[] row : boxes ){
for(Box b : row){
if(b == null){
continue;
}
dos.writeBoolean(b.isCheated());
IO.writeNullTerminatedString(dos, b.getResponder());
}
}
dos.writeLong(puz.getTime());
}
}
| rappazzo/shortyz | puzlib/src/main/java/com/totsp/crossword/io/versions/IOVersion1.java | Java | gpl-3.0 | 2,029 |
// Copyright (c) 2005 - 2017 Settlers Freaks (sf-team at siedler25.org)
//
// This file is part of Return To The Roots.
//
// Return To The Roots 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.
//
// Return To The Roots 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 Return To The Roots. If not, see <http://www.gnu.org/licenses/>.
#include "rttrDefines.h" // IWYU pragma: keep
#include "FileChecksum.h"
#include <boost/nowide/fstream.hpp>
uint32_t CalcChecksumOfFile(const std::string& path)
{
bnw::ifstream file(path);
if(!file)
return 0;
uint32_t checksum = 0;
for(std::istreambuf_iterator<char> it(file), e; it != e; ++it)
checksum += static_cast<uint8_t>(*it);
return checksum;
}
uint32_t CalcChecksumOfBuffer(const uint8_t* buffer, size_t size)
{
if(!buffer || size == 0)
return 0;
uint32_t checksum = 0;
for(unsigned i = 0; i < size; ++i)
checksum += buffer[i];
return checksum;
}
| stefson/s25client | libs/s25main/FileChecksum.cpp | C++ | gpl-3.0 | 1,418 |
// Type definitions for iview 3.1.0
// Project: https://github.com/iview/iview
// Definitions by: yangdan
// Definitions: https://github.com/yangdan8/iview.git
import Vue, { VNode } from 'vue';
export declare interface Anchor extends Vue {
/**
* 固定模式
* @default true
*/
affix?: boolean;
/**
* 距离窗口顶部达到指定偏移量后触发
* @default 0
*/
'offset-top'?: number;
/**
* 距离窗口底部达到指定偏移量后触发
*/
'offset-bottom'?: number;
/**
* 锚点区域边界,单位:px
* @default 5
*/
bounds?: number;
/**
* 点击滚动的额外距离
* @default 0
*/
'scroll-offset'?: number;
/**
* 指定滚动的容器
*/
container?: string | HTMLElement;
/**
* 是否显示小圆点
* @default false
*/
'show-ink'?: boolean;
/**
* 点击锚点时触发,返回链接
*/
$emit(eventName: 'on-select', href: string): this;
/**
* 链接改变时触发,返回新链接和旧链接
*/
$emit(eventName: 'on-change', []): this;
}
export declare interface AnchorLink extends Vue {
/**
* 锚点链接
* @default
*/
href?: string;
/**
* 文字内容
* @default
*/
title?: string;
/**
* 点击滚动的额外距离
* @default 0
*/
'scroll-offset'?: number;
} | cmos3511/cmos_linux | python/op/op_site/op_static/npm/node_modules/iview/types/anchor.d.ts | TypeScript | gpl-3.0 | 1,330 |
<?php
/**
* LICENSE: The MIT License (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* https://github.com/azure/azure-storage-php/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* PHP version 5
*
* @category Microsoft
* @package MicrosoftAzure\Storage\Tests\Unit\Table\Models
* @author Azure Storage PHP SDK <dmsh@microsoft.com>
* @copyright 2016 Microsoft Corporation
* @license https://github.com/azure/azure-storage-php/LICENSE
* @link https://github.com/azure/azure-storage-php
*/
namespace MicrosoftAzure\Storage\Tests\Unit\Table\Models;
use MicrosoftAzure\Storage\Table\Models\QueryEntitiesResult;
/**
* Unit tests for class QueryEntitiesResult
*
* @category Microsoft
* @package MicrosoftAzure\Storage\Tests\Unit\Table\Models
* @author Azure Storage PHP SDK <dmsh@microsoft.com>
* @copyright 2016 Microsoft Corporation
* @license https://github.com/azure/azure-storage-php/LICENSE
* @version Release: 0.10.1
* @link https://github.com/azure/azure-storage-php
*/
class QueryEntitiesResultTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers MicrosoftAzure\Storage\Table\Models\QueryEntitiesResult::create
*/
public function testCreate()
{
// Test
$result = QueryEntitiesResult::create(array(), array());
// Assert
$this->assertCount(0, $result->getEntities());
$this->assertNull($result->getNextPartitionKey());
$this->assertNull($result->getNextRowKey());
}
/**
* @covers MicrosoftAzure\Storage\Table\Models\QueryEntitiesResult::setNextPartitionKey
* @covers MicrosoftAzure\Storage\Table\Models\QueryEntitiesResult::getNextPartitionKey
*/
public function testSetNextPartitionKey()
{
// Setup
$result = new QueryEntitiesResult();
$expected = 'parition';
// Test
$result->setNextPartitionKey($expected);
// Assert
$this->assertEquals($expected, $result->getNextPartitionKey());
}
/**
* @covers MicrosoftAzure\Storage\Table\Models\QueryEntitiesResult::setNextRowKey
* @covers MicrosoftAzure\Storage\Table\Models\QueryEntitiesResult::getNextRowKey
*/
public function testSetNextRowKey()
{
// Setup
$result = new QueryEntitiesResult();
$expected = 'edelo';
// Test
$result->setNextRowKey($expected);
// Assert
$this->assertEquals($expected, $result->getNextRowKey());
}
/**
* @covers MicrosoftAzure\Storage\Table\Models\QueryEntitiesResult::setEntities
* @covers MicrosoftAzure\Storage\Table\Models\QueryEntitiesResult::getEntities
*/
public function testSetEntities()
{
// Setup
$result = new QueryEntitiesResult();
$expected = array();
// Test
$result->setEntities($expected);
// Assert
$this->assertEquals($expected, $result->getEntities());
}
}
| segej87/ecomapper | DataEntry/server_side/ecomapper-backend/vendor/microsoft/azure-storage/tests/unit/Table/Models/QueryEntitiesResultTest.php | PHP | gpl-3.0 | 3,388 |
/*
* Copyright (c) The Shogun Machine Learning Toolbox
* Written (W) 2015 Wu Lin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Shogun Development Team.
*
*/
#include <shogun/machine/gp/SingleSparseInference.h>
#ifdef USE_GPL_SHOGUN
#ifdef HAVE_NLOPT
#include <shogun/optimization/NLOPTMinimizer.h>
#endif //HAVE_NLOPT
#endif //USE_GPL_SHOGUN
#include <shogun/mathematics/Math.h>
#include <shogun/mathematics/eigen3.h>
#include <shogun/features/DotFeatures.h>
#include <shogun/optimization/FirstOrderBoundConstraintsCostFunction.h>
using namespace shogun;
using namespace Eigen;
namespace shogun
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/** Wrapped cost function used for the NLOPT minimizer */
class SingleSparseInferenceCostFunction: public FirstOrderBoundConstraintsCostFunction
{
public:
SingleSparseInferenceCostFunction():FirstOrderBoundConstraintsCostFunction() { init(); }
virtual ~SingleSparseInferenceCostFunction() { SG_UNREF(m_obj); }
virtual const char* get_name() const { return "SingleSparseInferenceCostFunction"; }
void set_target(CSingleSparseInference *obj)
{
REQUIRE(obj,"Object not set\n");
if(obj!=m_obj)
{
SG_REF(obj);
SG_UNREF(m_obj);
m_obj=obj;
m_obj->check_fully_sparse();
REQUIRE(m_obj->m_fully_sparse,"Can not compute gradient\n");
}
}
void unset_target(bool is_unref)
{
if(is_unref)
{
SG_UNREF(m_obj);
}
m_obj=NULL;
}
virtual float64_t get_cost()
{
REQUIRE(m_obj,"Object not set\n");
float64_t nlz=m_obj->get_negative_log_marginal_likelihood();
return nlz;
}
virtual SGVector<float64_t> obtain_variable_reference()
{
REQUIRE(m_obj,"Object not set\n");
SGMatrix<float64_t>& lat_m=m_obj->m_inducing_features;
SGVector<float64_t> x(lat_m.matrix,lat_m.num_rows*lat_m.num_cols,false);
return x;
}
virtual SGVector<float64_t> get_gradient()
{
REQUIRE(m_obj,"Object not set\n");
m_obj->compute_gradient();
TParameter* param=m_obj->m_gradient_parameters->get_parameter("inducing_features");
SGVector<float64_t> derivatives=m_obj->get_derivative_wrt_inducing_features(param);
return derivatives;
}
virtual SGVector<float64_t> get_lower_bound()
{
REQUIRE(m_obj,"Object not set\n");
return m_obj->m_lower_bound;
}
virtual SGVector<float64_t> get_upper_bound()
{
REQUIRE(m_obj,"Object not set\n");
return m_obj->m_upper_bound;
}
private:
CSingleSparseInference *m_obj;
void init()
{
m_obj=NULL;
//The existing implementation in CSGObject::get_parameter_incremental_hash()
//can NOT deal with circular reference when parameter_hash_changed() is called
//SG_ADD((CSGObject **)&m_obj, "CSigleSparseInference__m_obj",
//"m_obj in SingleSparseInferenceCostFunction", MS_NOT_AVAILABLE);
}
};
#endif //DOXYGEN_SHOULD_SKIP_THIS
CSingleSparseInference::CSingleSparseInference() : CSparseInference()
{
init();
}
CSingleSparseInference::CSingleSparseInference(CKernel* kern, CFeatures* feat,
CMeanFunction* m, CLabels* lab, CLikelihoodModel* mod, CFeatures* lat)
: CSparseInference(kern, feat, m, lab, mod, lat)
{
init();
check_fully_sparse();
}
void CSingleSparseInference::init()
{
m_fully_sparse=false;
m_inducing_minimizer=NULL;
SG_ADD(&m_fully_sparse, "fully_Sparse",
"whether the kernel support sparse inference", MS_NOT_AVAILABLE);
m_lock=new CLock();
SG_ADD(&m_upper_bound, "upper_bound",
"upper bound of inducing features", MS_NOT_AVAILABLE);
SG_ADD(&m_lower_bound, "lower_bound",
"lower bound of inducing features", MS_NOT_AVAILABLE);
SG_ADD(&m_max_ind_iterations, "max_ind_iterations",
"max number of iterations used in inducing features optimization", MS_NOT_AVAILABLE);
SG_ADD(&m_ind_tolerance, "ind_tolerance",
"tolearance used in inducing features optimization", MS_NOT_AVAILABLE);
SG_ADD(&m_opt_inducing_features,
"opt_inducing_features", "whether optimize inducing features", MS_NOT_AVAILABLE);
SG_ADD((CSGObject **)&m_inducing_minimizer,
"inducing_minimizer", "Minimizer used in optimize inducing features", MS_NOT_AVAILABLE);
m_max_ind_iterations=50;
m_ind_tolerance=1e-3;
m_opt_inducing_features=false;
m_lower_bound=SGVector<float64_t>();
m_upper_bound=SGVector<float64_t>();
}
void CSingleSparseInference::set_kernel(CKernel* kern)
{
CInference::set_kernel(kern);
check_fully_sparse();
}
CSingleSparseInference::~CSingleSparseInference()
{
SG_UNREF(m_inducing_minimizer);
delete m_lock;
}
void CSingleSparseInference::check_fully_sparse()
{
REQUIRE(m_kernel, "Kernel must be set first\n")
if (strstr(m_kernel->get_name(), "SparseKernel")!=NULL)
m_fully_sparse=true;
else
{
SG_WARNING( "The provided kernel does not support to optimize inducing features\n");
m_fully_sparse=false;
}
}
SGVector<float64_t> CSingleSparseInference::get_derivative_wrt_inference_method(
const TParameter* param)
{
// the time complexity O(m^2*n) if the TO DO is done
REQUIRE(param, "Param not set\n");
REQUIRE(!(strcmp(param->m_name, "log_scale")
&& strcmp(param->m_name, "log_inducing_noise")
&& strcmp(param->m_name, "inducing_features")),
"Can't compute derivative of"
" the nagative log marginal likelihood wrt %s.%s parameter\n",
get_name(), param->m_name)
if (!strcmp(param->m_name, "log_inducing_noise"))
// wrt inducing_noise
// compute derivative wrt inducing noise
return get_derivative_wrt_inducing_noise(param);
else if (!strcmp(param->m_name, "inducing_features"))
{
SGVector<float64_t> res;
if (!m_fully_sparse)
{
int32_t dim=m_inducing_features.num_rows;
int32_t num_samples=m_inducing_features.num_cols;
res=SGVector<float64_t>(dim*num_samples);
SG_WARNING("Derivative wrt %s cannot be computed since the kernel does not support fully sparse inference\n",
param->m_name);
res.zero();
return res;
}
res=get_derivative_wrt_inducing_features(param);
return res;
}
// wrt scale
// clone kernel matrices
SGVector<float64_t> deriv_trtr=m_ktrtr_diag.clone();
SGMatrix<float64_t> deriv_uu=m_kuu.clone();
SGMatrix<float64_t> deriv_tru=m_ktru.clone();
// create eigen representation of kernel matrices
Map<VectorXd> ddiagKi(deriv_trtr.vector, deriv_trtr.vlen);
Map<MatrixXd> dKuui(deriv_uu.matrix, deriv_uu.num_rows, deriv_uu.num_cols);
Map<MatrixXd> dKui(deriv_tru.matrix, deriv_tru.num_rows, deriv_tru.num_cols);
// compute derivatives wrt scale for each kernel matrix
SGVector<float64_t> result(1);
result[0]=get_derivative_related_cov(deriv_trtr, deriv_uu, deriv_tru);
result[0]*=CMath::exp(m_log_scale*2.0)*2.0;
return result;
}
SGVector<float64_t> CSingleSparseInference::get_derivative_wrt_kernel(
const TParameter* param)
{
REQUIRE(param, "Param not set\n");
SGVector<float64_t> result;
int64_t len=const_cast<TParameter *>(param)->m_datatype.get_num_elements();
result=SGVector<float64_t>(len);
CFeatures *inducing_features=get_inducing_features();
for (index_t i=0; i<result.vlen; i++)
{
SGVector<float64_t> deriv_trtr;
SGMatrix<float64_t> deriv_uu;
SGMatrix<float64_t> deriv_tru;
m_lock->lock();
m_kernel->init(m_features, m_features);
//to reduce the time complexity
//the kernel object only computes diagonal elements of gradients wrt hyper-parameter
deriv_trtr=m_kernel->get_parameter_gradient_diagonal(param, i);
m_kernel->init(inducing_features, inducing_features);
deriv_uu=m_kernel->get_parameter_gradient(param, i);
m_kernel->init(inducing_features, m_features);
deriv_tru=m_kernel->get_parameter_gradient(param, i);
m_lock->unlock();
// create eigen representation of derivatives
Map<VectorXd> ddiagKi(deriv_trtr.vector, deriv_trtr.vlen);
Map<MatrixXd> dKuui(deriv_uu.matrix, deriv_uu.num_rows,
deriv_uu.num_cols);
Map<MatrixXd> dKui(deriv_tru.matrix, deriv_tru.num_rows,
deriv_tru.num_cols);
result[i]=get_derivative_related_cov(deriv_trtr, deriv_uu, deriv_tru);
result[i]*=CMath::exp(m_log_scale*2.0);
}
SG_UNREF(inducing_features);
return result;
}
void CSingleSparseInference::check_bound(SGVector<float64_t> bound, const char* name)
{
if (bound.vlen>1)
{
REQUIRE(m_inducing_features.num_rows>0, "Inducing features must set before this method is called\n");
REQUIRE(m_inducing_features.num_rows*m_inducing_features.num_cols==bound.vlen,
"The length of inducing features (%dx%d)",
" and the length of bound constraints (%d) are different\n",
m_inducing_features.num_rows,m_inducing_features.num_cols,bound.vlen);
}
else if(bound.vlen==1)
{
SG_WARNING("All inducing_features (%dx%d) are constrainted by the single value (%f) in the %s bound\n",
m_inducing_features.num_rows,m_inducing_features.num_cols,bound[0],name);
}
}
void CSingleSparseInference::set_lower_bound_of_inducing_features(SGVector<float64_t> bound)
{
check_bound(bound,"lower");
m_lower_bound=bound;
}
void CSingleSparseInference::set_upper_bound_of_inducing_features(SGVector<float64_t> bound)
{
check_bound(bound, "upper");
m_upper_bound=bound;
}
void CSingleSparseInference::set_max_iterations_for_inducing_features(int32_t it)
{
REQUIRE(it>0, "Iteration (%d) must be positive\n",it);
m_max_ind_iterations=it;
}
void CSingleSparseInference::set_tolearance_for_inducing_features(float64_t tol)
{
REQUIRE(tol>0, "Tolearance (%f) must be positive\n",tol);
m_ind_tolerance=tol;
}
void CSingleSparseInference::enable_optimizing_inducing_features(bool is_optmization, FirstOrderMinimizer* minimizer)
{
m_opt_inducing_features=is_optmization;
if (m_opt_inducing_features)
{
check_fully_sparse();
REQUIRE(m_fully_sparse,"Please use a kernel which has the functionality about optimizing inducing features\n");
}
if(minimizer)
{
if (minimizer!=m_inducing_minimizer)
{
SG_REF(minimizer);
SG_UNREF(m_inducing_minimizer);
m_inducing_minimizer=minimizer;
}
}
else
{
SG_UNREF(m_inducing_minimizer);
#ifdef USE_GPL_SHOGUN
#ifdef HAVE_NLOPT
m_inducing_minimizer=new CNLOPTMinimizer();
SG_REF(m_inducing_minimizer);
#else
m_inducing_minimizer=NULL;
SG_WARNING("We require NLOPT library for using default minimizer.\nYou can use other minimizer. (eg, LBFGSMinimier)\n");
#endif //HAVE_NLOPT
#else
m_inducing_minimizer=NULL;
SG_WARNING("We require NLOPT (GPL License) library for using default minimizer.\nYou can use other minimizer. (eg, LBFGSMinimier)");
#endif //USE_GPL_SHOGUN
}
}
void CSingleSparseInference::optimize_inducing_features()
{
if (!m_opt_inducing_features)
return;
REQUIRE(m_inducing_minimizer, "Please call enable_optimizing_inducing_features() first\n");
SingleSparseInferenceCostFunction *cost_fun=new SingleSparseInferenceCostFunction();
cost_fun->set_target(this);
bool cleanup=false;
if(this->ref_count()>1)
cleanup=true;
#ifdef USE_GPL_SHOGUN
#ifdef HAVE_NLOPT
CNLOPTMinimizer* opt=dynamic_cast<CNLOPTMinimizer*>(m_inducing_minimizer);
if (opt)
opt->set_nlopt_parameters(NLOPT_LD_LBFGS, m_max_ind_iterations, m_ind_tolerance, m_ind_tolerance);
#endif //HAVE_NLOPT
#endif //USE_GPL_SHOGUN
m_inducing_minimizer->set_cost_function(cost_fun);
m_inducing_minimizer->minimize();
m_inducing_minimizer->unset_cost_function(false);
cost_fun->unset_target(cleanup);
SG_UNREF(cost_fun);
}
}
| sanuj/shogun | src/shogun/machine/gp/SingleSparseInference.cpp | C++ | gpl-3.0 | 12,679 |
'use strict';
var resolveBranch = require('resolve-git-branch')
, resolveRemote = require('resolve-git-remote')
, asyncreduce = require('asyncreduce')
, cheerio = require('cheerio')
function overrideWithEnvVars(ghinfo) {
// could be optimized if both are given since then we don't need to obtain github info
var env = process.env;
ghinfo.remote = env.JSDOC_GITHUBIFY_REMOTE || ghinfo.remote;
ghinfo.branch = env.JSDOC_GITHUBIFY_BRANCH || ghinfo.branch;
}
function githubInfo(cb) {
asyncreduce(
[ [ 'remote', resolveRemote ], [ 'branch', resolveBranch ] ]
, {}
, function (acc, tuple, cb_) {
tuple[1](function (err, res) {
if (err) return cb_(err);
acc[tuple[0]] = res;
cb_(null, acc);
});
}
, function (err, res) {
if (err) return cb(err);
overrideWithEnvVars(res);
res.blobRoot = 'https://github.com/' + res.remote + '/blob/' + res.branch;
cb(null, res);
}
);
}
function getDom(html) {
// all jsdoc pages should have a <div id="main"> and we only care about its children
var dom = cheerio('<wrap>' + html + '</wrap>')
var main = dom.find('div#main');
if (main.length) return main;
// however if that is not found we'll grab the entire body
var body = dom.find('body');
if (body.length) return body;
// and if we don't even have a body we'll take it all
return dom;
}
function adaptLinks(dom, blobRoot) {
dom.find('.tag-source li')
.map(function (idx, x) {
if (x.children && x.children[0] && x.children[0].data) {
var parts = x.children[0].data.split(',');
if (parts.length < 2) return null;
return { li: cheerio(x), file: parts[0].trim(), lineno: parts[1].replace(/line/, '').trim() };
}
})
.filter(function (x) { return x })
.forEach(function (x) {
var fileUrl = blobRoot + '/' + x.file;
x.li.replaceWith(
'\n<li>\n' +
'<a href="' + fileUrl + '">' + x.file + '</a>\n' +
'<span>, </span>\n' +
'<a href="' + fileUrl + '#L' + x.lineno + '">lineno ' + x.lineno + '</a>\n' +
'</li>\n'
)
})
}
/**
* Adapts the given html to be used on github via the following steps:
*
* - redirect all code sample links to gihub repo blob
* - wrap in div.jsdoc-githubify for styling
*
* @name adaptHtml
* @function
* @private
* @param {String} html generated by jsdoc
* @param {Function} cb function (err, res) { } called with transformed html
*/
exports = module.exports = function adaptHtml(html, cb) {
githubInfo(function (err, ghinfo) {
if (err) return cb(err);
var dom = getDom(html);
adaptLinks(dom, ghinfo.blobRoot);
var trimmedHtml = dom.html().trim();
cb(null, '<div class="jsdoc-githubify">\n' + trimmedHtml + '\n</div>');
});
};
/**
* Determines if the given html contains API documentation
*
* @name hasApi
* @function
* @private
* @param {String} html
* @return true if @see html contains API documentation
*/
exports.hasApi = function(html) {
return !!cheerio(html).find('.details .tag-source').length;
}
| santiagogil/mis-e-recursos | node_modules/docme/node_modules/jsdoc-githubify/lib/adapt-html.js | JavaScript | gpl-3.0 | 3,153 |
#!/usr/bin/python
"""Joins a number of 3D manual markers into a 4D marker volume."""
# build-in modules
import argparse
import logging
import re
# third-party modules
import scipy
# path changes
# own modules
from medpy.core import Logger
from medpy.io import load, save
from medpy.core.exceptions import ArgumentError
from medpy.filter import relabel_non_zero
# information
__author__ = "Oskar Maier"
__version__ = "d0.1.0, 2012-06-13"
__email__ = "oskar.maier@googlemail.com"
__status__ = "Development"
__description__ = """
Prepares one or more 4D from a number of 3D manual marker volumes. The supplied volumes
have to follow a special naming convention. Additionally requires the original 4D image.
Images in 4D can not me visualized very well for the creation of manual markers. This
script and its counterpart allow to de-construct a 4D volume in various ways and to
afterwards combine the created marker volumes easily. Just select one of the following
modi, create markers for the resulting volumes and then join the markers together.
This script supports the combination of all manual marker volumes that follow the naming
convention. See the counterpart of this script, "Split for manual markers", for some more
remarks on this subject.
Some remarks on the manual markers:
The supplied marker file has to contain two or more markers, which all must have indices
between 1 and 9 (higher are ignored). If two markers could be found, the one with the
lowest index is treated as foreground (FG) and the other one as background (BG).
Upon the existence of more markers, all but the lone with the highest index are treated
as FG of an distinct object. For each of these objects a 4D marker volume is created,
whereas the associated marker index is treated as FG and all others joined together into
the BG marker.
In the resulting files the index 1 will always represent the FG and the index 2 the BG.
"""
# code
def main():
args = getArguments(getParser())
# prepare logger
logger = Logger.getInstance()
if args.debug: logger.setLevel(logging.DEBUG)
elif args.verbose: logger.setLevel(logging.INFO)
# load original example volume
original_data, original_header = load(args.original)
# prepare execution
result_data = scipy.zeros(original_data.shape, scipy.uint8)
del original_data
# First step: Combine all marker images
basename_old = False
# iterate over marker images
for marker_image in args.input:
# extract information from filename and prepare slicr object
basename, slice_dimension, slice_number = re.match(r'.*m(.*)_d([0-9])_s([0-9]{4}).*', marker_image).groups()
slice_dimension = int(slice_dimension)
slice_number = int(slice_number)
# check basenames
if basename_old and not basename_old == basename:
logger.warning('The marker seem to come from different sources. Encountered basenames {} and {}. Continuing anyway.'.format(basename, basename_old))
basename_old = basename
# prepare slicer
slicer = [slice(None)] * result_data.ndim
slicer[slice_dimension] = slice_number
# load marker image
marker_data, _ = load(marker_image)
# add to marker image ONLY where this is zero!
result_data_subvolume = result_data[slicer]
mask_array = result_data_subvolume == 0
result_data_subvolume[mask_array] = marker_data[mask_array]
if not 0 == len(marker_data[~mask_array].nonzero()[0]):
logger.warning('The mask volume {} showed some intersection with previous mask volumes. Up to {} marker voxels might be lost.'.format(marker_image, len(marker_data[~mask_array].nonzero()[0])))
# Second step: Normalize and determine type of markers
result_data[result_data >= 10] = 0 # remove markers with indices higher than 10
#result_data = relabel_non_zero(result_data) # relabel starting from 1, 0's are kept where encountered
marker_count = len(scipy.unique(result_data))
if 3 > marker_count: # less than two markers
raise ArgumentError('A minimum of two markers must be contained in the conjunction of all markers files (excluding the neutral markers of index 0).')
# assuming here that 1 == inner marker, 2 = border marker and 3 = background marker
inner_name = args.output.format('i')
inner_data = scipy.zeros_like(result_data)
inner_data[result_data == 1] = 1
inner_data[result_data == 2] = 2
inner_data[result_data == 3] = 2
save(inner_data, inner_name, original_header, args.force)
outer_name = args.output.format('o')
outer_data = scipy.zeros_like(result_data)
outer_data[result_data == 1] = 1
outer_data[result_data == 2] = 1
outer_data[result_data == 3] = 2
save(outer_data, outer_name, original_header, args.force)
# for marker in scipy.unique(result_data)[1:-1]: # first is neutral marker (0) and last overall background marker
# output = args.output.format(marker)
# _data = scipy.zeros_like(result_data)
# _data += 2 # set all as BG markers
# _data[result_data == marker] = 1
# _data[result_data == 0] = 0
# save(_data, output, original_header, args.force)
logger.info("Successfully terminated.")
def getArguments(parser):
"Provides additional validation of the arguments collected by argparse."
args = parser.parse_args()
if not '{}' in args.output:
raise ArgumentError(args.output, 'The output argument string must contain the sequence "{}".')
return args
def getParser():
"Creates and returns the argparse parser object."
parser = argparse.ArgumentParser(description=__description__, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('original', help='Original volume.')
parser.add_argument('output', help='Target volume(s). Has to include the sequence "{}" in the place where the marker number should be placed.')
parser.add_argument('input', nargs='+', help='The manual marker volumes to combine.')
parser.add_argument('-v', dest='verbose', action='store_true', help='Display more information.')
parser.add_argument('-d', dest='debug', action='store_true', help='Display debug information.')
parser.add_argument('-f', dest='force', action='store_true', help='Silently override existing output images.')
return parser
if __name__ == "__main__":
main()
| kleinfeld/medpy | bin/others/miccai12/join_for_manual_markers.py | Python | gpl-3.0 | 6,830 |
/*
* Ref-Finder
* Copyright (C) <2015> <PLSE_UCLA>
*
* 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 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 serp.util;
import java.lang.ref.*;
import java.util.*;
/**
* <p>Map implementation in which the keys are held as weak references.</p>
*
* <p>Expired values are removed from the map before any mutator methods;
* removing before accessor methods can lead to
* {@link ConcurrentModificationException}s. Thus, the following methods may
* produce results which include key/value pairs that have expired:
* <ul>
* <li><code>size</code></li>
* <li><code>isEmpty</code></li>
* <li><code>containsKey</code></li>
* <li><code>keySet.size,contains,isEmpty</code></li>
* <li><code>entrySet.size,contains,isEmpty</code></li>
* <li><code>values.size,contains,isEmpty</code></li>
* </ul></p>
*
* <p>By default, all methods are delegated to the internal map provided at
* construction. Thus, the ordering, etc of the given map will be preserved;
* however, the hashing algorithm cannot be duplicated. A special case is
* made for the {@link IdentityMap}'s hashing, which is supported.
* Performance is similar to that of the internal map instance.</p>
*
* @author Abe White
*/
public class WeakKeyMap
extends RefKeyMap
{
/**
* Equivalent to <code>WeakKeyMap (new HashMap ())</code>.
*/
public WeakKeyMap ()
{
super ();
}
/**
* Construct a WeakKeyMap with the given interal map. The internal
* map will be cleared. It should not be accessed in any way after being
* given to this constructor; this Map will 'inherit' its behavior,
* however. For example, if the given map is a {@link LinkedHashMap},
* the <code>values</code> method of this map will return values in
* insertion order.
*/
public WeakKeyMap (Map map)
{
super (map);
}
protected RefMapKey createRefMapKey (Object key, ReferenceQueue queue,
boolean identity)
{
if (queue == null)
return new WeakMapKey (key, identity);
else
return new WeakMapKey (key, queue, identity);
}
/**
* Struct holding the referenced key in a weak reference.
*/
private static final class WeakMapKey
extends WeakReference
implements RefMapKey
{
private boolean _identity = false;
private int _hash = 0;
public WeakMapKey (Object key, boolean identity)
{
super (key);
_identity = identity;
_hash = (identity) ? System.identityHashCode(key) : key.hashCode ();
}
public WeakMapKey (Object key, ReferenceQueue queue, boolean identity)
{
super (key, queue);
_identity = identity;
_hash = (identity) ? System.identityHashCode(key) : key.hashCode ();
}
public Object getKey ()
{
return get ();
}
public int hashCode ()
{
return _hash;
}
public boolean equals (Object other)
{
if (this == other)
return true;
if (other instanceof RefMapKey)
other = ((RefMapKey) other).getKey ();
Object obj = get ();
if (obj == null)
return false;
if (_identity)
return obj == other;
return obj.equals (other);
}
public int compareTo (Object other)
{
if (this == other)
return 0;
Object key = getKey ();
Object otherKey;
if (other instanceof RefMapKey)
otherKey = ((RefMapKey) other).getKey ();
else
otherKey = other;
if (key == null)
return -1;
if (otherKey == null)
return 1;
if (!(key instanceof Comparable))
return System.identityHashCode (otherKey)
- System.identityHashCode (key);
return ((Comparable) key).compareTo (otherKey);
}
}
}
| SoftwareEngineeringToolDemos/FSE-2010-Ref-Finder | code/lsd/serp/util/WeakKeyMap.java | Java | gpl-3.0 | 4,172 |
namespace FFR.Common
{
using System;
using FF1Lib;
using RomUtilities;
/// <summary>
/// Represents a set of randomization settings to supply
/// to ROM generation.
/// </summary>
public struct RandomizerSettings {
public Blob Seed { get; }
public Flags Flags { get; }
public Preferences Preferences { get; }
public string SeedString
=> Seed.ToHex();
public string FlagString
=> FF1Lib.Flags.EncodeFlagsText(Flags);
public RandomizerSettings(Flags flags, Preferences preferences)
: this(Blob.Random(4), flags, preferences) { }
public RandomizerSettings(string seed, Flags flags, Preferences preferences)
: this(SettingsUtils.ConvertSeed(seed), flags, preferences) { }
public RandomizerSettings(Blob seed, Flags flags, Preferences preferences)
{
Seed = seed;
Flags = flags;
Preferences = preferences;
}
public RandomizerSettings(string seed, string flags)
: this(
SettingsUtils.ConvertSeed(seed),
SettingsUtils.ConvertFlags(flags),
new Preferences()
) { }
public static RandomizerSettings FromImportString(string import)
{
var seed = import.Substring(0, 8);
var flags = import.Substring(9);
return new RandomizerSettings(seed, flags);
}
}
static class SettingsUtils {
/// <summary>
/// Convert a string composed of hexadecimal characters into a Blob.
/// Returns a random Blob on an empty string.
/// </summary>
// Will raise an exception if the input string has characters outside
// the [a-fA-f0-9] range.
public static Blob ConvertSeed(string maybeHex)
=> String.IsNullOrEmpty(maybeHex)
? Blob.Random(4)
: Blob.FromHex(maybeHex.Substring(0, 8));
public static Flags ConvertFlags(string maybeFlags)
=> String.IsNullOrEmpty(maybeFlags)
? new Flags()
: Flags.DecodeFlagsText(maybeFlags);
}
}
| Entroper/FF1Randomizer | FFR.Common/RandomizerSettings.cs | C# | gpl-3.0 | 1,902 |
package com.ugcleague.ops.domain.document;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.validation.constraints.NotNull;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
@Document(collection = "ugc_season")
public class UgcSeason {
@Id
private Integer id;
@NotNull
private Set<UgcWeek> weeks = new LinkedHashSet<>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Set<UgcWeek> getWeeks() {
return weeks;
}
public void setWeeks(Set<UgcWeek> weeks) {
this.weeks = weeks;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UgcSeason ugcSeason = (UgcSeason) o;
return Objects.equals(id, ugcSeason.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "UgcSeason{" +
"id=" + id +
", weeks=" + weeks +
'}';
}
}
| iabarca/ugc-bot-redux | src/main/java/com/ugcleague/ops/domain/document/UgcSeason.java | Java | gpl-3.0 | 1,211 |
# /* **************************************************************************
# * *
# * (C) Copyright Paul Mensonides 2002.
# * Distributed under the Boost Software License, Version 1.0. (See
# * accompanying file LICENSE_1_0.txt or copy at
# * http://www.boost.org/LICENSE_1_0.txt)
# * *
# ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# if defined(MSGPACK_PP_ITERATION_LIMITS)
# if !defined(MSGPACK_PP_FILENAME_4)
# error MSGPACK_PP_ERROR: depth #4 filename is not defined
# endif
# define MSGPACK_PP_VALUE MSGPACK_PP_TUPLE_ELEM(2, 0, MSGPACK_PP_ITERATION_LIMITS)
# include <rpc/msgpack/preprocessor/iteration/detail/bounds/lower4.hpp>
# define MSGPACK_PP_VALUE MSGPACK_PP_TUPLE_ELEM(2, 1, MSGPACK_PP_ITERATION_LIMITS)
# include <rpc/msgpack/preprocessor/iteration/detail/bounds/upper4.hpp>
# define MSGPACK_PP_ITERATION_FLAGS_4() 0
# undef MSGPACK_PP_ITERATION_LIMITS
# elif defined(MSGPACK_PP_ITERATION_PARAMS_4)
# define MSGPACK_PP_VALUE MSGPACK_PP_ARRAY_ELEM(0, MSGPACK_PP_ITERATION_PARAMS_4)
# include <rpc/msgpack/preprocessor/iteration/detail/bounds/lower4.hpp>
# define MSGPACK_PP_VALUE MSGPACK_PP_ARRAY_ELEM(1, MSGPACK_PP_ITERATION_PARAMS_4)
# include <rpc/msgpack/preprocessor/iteration/detail/bounds/upper4.hpp>
# define MSGPACK_PP_FILENAME_4 MSGPACK_PP_ARRAY_ELEM(2, MSGPACK_PP_ITERATION_PARAMS_4)
# if MSGPACK_PP_ARRAY_SIZE(MSGPACK_PP_ITERATION_PARAMS_4) >= 4
# define MSGPACK_PP_ITERATION_FLAGS_4() MSGPACK_PP_ARRAY_ELEM(3, MSGPACK_PP_ITERATION_PARAMS_4)
# else
# define MSGPACK_PP_ITERATION_FLAGS_4() 0
# endif
# else
# error MSGPACK_PP_ERROR: depth #4 iteration boundaries or filename not defined
# endif
#
# undef MSGPACK_PP_ITERATION_DEPTH
# define MSGPACK_PP_ITERATION_DEPTH() 4
#
# if (MSGPACK_PP_ITERATION_START_4) > (MSGPACK_PP_ITERATION_FINISH_4)
# include <rpc/msgpack/preprocessor/iteration/detail/iter/reverse4.hpp>
# else
# if MSGPACK_PP_ITERATION_START_4 <= 0 && MSGPACK_PP_ITERATION_FINISH_4 >= 0
# define MSGPACK_PP_ITERATION_4 0
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 1 && MSGPACK_PP_ITERATION_FINISH_4 >= 1
# define MSGPACK_PP_ITERATION_4 1
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 2 && MSGPACK_PP_ITERATION_FINISH_4 >= 2
# define MSGPACK_PP_ITERATION_4 2
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 3 && MSGPACK_PP_ITERATION_FINISH_4 >= 3
# define MSGPACK_PP_ITERATION_4 3
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 4 && MSGPACK_PP_ITERATION_FINISH_4 >= 4
# define MSGPACK_PP_ITERATION_4 4
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 5 && MSGPACK_PP_ITERATION_FINISH_4 >= 5
# define MSGPACK_PP_ITERATION_4 5
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 6 && MSGPACK_PP_ITERATION_FINISH_4 >= 6
# define MSGPACK_PP_ITERATION_4 6
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 7 && MSGPACK_PP_ITERATION_FINISH_4 >= 7
# define MSGPACK_PP_ITERATION_4 7
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 8 && MSGPACK_PP_ITERATION_FINISH_4 >= 8
# define MSGPACK_PP_ITERATION_4 8
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 9 && MSGPACK_PP_ITERATION_FINISH_4 >= 9
# define MSGPACK_PP_ITERATION_4 9
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 10 && MSGPACK_PP_ITERATION_FINISH_4 >= 10
# define MSGPACK_PP_ITERATION_4 10
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 11 && MSGPACK_PP_ITERATION_FINISH_4 >= 11
# define MSGPACK_PP_ITERATION_4 11
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 12 && MSGPACK_PP_ITERATION_FINISH_4 >= 12
# define MSGPACK_PP_ITERATION_4 12
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 13 && MSGPACK_PP_ITERATION_FINISH_4 >= 13
# define MSGPACK_PP_ITERATION_4 13
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 14 && MSGPACK_PP_ITERATION_FINISH_4 >= 14
# define MSGPACK_PP_ITERATION_4 14
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 15 && MSGPACK_PP_ITERATION_FINISH_4 >= 15
# define MSGPACK_PP_ITERATION_4 15
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 16 && MSGPACK_PP_ITERATION_FINISH_4 >= 16
# define MSGPACK_PP_ITERATION_4 16
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 17 && MSGPACK_PP_ITERATION_FINISH_4 >= 17
# define MSGPACK_PP_ITERATION_4 17
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 18 && MSGPACK_PP_ITERATION_FINISH_4 >= 18
# define MSGPACK_PP_ITERATION_4 18
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 19 && MSGPACK_PP_ITERATION_FINISH_4 >= 19
# define MSGPACK_PP_ITERATION_4 19
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 20 && MSGPACK_PP_ITERATION_FINISH_4 >= 20
# define MSGPACK_PP_ITERATION_4 20
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 21 && MSGPACK_PP_ITERATION_FINISH_4 >= 21
# define MSGPACK_PP_ITERATION_4 21
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 22 && MSGPACK_PP_ITERATION_FINISH_4 >= 22
# define MSGPACK_PP_ITERATION_4 22
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 23 && MSGPACK_PP_ITERATION_FINISH_4 >= 23
# define MSGPACK_PP_ITERATION_4 23
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 24 && MSGPACK_PP_ITERATION_FINISH_4 >= 24
# define MSGPACK_PP_ITERATION_4 24
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 25 && MSGPACK_PP_ITERATION_FINISH_4 >= 25
# define MSGPACK_PP_ITERATION_4 25
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 26 && MSGPACK_PP_ITERATION_FINISH_4 >= 26
# define MSGPACK_PP_ITERATION_4 26
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 27 && MSGPACK_PP_ITERATION_FINISH_4 >= 27
# define MSGPACK_PP_ITERATION_4 27
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 28 && MSGPACK_PP_ITERATION_FINISH_4 >= 28
# define MSGPACK_PP_ITERATION_4 28
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 29 && MSGPACK_PP_ITERATION_FINISH_4 >= 29
# define MSGPACK_PP_ITERATION_4 29
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 30 && MSGPACK_PP_ITERATION_FINISH_4 >= 30
# define MSGPACK_PP_ITERATION_4 30
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 31 && MSGPACK_PP_ITERATION_FINISH_4 >= 31
# define MSGPACK_PP_ITERATION_4 31
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 32 && MSGPACK_PP_ITERATION_FINISH_4 >= 32
# define MSGPACK_PP_ITERATION_4 32
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 33 && MSGPACK_PP_ITERATION_FINISH_4 >= 33
# define MSGPACK_PP_ITERATION_4 33
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 34 && MSGPACK_PP_ITERATION_FINISH_4 >= 34
# define MSGPACK_PP_ITERATION_4 34
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 35 && MSGPACK_PP_ITERATION_FINISH_4 >= 35
# define MSGPACK_PP_ITERATION_4 35
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 36 && MSGPACK_PP_ITERATION_FINISH_4 >= 36
# define MSGPACK_PP_ITERATION_4 36
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 37 && MSGPACK_PP_ITERATION_FINISH_4 >= 37
# define MSGPACK_PP_ITERATION_4 37
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 38 && MSGPACK_PP_ITERATION_FINISH_4 >= 38
# define MSGPACK_PP_ITERATION_4 38
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 39 && MSGPACK_PP_ITERATION_FINISH_4 >= 39
# define MSGPACK_PP_ITERATION_4 39
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 40 && MSGPACK_PP_ITERATION_FINISH_4 >= 40
# define MSGPACK_PP_ITERATION_4 40
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 41 && MSGPACK_PP_ITERATION_FINISH_4 >= 41
# define MSGPACK_PP_ITERATION_4 41
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 42 && MSGPACK_PP_ITERATION_FINISH_4 >= 42
# define MSGPACK_PP_ITERATION_4 42
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 43 && MSGPACK_PP_ITERATION_FINISH_4 >= 43
# define MSGPACK_PP_ITERATION_4 43
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 44 && MSGPACK_PP_ITERATION_FINISH_4 >= 44
# define MSGPACK_PP_ITERATION_4 44
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 45 && MSGPACK_PP_ITERATION_FINISH_4 >= 45
# define MSGPACK_PP_ITERATION_4 45
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 46 && MSGPACK_PP_ITERATION_FINISH_4 >= 46
# define MSGPACK_PP_ITERATION_4 46
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 47 && MSGPACK_PP_ITERATION_FINISH_4 >= 47
# define MSGPACK_PP_ITERATION_4 47
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 48 && MSGPACK_PP_ITERATION_FINISH_4 >= 48
# define MSGPACK_PP_ITERATION_4 48
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 49 && MSGPACK_PP_ITERATION_FINISH_4 >= 49
# define MSGPACK_PP_ITERATION_4 49
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 50 && MSGPACK_PP_ITERATION_FINISH_4 >= 50
# define MSGPACK_PP_ITERATION_4 50
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 51 && MSGPACK_PP_ITERATION_FINISH_4 >= 51
# define MSGPACK_PP_ITERATION_4 51
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 52 && MSGPACK_PP_ITERATION_FINISH_4 >= 52
# define MSGPACK_PP_ITERATION_4 52
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 53 && MSGPACK_PP_ITERATION_FINISH_4 >= 53
# define MSGPACK_PP_ITERATION_4 53
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 54 && MSGPACK_PP_ITERATION_FINISH_4 >= 54
# define MSGPACK_PP_ITERATION_4 54
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 55 && MSGPACK_PP_ITERATION_FINISH_4 >= 55
# define MSGPACK_PP_ITERATION_4 55
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 56 && MSGPACK_PP_ITERATION_FINISH_4 >= 56
# define MSGPACK_PP_ITERATION_4 56
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 57 && MSGPACK_PP_ITERATION_FINISH_4 >= 57
# define MSGPACK_PP_ITERATION_4 57
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 58 && MSGPACK_PP_ITERATION_FINISH_4 >= 58
# define MSGPACK_PP_ITERATION_4 58
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 59 && MSGPACK_PP_ITERATION_FINISH_4 >= 59
# define MSGPACK_PP_ITERATION_4 59
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 60 && MSGPACK_PP_ITERATION_FINISH_4 >= 60
# define MSGPACK_PP_ITERATION_4 60
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 61 && MSGPACK_PP_ITERATION_FINISH_4 >= 61
# define MSGPACK_PP_ITERATION_4 61
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 62 && MSGPACK_PP_ITERATION_FINISH_4 >= 62
# define MSGPACK_PP_ITERATION_4 62
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 63 && MSGPACK_PP_ITERATION_FINISH_4 >= 63
# define MSGPACK_PP_ITERATION_4 63
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 64 && MSGPACK_PP_ITERATION_FINISH_4 >= 64
# define MSGPACK_PP_ITERATION_4 64
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 65 && MSGPACK_PP_ITERATION_FINISH_4 >= 65
# define MSGPACK_PP_ITERATION_4 65
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 66 && MSGPACK_PP_ITERATION_FINISH_4 >= 66
# define MSGPACK_PP_ITERATION_4 66
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 67 && MSGPACK_PP_ITERATION_FINISH_4 >= 67
# define MSGPACK_PP_ITERATION_4 67
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 68 && MSGPACK_PP_ITERATION_FINISH_4 >= 68
# define MSGPACK_PP_ITERATION_4 68
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 69 && MSGPACK_PP_ITERATION_FINISH_4 >= 69
# define MSGPACK_PP_ITERATION_4 69
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 70 && MSGPACK_PP_ITERATION_FINISH_4 >= 70
# define MSGPACK_PP_ITERATION_4 70
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 71 && MSGPACK_PP_ITERATION_FINISH_4 >= 71
# define MSGPACK_PP_ITERATION_4 71
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 72 && MSGPACK_PP_ITERATION_FINISH_4 >= 72
# define MSGPACK_PP_ITERATION_4 72
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 73 && MSGPACK_PP_ITERATION_FINISH_4 >= 73
# define MSGPACK_PP_ITERATION_4 73
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 74 && MSGPACK_PP_ITERATION_FINISH_4 >= 74
# define MSGPACK_PP_ITERATION_4 74
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 75 && MSGPACK_PP_ITERATION_FINISH_4 >= 75
# define MSGPACK_PP_ITERATION_4 75
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 76 && MSGPACK_PP_ITERATION_FINISH_4 >= 76
# define MSGPACK_PP_ITERATION_4 76
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 77 && MSGPACK_PP_ITERATION_FINISH_4 >= 77
# define MSGPACK_PP_ITERATION_4 77
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 78 && MSGPACK_PP_ITERATION_FINISH_4 >= 78
# define MSGPACK_PP_ITERATION_4 78
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 79 && MSGPACK_PP_ITERATION_FINISH_4 >= 79
# define MSGPACK_PP_ITERATION_4 79
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 80 && MSGPACK_PP_ITERATION_FINISH_4 >= 80
# define MSGPACK_PP_ITERATION_4 80
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 81 && MSGPACK_PP_ITERATION_FINISH_4 >= 81
# define MSGPACK_PP_ITERATION_4 81
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 82 && MSGPACK_PP_ITERATION_FINISH_4 >= 82
# define MSGPACK_PP_ITERATION_4 82
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 83 && MSGPACK_PP_ITERATION_FINISH_4 >= 83
# define MSGPACK_PP_ITERATION_4 83
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 84 && MSGPACK_PP_ITERATION_FINISH_4 >= 84
# define MSGPACK_PP_ITERATION_4 84
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 85 && MSGPACK_PP_ITERATION_FINISH_4 >= 85
# define MSGPACK_PP_ITERATION_4 85
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 86 && MSGPACK_PP_ITERATION_FINISH_4 >= 86
# define MSGPACK_PP_ITERATION_4 86
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 87 && MSGPACK_PP_ITERATION_FINISH_4 >= 87
# define MSGPACK_PP_ITERATION_4 87
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 88 && MSGPACK_PP_ITERATION_FINISH_4 >= 88
# define MSGPACK_PP_ITERATION_4 88
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 89 && MSGPACK_PP_ITERATION_FINISH_4 >= 89
# define MSGPACK_PP_ITERATION_4 89
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 90 && MSGPACK_PP_ITERATION_FINISH_4 >= 90
# define MSGPACK_PP_ITERATION_4 90
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 91 && MSGPACK_PP_ITERATION_FINISH_4 >= 91
# define MSGPACK_PP_ITERATION_4 91
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 92 && MSGPACK_PP_ITERATION_FINISH_4 >= 92
# define MSGPACK_PP_ITERATION_4 92
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 93 && MSGPACK_PP_ITERATION_FINISH_4 >= 93
# define MSGPACK_PP_ITERATION_4 93
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 94 && MSGPACK_PP_ITERATION_FINISH_4 >= 94
# define MSGPACK_PP_ITERATION_4 94
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 95 && MSGPACK_PP_ITERATION_FINISH_4 >= 95
# define MSGPACK_PP_ITERATION_4 95
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 96 && MSGPACK_PP_ITERATION_FINISH_4 >= 96
# define MSGPACK_PP_ITERATION_4 96
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 97 && MSGPACK_PP_ITERATION_FINISH_4 >= 97
# define MSGPACK_PP_ITERATION_4 97
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 98 && MSGPACK_PP_ITERATION_FINISH_4 >= 98
# define MSGPACK_PP_ITERATION_4 98
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 99 && MSGPACK_PP_ITERATION_FINISH_4 >= 99
# define MSGPACK_PP_ITERATION_4 99
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 100 && MSGPACK_PP_ITERATION_FINISH_4 >= 100
# define MSGPACK_PP_ITERATION_4 100
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 101 && MSGPACK_PP_ITERATION_FINISH_4 >= 101
# define MSGPACK_PP_ITERATION_4 101
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 102 && MSGPACK_PP_ITERATION_FINISH_4 >= 102
# define MSGPACK_PP_ITERATION_4 102
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 103 && MSGPACK_PP_ITERATION_FINISH_4 >= 103
# define MSGPACK_PP_ITERATION_4 103
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 104 && MSGPACK_PP_ITERATION_FINISH_4 >= 104
# define MSGPACK_PP_ITERATION_4 104
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 105 && MSGPACK_PP_ITERATION_FINISH_4 >= 105
# define MSGPACK_PP_ITERATION_4 105
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 106 && MSGPACK_PP_ITERATION_FINISH_4 >= 106
# define MSGPACK_PP_ITERATION_4 106
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 107 && MSGPACK_PP_ITERATION_FINISH_4 >= 107
# define MSGPACK_PP_ITERATION_4 107
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 108 && MSGPACK_PP_ITERATION_FINISH_4 >= 108
# define MSGPACK_PP_ITERATION_4 108
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 109 && MSGPACK_PP_ITERATION_FINISH_4 >= 109
# define MSGPACK_PP_ITERATION_4 109
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 110 && MSGPACK_PP_ITERATION_FINISH_4 >= 110
# define MSGPACK_PP_ITERATION_4 110
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 111 && MSGPACK_PP_ITERATION_FINISH_4 >= 111
# define MSGPACK_PP_ITERATION_4 111
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 112 && MSGPACK_PP_ITERATION_FINISH_4 >= 112
# define MSGPACK_PP_ITERATION_4 112
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 113 && MSGPACK_PP_ITERATION_FINISH_4 >= 113
# define MSGPACK_PP_ITERATION_4 113
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 114 && MSGPACK_PP_ITERATION_FINISH_4 >= 114
# define MSGPACK_PP_ITERATION_4 114
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 115 && MSGPACK_PP_ITERATION_FINISH_4 >= 115
# define MSGPACK_PP_ITERATION_4 115
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 116 && MSGPACK_PP_ITERATION_FINISH_4 >= 116
# define MSGPACK_PP_ITERATION_4 116
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 117 && MSGPACK_PP_ITERATION_FINISH_4 >= 117
# define MSGPACK_PP_ITERATION_4 117
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 118 && MSGPACK_PP_ITERATION_FINISH_4 >= 118
# define MSGPACK_PP_ITERATION_4 118
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 119 && MSGPACK_PP_ITERATION_FINISH_4 >= 119
# define MSGPACK_PP_ITERATION_4 119
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 120 && MSGPACK_PP_ITERATION_FINISH_4 >= 120
# define MSGPACK_PP_ITERATION_4 120
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 121 && MSGPACK_PP_ITERATION_FINISH_4 >= 121
# define MSGPACK_PP_ITERATION_4 121
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 122 && MSGPACK_PP_ITERATION_FINISH_4 >= 122
# define MSGPACK_PP_ITERATION_4 122
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 123 && MSGPACK_PP_ITERATION_FINISH_4 >= 123
# define MSGPACK_PP_ITERATION_4 123
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 124 && MSGPACK_PP_ITERATION_FINISH_4 >= 124
# define MSGPACK_PP_ITERATION_4 124
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 125 && MSGPACK_PP_ITERATION_FINISH_4 >= 125
# define MSGPACK_PP_ITERATION_4 125
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 126 && MSGPACK_PP_ITERATION_FINISH_4 >= 126
# define MSGPACK_PP_ITERATION_4 126
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 127 && MSGPACK_PP_ITERATION_FINISH_4 >= 127
# define MSGPACK_PP_ITERATION_4 127
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 128 && MSGPACK_PP_ITERATION_FINISH_4 >= 128
# define MSGPACK_PP_ITERATION_4 128
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 129 && MSGPACK_PP_ITERATION_FINISH_4 >= 129
# define MSGPACK_PP_ITERATION_4 129
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 130 && MSGPACK_PP_ITERATION_FINISH_4 >= 130
# define MSGPACK_PP_ITERATION_4 130
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 131 && MSGPACK_PP_ITERATION_FINISH_4 >= 131
# define MSGPACK_PP_ITERATION_4 131
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 132 && MSGPACK_PP_ITERATION_FINISH_4 >= 132
# define MSGPACK_PP_ITERATION_4 132
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 133 && MSGPACK_PP_ITERATION_FINISH_4 >= 133
# define MSGPACK_PP_ITERATION_4 133
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 134 && MSGPACK_PP_ITERATION_FINISH_4 >= 134
# define MSGPACK_PP_ITERATION_4 134
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 135 && MSGPACK_PP_ITERATION_FINISH_4 >= 135
# define MSGPACK_PP_ITERATION_4 135
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 136 && MSGPACK_PP_ITERATION_FINISH_4 >= 136
# define MSGPACK_PP_ITERATION_4 136
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 137 && MSGPACK_PP_ITERATION_FINISH_4 >= 137
# define MSGPACK_PP_ITERATION_4 137
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 138 && MSGPACK_PP_ITERATION_FINISH_4 >= 138
# define MSGPACK_PP_ITERATION_4 138
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 139 && MSGPACK_PP_ITERATION_FINISH_4 >= 139
# define MSGPACK_PP_ITERATION_4 139
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 140 && MSGPACK_PP_ITERATION_FINISH_4 >= 140
# define MSGPACK_PP_ITERATION_4 140
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 141 && MSGPACK_PP_ITERATION_FINISH_4 >= 141
# define MSGPACK_PP_ITERATION_4 141
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 142 && MSGPACK_PP_ITERATION_FINISH_4 >= 142
# define MSGPACK_PP_ITERATION_4 142
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 143 && MSGPACK_PP_ITERATION_FINISH_4 >= 143
# define MSGPACK_PP_ITERATION_4 143
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 144 && MSGPACK_PP_ITERATION_FINISH_4 >= 144
# define MSGPACK_PP_ITERATION_4 144
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 145 && MSGPACK_PP_ITERATION_FINISH_4 >= 145
# define MSGPACK_PP_ITERATION_4 145
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 146 && MSGPACK_PP_ITERATION_FINISH_4 >= 146
# define MSGPACK_PP_ITERATION_4 146
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 147 && MSGPACK_PP_ITERATION_FINISH_4 >= 147
# define MSGPACK_PP_ITERATION_4 147
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 148 && MSGPACK_PP_ITERATION_FINISH_4 >= 148
# define MSGPACK_PP_ITERATION_4 148
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 149 && MSGPACK_PP_ITERATION_FINISH_4 >= 149
# define MSGPACK_PP_ITERATION_4 149
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 150 && MSGPACK_PP_ITERATION_FINISH_4 >= 150
# define MSGPACK_PP_ITERATION_4 150
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 151 && MSGPACK_PP_ITERATION_FINISH_4 >= 151
# define MSGPACK_PP_ITERATION_4 151
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 152 && MSGPACK_PP_ITERATION_FINISH_4 >= 152
# define MSGPACK_PP_ITERATION_4 152
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 153 && MSGPACK_PP_ITERATION_FINISH_4 >= 153
# define MSGPACK_PP_ITERATION_4 153
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 154 && MSGPACK_PP_ITERATION_FINISH_4 >= 154
# define MSGPACK_PP_ITERATION_4 154
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 155 && MSGPACK_PP_ITERATION_FINISH_4 >= 155
# define MSGPACK_PP_ITERATION_4 155
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 156 && MSGPACK_PP_ITERATION_FINISH_4 >= 156
# define MSGPACK_PP_ITERATION_4 156
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 157 && MSGPACK_PP_ITERATION_FINISH_4 >= 157
# define MSGPACK_PP_ITERATION_4 157
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 158 && MSGPACK_PP_ITERATION_FINISH_4 >= 158
# define MSGPACK_PP_ITERATION_4 158
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 159 && MSGPACK_PP_ITERATION_FINISH_4 >= 159
# define MSGPACK_PP_ITERATION_4 159
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 160 && MSGPACK_PP_ITERATION_FINISH_4 >= 160
# define MSGPACK_PP_ITERATION_4 160
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 161 && MSGPACK_PP_ITERATION_FINISH_4 >= 161
# define MSGPACK_PP_ITERATION_4 161
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 162 && MSGPACK_PP_ITERATION_FINISH_4 >= 162
# define MSGPACK_PP_ITERATION_4 162
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 163 && MSGPACK_PP_ITERATION_FINISH_4 >= 163
# define MSGPACK_PP_ITERATION_4 163
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 164 && MSGPACK_PP_ITERATION_FINISH_4 >= 164
# define MSGPACK_PP_ITERATION_4 164
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 165 && MSGPACK_PP_ITERATION_FINISH_4 >= 165
# define MSGPACK_PP_ITERATION_4 165
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 166 && MSGPACK_PP_ITERATION_FINISH_4 >= 166
# define MSGPACK_PP_ITERATION_4 166
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 167 && MSGPACK_PP_ITERATION_FINISH_4 >= 167
# define MSGPACK_PP_ITERATION_4 167
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 168 && MSGPACK_PP_ITERATION_FINISH_4 >= 168
# define MSGPACK_PP_ITERATION_4 168
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 169 && MSGPACK_PP_ITERATION_FINISH_4 >= 169
# define MSGPACK_PP_ITERATION_4 169
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 170 && MSGPACK_PP_ITERATION_FINISH_4 >= 170
# define MSGPACK_PP_ITERATION_4 170
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 171 && MSGPACK_PP_ITERATION_FINISH_4 >= 171
# define MSGPACK_PP_ITERATION_4 171
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 172 && MSGPACK_PP_ITERATION_FINISH_4 >= 172
# define MSGPACK_PP_ITERATION_4 172
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 173 && MSGPACK_PP_ITERATION_FINISH_4 >= 173
# define MSGPACK_PP_ITERATION_4 173
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 174 && MSGPACK_PP_ITERATION_FINISH_4 >= 174
# define MSGPACK_PP_ITERATION_4 174
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 175 && MSGPACK_PP_ITERATION_FINISH_4 >= 175
# define MSGPACK_PP_ITERATION_4 175
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 176 && MSGPACK_PP_ITERATION_FINISH_4 >= 176
# define MSGPACK_PP_ITERATION_4 176
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 177 && MSGPACK_PP_ITERATION_FINISH_4 >= 177
# define MSGPACK_PP_ITERATION_4 177
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 178 && MSGPACK_PP_ITERATION_FINISH_4 >= 178
# define MSGPACK_PP_ITERATION_4 178
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 179 && MSGPACK_PP_ITERATION_FINISH_4 >= 179
# define MSGPACK_PP_ITERATION_4 179
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 180 && MSGPACK_PP_ITERATION_FINISH_4 >= 180
# define MSGPACK_PP_ITERATION_4 180
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 181 && MSGPACK_PP_ITERATION_FINISH_4 >= 181
# define MSGPACK_PP_ITERATION_4 181
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 182 && MSGPACK_PP_ITERATION_FINISH_4 >= 182
# define MSGPACK_PP_ITERATION_4 182
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 183 && MSGPACK_PP_ITERATION_FINISH_4 >= 183
# define MSGPACK_PP_ITERATION_4 183
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 184 && MSGPACK_PP_ITERATION_FINISH_4 >= 184
# define MSGPACK_PP_ITERATION_4 184
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 185 && MSGPACK_PP_ITERATION_FINISH_4 >= 185
# define MSGPACK_PP_ITERATION_4 185
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 186 && MSGPACK_PP_ITERATION_FINISH_4 >= 186
# define MSGPACK_PP_ITERATION_4 186
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 187 && MSGPACK_PP_ITERATION_FINISH_4 >= 187
# define MSGPACK_PP_ITERATION_4 187
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 188 && MSGPACK_PP_ITERATION_FINISH_4 >= 188
# define MSGPACK_PP_ITERATION_4 188
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 189 && MSGPACK_PP_ITERATION_FINISH_4 >= 189
# define MSGPACK_PP_ITERATION_4 189
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 190 && MSGPACK_PP_ITERATION_FINISH_4 >= 190
# define MSGPACK_PP_ITERATION_4 190
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 191 && MSGPACK_PP_ITERATION_FINISH_4 >= 191
# define MSGPACK_PP_ITERATION_4 191
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 192 && MSGPACK_PP_ITERATION_FINISH_4 >= 192
# define MSGPACK_PP_ITERATION_4 192
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 193 && MSGPACK_PP_ITERATION_FINISH_4 >= 193
# define MSGPACK_PP_ITERATION_4 193
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 194 && MSGPACK_PP_ITERATION_FINISH_4 >= 194
# define MSGPACK_PP_ITERATION_4 194
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 195 && MSGPACK_PP_ITERATION_FINISH_4 >= 195
# define MSGPACK_PP_ITERATION_4 195
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 196 && MSGPACK_PP_ITERATION_FINISH_4 >= 196
# define MSGPACK_PP_ITERATION_4 196
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 197 && MSGPACK_PP_ITERATION_FINISH_4 >= 197
# define MSGPACK_PP_ITERATION_4 197
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 198 && MSGPACK_PP_ITERATION_FINISH_4 >= 198
# define MSGPACK_PP_ITERATION_4 198
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 199 && MSGPACK_PP_ITERATION_FINISH_4 >= 199
# define MSGPACK_PP_ITERATION_4 199
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 200 && MSGPACK_PP_ITERATION_FINISH_4 >= 200
# define MSGPACK_PP_ITERATION_4 200
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 201 && MSGPACK_PP_ITERATION_FINISH_4 >= 201
# define MSGPACK_PP_ITERATION_4 201
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 202 && MSGPACK_PP_ITERATION_FINISH_4 >= 202
# define MSGPACK_PP_ITERATION_4 202
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 203 && MSGPACK_PP_ITERATION_FINISH_4 >= 203
# define MSGPACK_PP_ITERATION_4 203
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 204 && MSGPACK_PP_ITERATION_FINISH_4 >= 204
# define MSGPACK_PP_ITERATION_4 204
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 205 && MSGPACK_PP_ITERATION_FINISH_4 >= 205
# define MSGPACK_PP_ITERATION_4 205
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 206 && MSGPACK_PP_ITERATION_FINISH_4 >= 206
# define MSGPACK_PP_ITERATION_4 206
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 207 && MSGPACK_PP_ITERATION_FINISH_4 >= 207
# define MSGPACK_PP_ITERATION_4 207
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 208 && MSGPACK_PP_ITERATION_FINISH_4 >= 208
# define MSGPACK_PP_ITERATION_4 208
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 209 && MSGPACK_PP_ITERATION_FINISH_4 >= 209
# define MSGPACK_PP_ITERATION_4 209
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 210 && MSGPACK_PP_ITERATION_FINISH_4 >= 210
# define MSGPACK_PP_ITERATION_4 210
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 211 && MSGPACK_PP_ITERATION_FINISH_4 >= 211
# define MSGPACK_PP_ITERATION_4 211
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 212 && MSGPACK_PP_ITERATION_FINISH_4 >= 212
# define MSGPACK_PP_ITERATION_4 212
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 213 && MSGPACK_PP_ITERATION_FINISH_4 >= 213
# define MSGPACK_PP_ITERATION_4 213
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 214 && MSGPACK_PP_ITERATION_FINISH_4 >= 214
# define MSGPACK_PP_ITERATION_4 214
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 215 && MSGPACK_PP_ITERATION_FINISH_4 >= 215
# define MSGPACK_PP_ITERATION_4 215
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 216 && MSGPACK_PP_ITERATION_FINISH_4 >= 216
# define MSGPACK_PP_ITERATION_4 216
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 217 && MSGPACK_PP_ITERATION_FINISH_4 >= 217
# define MSGPACK_PP_ITERATION_4 217
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 218 && MSGPACK_PP_ITERATION_FINISH_4 >= 218
# define MSGPACK_PP_ITERATION_4 218
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 219 && MSGPACK_PP_ITERATION_FINISH_4 >= 219
# define MSGPACK_PP_ITERATION_4 219
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 220 && MSGPACK_PP_ITERATION_FINISH_4 >= 220
# define MSGPACK_PP_ITERATION_4 220
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 221 && MSGPACK_PP_ITERATION_FINISH_4 >= 221
# define MSGPACK_PP_ITERATION_4 221
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 222 && MSGPACK_PP_ITERATION_FINISH_4 >= 222
# define MSGPACK_PP_ITERATION_4 222
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 223 && MSGPACK_PP_ITERATION_FINISH_4 >= 223
# define MSGPACK_PP_ITERATION_4 223
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 224 && MSGPACK_PP_ITERATION_FINISH_4 >= 224
# define MSGPACK_PP_ITERATION_4 224
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 225 && MSGPACK_PP_ITERATION_FINISH_4 >= 225
# define MSGPACK_PP_ITERATION_4 225
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 226 && MSGPACK_PP_ITERATION_FINISH_4 >= 226
# define MSGPACK_PP_ITERATION_4 226
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 227 && MSGPACK_PP_ITERATION_FINISH_4 >= 227
# define MSGPACK_PP_ITERATION_4 227
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 228 && MSGPACK_PP_ITERATION_FINISH_4 >= 228
# define MSGPACK_PP_ITERATION_4 228
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 229 && MSGPACK_PP_ITERATION_FINISH_4 >= 229
# define MSGPACK_PP_ITERATION_4 229
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 230 && MSGPACK_PP_ITERATION_FINISH_4 >= 230
# define MSGPACK_PP_ITERATION_4 230
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 231 && MSGPACK_PP_ITERATION_FINISH_4 >= 231
# define MSGPACK_PP_ITERATION_4 231
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 232 && MSGPACK_PP_ITERATION_FINISH_4 >= 232
# define MSGPACK_PP_ITERATION_4 232
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 233 && MSGPACK_PP_ITERATION_FINISH_4 >= 233
# define MSGPACK_PP_ITERATION_4 233
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 234 && MSGPACK_PP_ITERATION_FINISH_4 >= 234
# define MSGPACK_PP_ITERATION_4 234
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 235 && MSGPACK_PP_ITERATION_FINISH_4 >= 235
# define MSGPACK_PP_ITERATION_4 235
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 236 && MSGPACK_PP_ITERATION_FINISH_4 >= 236
# define MSGPACK_PP_ITERATION_4 236
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 237 && MSGPACK_PP_ITERATION_FINISH_4 >= 237
# define MSGPACK_PP_ITERATION_4 237
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 238 && MSGPACK_PP_ITERATION_FINISH_4 >= 238
# define MSGPACK_PP_ITERATION_4 238
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 239 && MSGPACK_PP_ITERATION_FINISH_4 >= 239
# define MSGPACK_PP_ITERATION_4 239
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 240 && MSGPACK_PP_ITERATION_FINISH_4 >= 240
# define MSGPACK_PP_ITERATION_4 240
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 241 && MSGPACK_PP_ITERATION_FINISH_4 >= 241
# define MSGPACK_PP_ITERATION_4 241
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 242 && MSGPACK_PP_ITERATION_FINISH_4 >= 242
# define MSGPACK_PP_ITERATION_4 242
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 243 && MSGPACK_PP_ITERATION_FINISH_4 >= 243
# define MSGPACK_PP_ITERATION_4 243
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 244 && MSGPACK_PP_ITERATION_FINISH_4 >= 244
# define MSGPACK_PP_ITERATION_4 244
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 245 && MSGPACK_PP_ITERATION_FINISH_4 >= 245
# define MSGPACK_PP_ITERATION_4 245
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 246 && MSGPACK_PP_ITERATION_FINISH_4 >= 246
# define MSGPACK_PP_ITERATION_4 246
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 247 && MSGPACK_PP_ITERATION_FINISH_4 >= 247
# define MSGPACK_PP_ITERATION_4 247
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 248 && MSGPACK_PP_ITERATION_FINISH_4 >= 248
# define MSGPACK_PP_ITERATION_4 248
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 249 && MSGPACK_PP_ITERATION_FINISH_4 >= 249
# define MSGPACK_PP_ITERATION_4 249
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 250 && MSGPACK_PP_ITERATION_FINISH_4 >= 250
# define MSGPACK_PP_ITERATION_4 250
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 251 && MSGPACK_PP_ITERATION_FINISH_4 >= 251
# define MSGPACK_PP_ITERATION_4 251
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 252 && MSGPACK_PP_ITERATION_FINISH_4 >= 252
# define MSGPACK_PP_ITERATION_4 252
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 253 && MSGPACK_PP_ITERATION_FINISH_4 >= 253
# define MSGPACK_PP_ITERATION_4 253
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 254 && MSGPACK_PP_ITERATION_FINISH_4 >= 254
# define MSGPACK_PP_ITERATION_4 254
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 255 && MSGPACK_PP_ITERATION_FINISH_4 >= 255
# define MSGPACK_PP_ITERATION_4 255
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# if MSGPACK_PP_ITERATION_START_4 <= 256 && MSGPACK_PP_ITERATION_FINISH_4 >= 256
# define MSGPACK_PP_ITERATION_4 256
# include MSGPACK_PP_FILENAME_4
# undef MSGPACK_PP_ITERATION_4
# endif
# endif
#
# undef MSGPACK_PP_ITERATION_DEPTH
# define MSGPACK_PP_ITERATION_DEPTH() 3
#
# undef MSGPACK_PP_ITERATION_START_4
# undef MSGPACK_PP_ITERATION_FINISH_4
# undef MSGPACK_PP_FILENAME_4
#
# undef MSGPACK_PP_ITERATION_FLAGS_4
# undef MSGPACK_PP_ITERATION_PARAMS_4
| dvdjg/GoapCpp | GoapMain/3rdparty/rpclib/include/rpc/msgpack/preprocessor/iteration/detail/iter/forward4.hpp | C++ | gpl-3.0 | 57,387 |
#!/usr/bin/env python
# encoding: utf-8
# andersg at 0x63.nu 2007
# Thomas Nagy 2010 (ita)
"""
Support for Perl extensions. A C/C++ compiler is required::
def options(opt):
opt.load('compiler_c perl')
def configure(conf):
conf.load('compiler_c perl')
conf.check_perl_version((5,6,0))
conf.check_perl_ext_devel()
conf.check_perl_module('Cairo')
conf.check_perl_module('Devel::PPPort 4.89')
def build(bld):
bld(
features = 'c cshlib perlext',
source = 'Mytest.xs',
target = 'Mytest',
install_path = '${ARCHDIR_PERL}/auto')
bld.install_files('${ARCHDIR_PERL}', 'Mytest.pm')
"""
import os
from waflib import Task, Options, Utils
from waflib.Configure import conf
from waflib.TaskGen import extension, feature, before_method
@before_method('apply_incpaths', 'apply_link', 'propagate_uselib_vars')
@feature('perlext')
def init_perlext(self):
"""
Change the values of *cshlib_PATTERN* and *cxxshlib_PATTERN* to remove the
*lib* prefix from library names.
"""
self.uselib = self.to_list(getattr(self, 'uselib', []))
if not 'PERLEXT' in self.uselib: self.uselib.append('PERLEXT')
self.env['cshlib_PATTERN'] = self.env['cxxshlib_PATTERN'] = self.env['perlext_PATTERN']
@extension('.xs')
def xsubpp_file(self, node):
"""
Create :py:class:`waflib.Tools.perl.xsubpp` tasks to process *.xs* files
"""
outnode = node.change_ext('.c')
self.create_task('xsubpp', node, outnode)
self.source.append(outnode)
class xsubpp(Task.Task):
"""
Process *.xs* files
"""
run_str = '${PERL} ${XSUBPP} -noprototypes -typemap ${EXTUTILS_TYPEMAP} ${SRC} > ${TGT}'
color = 'BLUE'
ext_out = ['.h']
@conf
def check_perl_version(self, minver=None):
"""
Check if Perl is installed, and set the variable PERL.
minver is supposed to be a tuple
"""
res = True
if minver:
cver = '.'.join(map(str,minver))
else:
cver = ''
self.start_msg('Checking for minimum perl version %s' % cver)
perl = getattr(Options.options, 'perlbinary', None)
if not perl:
perl = self.find_program('perl', var='PERL')
if not perl:
self.end_msg("Perl not found", color="YELLOW")
return False
self.env['PERL'] = perl
version = self.cmd_and_log(self.env.PERL + ["-e", 'printf \"%vd\", $^V'])
if not version:
res = False
version = "Unknown"
elif not minver is None:
ver = tuple(map(int, version.split(".")))
if ver < minver:
res = False
self.end_msg(version, color=res and "GREEN" or "YELLOW")
return res
@conf
def check_perl_module(self, module):
"""
Check if specified perlmodule is installed.
The minimum version can be specified by specifying it after modulename
like this::
def configure(conf):
conf.check_perl_module("Some::Module 2.92")
"""
cmd = self.env.PERL + ['-e', 'use %s' % module]
self.start_msg('perl module %s' % module)
try:
r = self.cmd_and_log(cmd)
except Exception:
self.end_msg(False)
return None
self.end_msg(r or True)
return r
@conf
def check_perl_ext_devel(self):
"""
Check for configuration needed to build perl extensions.
Sets different xxx_PERLEXT variables in the environment.
Also sets the ARCHDIR_PERL variable useful as installation path,
which can be overridden by ``--with-perl-archdir`` option.
"""
env = self.env
perl = env.PERL
if not perl:
self.fatal('find perl first')
def cmd_perl_config(s):
return perl + ['-MConfig', '-e', 'print \"%s\"' % s]
def cfg_str(cfg):
return self.cmd_and_log(cmd_perl_config(cfg))
def cfg_lst(cfg):
return Utils.to_list(cfg_str(cfg))
env['LINKFLAGS_PERLEXT'] = cfg_lst('$Config{lddlflags}')
env['INCLUDES_PERLEXT'] = cfg_lst('$Config{archlib}/CORE')
env['CFLAGS_PERLEXT'] = cfg_lst('$Config{ccflags} $Config{cccdlflags}')
env['XSUBPP'] = cfg_lst('$Config{privlib}/ExtUtils/xsubpp$Config{exe_ext}')
env['EXTUTILS_TYPEMAP'] = cfg_lst('$Config{privlib}/ExtUtils/typemap')
if not getattr(Options.options, 'perlarchdir', None):
env['ARCHDIR_PERL'] = cfg_str('$Config{sitearch}')
else:
env['ARCHDIR_PERL'] = getattr(Options.options, 'perlarchdir')
env['perlext_PATTERN'] = '%s.' + cfg_str('$Config{dlext}')
def options(opt):
"""
Add the ``--with-perl-archdir`` and ``--with-perl-binary`` command-line options.
"""
opt.add_option('--with-perl-binary', type='string', dest='perlbinary', help = 'Specify alternate perl binary', default=None)
opt.add_option('--with-perl-archdir', type='string', dest='perlarchdir', help = 'Specify directory where to install arch specific files', default=None)
| AltruisticControlSystems/controlnode | waflib/Tools/perl.py | Python | gpl-3.0 | 4,480 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CoursesAPI.Services.Models.Entities
{
class StudentCourseRegistration
{
public int ID { get; set; }
public string SSN { get; set; }
public int CourseInstanceID { get; set; }
public bool Active { get; set; }
}
}
| skulia15/Web-Services | D4/Services/Entities/StudentCourseRegistration.cs | C# | gpl-3.0 | 349 |
<?php
/**
* The wol broadcast page.
*
* PHP version 5
*
* @category WOLBroadcastManagementPage
* @package FOGProject
* @author Tom Elliott <tommygunsster@gmail.com>
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link https://fogproject.org
*/
/**
* The wol broadcast page.
*
* @category WOLBroadcastManagementPage
* @package FOGProject
* @author Tom Elliott <tommygunsster@gmail.com>
* @license http://opensource.org/licenses/gpl-3.0 GPLv3
* @link https://fogproject.org
*/
class WOLBroadcastManagementPage extends FOGPage
{
/**
* The node this page displays with.
*
* @var string
*/
public $node = 'wolbroadcast';
/**
* Initializes the WOL Page.
*
* @param string $name The name to pass with.
*
* @return void
*/
public function __construct($name = '')
{
$this->name = 'WOL Broadcast Management';
self::$foglang['ExportWolbroadcast'] = _('Export WOLBroadcasts');
self::$foglang['ImportWolbroadcast'] = _('Import WOLBroadcasts');
parent::__construct($this->name);
global $id;
if ($id) {
$this->subMenu = array(
"$this->linkformat#wol-general" => self::$foglang['General'],
$this->delformat => self::$foglang['Delete'],
);
$this->notes = array(
_('Broadcast Name') => $this->obj->get('name'),
_('IP Address') => $this->obj->get('broadcast'),
);
}
$this->headerData = array(
'<input type="checkbox" name="toggle-checkbox" class='
. '"toggle-checkboxAction" checked/>',
_('Broadcast Name'),
_('Broadcast IP')
);
$this->templates = array(
'<label for="toggler">'
. '<input type="checkbox" name="wolbroadcast[]" value='
. '"${id}" class="toggle-action" checked/>'
. '</label>',
'<a href="?node=wolbroadcast&sub=edit&id=${id}" title="'
. _('Edit')
. '">${name}</a>',
'${wol_ip}'
);
$this->attributes = array(
array(
'class' => 'filter-false',
'width' => '16'
),
array(),
array()
);
/**
* Lambda function to return data either by list or search.
*
* @param object $WOLBroadcast the object to use
*
* @return void
*/
self::$returnData = function (&$WOLBroadcast) {
$this->data[] = array(
'id' => $WOLBroadcast->id,
'name' => $WOLBroadcast->name,
'wol_ip' => $WOLBroadcast->broadcast,
);
unset($WOLBroadcast);
};
}
/**
* Present page to create new WOL entry.
*
* @return void
*/
public function add()
{
$name = trim(
filter_input(INPUT_POST, 'name')
);
$broadcast = trim(
filter_input(INPUT_POST, 'broadcast')
);
$this->title = _('New Broadcast Address');
unset($this->headerData);
$this->attributes = array(
array('class' => 'col-xs-4'),
array('class' => 'col-xs-8 form-group'),
);
$this->templates = array(
'${field}',
'${input}',
);
$fields = array(
'<label for="name">'
. _('Broadcast Name')
. '</label>' => '<div class="input-group">'
. '<input class="form-control wolinput-name" type='
. '"text" name="name" id="name" required value="'
. $name
. '"/>'
. '</div>',
'<label for="broadcast">'
. _('Broadcast IP')
. '</label>' => '<div class="input-group">'
. '<input class="form-control wolinput-ip" type='
. '"text" name="broadcast" id="broadcast" required value="'
. $broadcast
. '"/>',
'<label for="add">'
. _('Create WOL Broadcast?')
. '</label>' => '<button class="btn btn-info btn-block" name="'
. 'add" id="add" type="submit">'
. _('Create')
. '</button>'
);
array_walk($fields, $this->fieldsToData);
self::$HookManager
->processEvent(
'BROADCAST_ADD',
array(
'headerData' => &$this->headerData,
'data' => &$this->data,
'templates' => &$this->templates,
'attributes' => &$this->attributes
)
);
unset($fields);
echo '<div class="col-xs-9">';
echo '<div class="panel panel-info">';
echo '<div class="panel-heading text-center">';
echo '<h4 class="title">';
echo $this->title;
echo '</h4>';
echo '</div>';
echo '<div class="panel-body">';
echo '<form class="form-horizontal" method="post" action="'
. $this->formAction
. '">';
$this->render(12);
echo '</form>';
echo '</div>';
echo '</div>';
echo '</div>';
}
/**
* Actually create the items.
*
* @return void
*/
public function addPost()
{
self::$HookManager->processEvent('BROADCAST_ADD_POST');
$name = trim(
filter_input(INPUT_POST, 'name')
);
$broadcast = trim(
filter_input(INPUT_POST, 'broadcast')
);
try {
if (!$name) {
throw new Exception(
_('A name is required!')
);
}
if (self::getClass('WolbroadcastManager')->exists($name)) {
throw new Exception(
_('A broadcast already exists with this name!')
);
}
if (!$broadcast) {
throw new Exception(
_('A broadcast address is required')
);
}
if (!filter_var($broadcast, FILTER_VALIDATE_IP)) {
throw new Exception(
_('Please enter a valid ip')
);
}
$WOLBroadcast = self::getClass('Wolbroadcast')
->set('name', $name)
->set('broadcast', $broadcast);
if (!$WOLBroadcast->save()) {
throw new Exception(_('Add broadcast failed!'));
}
$hook = 'BROADCAST_ADD_SUCCESS';
$msg = json_encode(
array(
'msg' => _('Broadcast added!'),
'title' => _('Broadcast Create Success')
)
);
} catch (Exception $e) {
$hook = 'BROADCAST_ADD_FAIL';
$msg = json_encode(
array(
'error' => $e->getMessage(),
'title' => _('Broadcast Create Fail')
)
);
}
self::$HookManager
->processEvent(
$hook,
array('WOLBroadcast' => &$WOLBroadcast)
);
unset($WOLBroadcast);
echo $msg;
exit;
}
/**
* WOL General tab.
*
* @return void
*/
public function wolGeneral()
{
unset(
$this->form,
$this->data,
$this->headerData,
$this->attributes,
$this->templates
);
$name = filter_input(INPUT_POST, 'name') ?:
$this->obj->get('name');
$broadcast = filter_input(INPUT_POST, 'broadcast') ?:
$this->obj->get('broadcast');
$this->title = _('WOL Broadcast General');
$this->attributes = array(
array('class' => 'col-xs-4'),
array('class' => 'col-xs-8 form-group'),
);
$this->templates = array(
'${field}',
'${input}',
);
$fields = array(
'<label for="name">'
. _('Broadcast Name')
. '</label>' => '<div class="input-group">'
. '<input class="form-control wolinput-name" type='
. '"text" name="name" id="name" required value="'
. $name
. '"/>'
. '</div>',
'<label for="broadcast">'
. _('Broadcast IP')
. '</label>' => '<div class="input-group">'
. '<input class="form-control wolinput-ip" type='
. '"text" name="broadcast" id="broadcast" required value="'
. $broadcast
. '"/>',
'<label for="updategen">'
. _('Make Changes?')
. '</label>' => '<button class="btn btn-info btn-block" name="'
. 'updategen" id="updategen" type="submit">'
. _('Update')
. '</button>'
);
array_walk($fields, $this->fieldsToData);
self::$HookManager
->processEvent(
'BROADCAST_EDIT',
array(
'data' => &$this->data,
'headerData' => &$this->headerData,
'attributes' => &$this->attributes,
'templates' => &$this->templates
)
);
unset($fields);
echo '<!-- General -->';
echo '<div class="tab-pane fade in active" id="wol-general">';
echo '<div class="panel panel-info">';
echo '<div class="panel-heading text-center">';
echo '<h4 class="title">';
echo $this->title;
echo '</h4>';
echo '</div>';
echo '<div class="panel-body">';
echo '<form class="form-horizontal" method="post" action="'
. $this->formAction
. '&tab=wol-general">';
$this->render(12);
echo '</form>';
echo '</div>';
echo '</div>';
echo '</div>';
unset(
$this->form,
$this->data,
$this->headerData,
$this->attributes,
$this->templates
);
}
/**
* Edit the current item.
*
* @return void
*/
public function edit()
{
echo '<div class="col-xs-9 tab-content">';
$this->wolGeneral();
echo '</div>';
}
/**
* WOL General Post()
*
* @return void
*/
public function wolGeneralPost()
{
$name = trim(
filter_input(INPUT_POST, 'name')
);
$broadcast = trim(
filter_input(INPUT_POST, 'broadcast')
);
if ($this->obj->get('name') != $name
&& self::getClass('WOLBroadcastManager')->exists(
$name,
$this->obj->get('id')
)
) {
throw new Exception(
_('A broadcast already exists with this name')
);
}
$this->obj
->set('name', $name)
->set('broadcast', $broadcast);
}
/**
* Submit the edits.
*
* @return void
*/
public function editPost()
{
self::$HookManager
->processEvent(
'BROADCAST_EDIT_POST',
array('Broadcast'=> &$this->obj)
);
global $tab;
try {
switch ($tab) {
case 'wol-general':
$this->wolGeneralPost();
break;
}
if (!$this->obj->save()) {
throw new Exception(_('Broadcast update failed!'));
}
$hook = 'BROADCAST_UPDATE_SUCCESS';
$msg = json_encode(
array(
'msg' => _('Broadcast updated!'),
'title' => _('Broadcast Update Success')
)
);
} catch (Exception $e) {
$hook = 'BROADCAST_UPDATE_FAIL';
$msg = json_encode(
array(
'error' => $e->getMessage(),
'title' => _('Broadcast Update Fail')
)
);
}
self::$HookManager
->processEvent(
$hook,
array('WOLBroadcast' => &$this->obj)
);
echo $msg;
exit;
}
}
| Sebastian-Roth/fogproject | packages/web/lib/plugins/wolbroadcast/pages/wolbroadcastmanagementpage.class.php | PHP | gpl-3.0 | 12,420 |
"""
setup.py: Basic setup wizard steps
Copyright 2014-2015, Outernet Inc.
Some rights reserved.
This software is free software licensed under the terms of GPLv3. See COPYING
file that comes with the source code, or http://www.gnu.org/licenses/gpl.txt.
"""
import pytz
from bottle import request, redirect
from ..forms.auth import RegistrationForm
from ..forms.setup import SetupLanguageForm, SetupDateTimeForm
from ..lib import auth
from ..utils.lang import UI_LOCALES, set_default_locale
from ..utils.setup import setup_wizard
def is_language_invalid():
return request.app.setup.get('language') not in UI_LOCALES
@setup_wizard.register_step('language', template='setup/step_language.tpl',
method='GET', index=1, test=is_language_invalid)
def setup_language_form():
return dict(form=SetupLanguageForm())
@setup_wizard.register_step('language', template='setup/step_language.tpl',
method='POST', index=1, test=is_language_invalid)
def setup_language():
form = SetupLanguageForm(request.forms)
if not form.is_valid():
return dict(successful=False, form=form)
lang = form.processed_data['language']
request.app.setup.append({'language': lang})
set_default_locale(lang)
return dict(successful=True, language=lang)
def has_bad_tz():
return request.app.setup.get('timezone') not in pytz.common_timezones
@setup_wizard.register_step('datetime', template='setup/step_datetime.tpl',
method='GET', index=2, test=has_bad_tz)
def setup_datetime_form():
return dict(form=SetupDateTimeForm())
@setup_wizard.register_step('datetime', template='setup/step_datetime.tpl',
method='POST', index=2, test=has_bad_tz)
def setup_datetime():
form = SetupDateTimeForm(request.forms)
if not form.is_valid():
return dict(successful=False, form=form)
timezone = form.processed_data['timezone']
request.app.setup.append({'timezone': timezone})
return dict(successful=True, timezone=timezone)
def has_no_superuser():
db = request.db.sessions
query = db.Select(sets='users', where='is_superuser = ?')
db.query(query, True)
return db.result is None
@setup_wizard.register_step('superuser', template='setup/step_superuser.tpl',
method='GET', index=3, test=has_no_superuser)
def setup_superuser_form():
return dict(form=RegistrationForm())
@setup_wizard.register_step('superuser', template='setup/step_superuser.tpl',
method='POST', index=3, test=has_no_superuser)
def setup_superuser():
form = RegistrationForm(request.forms)
if not form.is_valid():
return dict(successful=False, form=form)
auth.create_user(form.processed_data['username'],
form.processed_data['password1'],
is_superuser=True,
db=request.db.sessions,
overwrite=True)
return dict(successful=True)
def exit_wizard():
next_path = request.params.get('next', '/')
request.app.setup.wizard.exit()
redirect(next_path)
def routes(app):
return (
('setup:main', setup_wizard, ['GET', 'POST'], '/setup/', {}),
('setup:exit', exit_wizard, ['GET'], '/setup/exit/', {}),
)
| karanisverma/feature_langpop | librarian/routes/setup.py | Python | gpl-3.0 | 3,332 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="OrganisationGlAccountBalance.cs" company="Allors bvba">
// Copyright 2002-2012 Allors bvba.
// Dual Licensed under
// a) the General Public Licence v3 (GPL)
// b) the Allors License
// The GPL License is included in the file gpl.txt.
// The Allors License is an addendum to your contract.
// Allors Applications 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.
// For more information visit http://www.allors.com/legal
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Allors.Domain
{
public partial class OrganisationGlAccountBalance
{
public void AppsOnPreDerive(ObjectOnPreDerive method)
{
var derivation = method.Derivation;
if (this.ExistAccountingPeriod)
{
derivation.AddDependency(this, this.AccountingPeriod);
}
}
}
} | Allors/apps | Domains/Apps/Database/Domain/Export/Apps/Accounting/OrganisationGlAccountBalance.cs | C# | gpl-3.0 | 1,249 |
# -*- coding: utf-8 -*-
# Copyright (C) 2014 Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/
#
# 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 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/>.
#
from django.contrib import admin
# Register your models here.
| bioinformatics-ua/catalogue | emif/control_version/admin.py | Python | gpl-3.0 | 834 |
<?php
/**
* The sidebar containing the main widget area.
*
* @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
*
* @package languru
*/
if ( ! is_active_sidebar( 'sidebar-1' ) ) {
return;
}
?>
<aside id="secondary" class="widget-area" role="complementary">
<?php dynamic_sidebar( 'sidebar-1' ); ?>
</aside><!-- #secondary -->
| csbweb/languru | theme/sidebar.php | PHP | gpl-3.0 | 371 |
<?php
declare(strict_types=1);
/*
* (c) 2021 Michael Joyce <mjoyce@sfu.ca>
* This source file is subject to the GPL v2, bundled
* with this source code in the file LICENSE.
*/
namespace App\Services;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
/**
* Service to check the current user's roles.
*/
class RoleChecker {
/**
* @var AuthorizationCheckerInterface
*/
private $authChecker;
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
/**
* RoleChecker constructor.
*/
public function __construct(AuthorizationCheckerInterface $authChecker, TokenStorageInterface $tokenStorage) {
$this->authChecker = $authChecker;
$this->tokenStorage = $tokenStorage;
}
/**
* Check that the current use has the given role.
*
* @param string $role
*
* @return bool
*/
public function hasRole($role) {
if ( ! $this->tokenStorage->getToken()) {
return false;
}
return $this->authChecker->isGranted($role);
}
}
| ubermichael/wphp | src/Services/RoleChecker.php | PHP | gpl-3.0 | 1,189 |
/*
This file is part of Telegram Desktop,
an unofficial desktop messaging app, see https://telegram.org
Telegram Desktop 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.
It 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.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014 John Preston, https://tdesktop.com
*/
#include "stdafx.h"
#include "application.h"
namespace {
void _sendResizeEvents(QWidget *target) {
QResizeEvent e(target->size(), QSize());
QApplication::sendEvent(target, &e);
const QObjectList children = target->children();
for (int i = 0; i < children.size(); ++i) {
QWidget *child = static_cast<QWidget*>(children.at(i));
if (child->isWidgetType() && !child->isWindow() && child->testAttribute(Qt::WA_PendingResizeEvent)) {
_sendResizeEvents(child);
}
}
}
}
QPixmap myGrab(QWidget *target, const QRect &rect) {
if (!cRetina()) return target->grab(rect);
if (target->testAttribute(Qt::WA_PendingResizeEvent) || !target->testAttribute(Qt::WA_WState_Created)) {
_sendResizeEvents(target);
}
qreal dpr = App::app()->devicePixelRatio();
QPixmap result(rect.size() * dpr);
result.setDevicePixelRatio(dpr);
result.fill(Qt::transparent);
target->render(&result, QPoint(), QRegion(rect), QWidget::DrawWindowBackground | QWidget::DrawChildren | QWidget::IgnoreMask);
return result;
}
| gzle/TelegramDesktopKR | Telegram/SourceFiles/gui/twidget.cpp | C++ | gpl-3.0 | 1,857 |
/*
* All Sigmah code is released under the GNU General Public License v3
* See COPYRIGHT.txt and LICENSE.txt.
*/
package org.sigmah.server.report.generator.map;
import org.sigmah.server.domain.SiteData;
import org.sigmah.server.report.generator.MapSymbol;
import org.sigmah.shared.report.content.PieMapMarker;
import org.sigmah.shared.report.content.Point;
import java.awt.*;
import java.util.List;
public class PointValue {
public PointValue() {
}
public PointValue(SiteData site, MapSymbol symbol, double value, Point px) {
this.site = site;
this.symbol = symbol;
this.value = value;
this.px = px;
}
public PointValue(SiteData site, Point px, Rectangle iconRect) {
this.site = site;
this.px = px;
this.iconRect = iconRect;
this.value = 1;
}
public SiteData site;
public MapSymbol symbol;
public double value;
public Point px;
public Rectangle iconRect;
public List<PieMapMarker.Slice> slices;
}
| spMohanty/sigmah_svn_to_git_migration_test | sigmah/src/main/java/org/sigmah/server/report/generator/map/PointValue.java | Java | gpl-3.0 | 1,065 |
#include "files.h"
#include "QDir"
#include "QDebug"
Files::Files()
{
// Users home directory by default
currentDirectory = QDir::homePath();
}
// Get directory given file path(example: /bin/bash returns /bin/)
QString Files::getDirectory(QString filepath){
int lastIndex = filepath.lastIndexOf("/");
filepath.chop(filepath.length() - lastIndex);
return filepath;
}
// Set current directory given most recently opened file
void Files::setCurrentDirectory(QString file){
currentDirectory = getDirectory(file);
}
// Return current directory
QString Files::getCurrentDirectory(){
return currentDirectory;
}
| jubal-R/ObjGui | src/files.cpp | C++ | gpl-3.0 | 639 |
// YAHW - Yet Another Hardware Monitor
// Copyright (c) 2015 Steffen Steinbrecher
// Contact and Information: http://csharp-blog.de/category/yahw/
//
// 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 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/>.
//
// 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.
//
// THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE
using System;
using System.Windows;
using YAHW.Constants;
using YAHW.Interfaces;
namespace YAHW
{
/// <summary>
/// <para>
/// Interaction logic for App.xaml
/// </para>
///
/// <para>
/// Class history:
/// <list type="bullet">
/// <item>
/// <description>1.0: First release, working (Steffen Steinbrecher).</description>
/// </item>
/// </list>
/// </para>
///
/// <para>Author: Steffen Steinbrecher</para>
/// <para>Date: 12.07.2015</para>
/// </summary>
public partial class App : Application
{
public App()
{
this.Startup += App_Startup;
}
private void App_Startup(object sender, StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
DependencyFactory.Resolve<ILoggingService>(ServiceNames.LoggingService).LogException(ex.Message, ex);
DependencyFactory.Resolve<IExceptionReporterService>(ServiceNames.ExceptionReporterService).ReportException(ex);
}
private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
//Handling the exception within the UnhandledException handler.
DependencyFactory.Resolve<ILoggingService>(ServiceNames.LoggingService).LogException(e.Exception.Message, e.Exception);
DependencyFactory.Resolve<IExceptionReporterService>(ServiceNames.ExceptionReporterService).ReportException(e.Exception);
e.Handled = true;
}
}
}
| No3x/YAHW | YAHW/App.xaml.cs | C# | gpl-3.0 | 3,194 |
<?php
/**
* tech-literacy functions and definitions
*
* @package Tech Literacy
*/
if ( ! function_exists( 'tech_literacy_setup' ) ) :
/**
* Sets up theme defaults and registers support for various WordPress features.
*
* Note that this function is hooked into the after_setup_theme hook, which
* runs before the init hook. The init hook is too late for some features, such
* as indicating support for post thumbnails.
*/
function tech_literacy_setup() {
/*
* Make theme available for translation.
* Translations can be filed in the /languages/ directory.
* If you're building a theme based on tech-literacy, use a find and replace
* to change 'tech-literacy' to the name of your theme in all the template files
*/
load_theme_textdomain( 'tech-literacy', get_template_directory() . '/languages' );
// Add default posts and comments RSS feed links to head.
add_theme_support( 'automatic-feed-links' );
/*
* Let WordPress manage the document title.
* By adding theme support, we declare that this theme does not use a
* hard-coded <title> tag in the document head, and expect WordPress to
* provide it for us.
*/
add_theme_support( 'title-tag' );
/*
* Enable support for Post Thumbnails on posts and pages.
*
* @link http://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails
*/
add_theme_support( 'post-thumbnails' );
// This theme uses wp_nav_menu() in one location.
register_nav_menus( array(
'primary' => __( 'Primary Menu', 'tech-literacy' ),
) );
/*
* Switch default core markup for search form, comment form, and comments
* to output valid HTML5.
*/
add_theme_support( 'html5', array(
'comment-list', 'gallery', 'caption',
) );
add_theme_support( 'post-formats', array(
'aside', 'image', 'video', 'quote', 'link',
) );
/**
* Set the content width in pixels, based on the theme's design and stylesheet.
*/
$GLOBALS['content_width'] = apply_filters( 'tech_literacy_content_width', 640 );
// Set up the WordPress core custom background feature.
add_theme_support( 'custom-background', apply_filters( 'tech_literacy_custom_background_args', array(
'default-color' => 'ffffff',
'default-image' => '',
) ) );
/*
* Custom Logo
*/
add_theme_support( 'custom-logo' );
/* Woocommerce support */
add_theme_support('woocommerce');
add_theme_support( 'wc-product-gallery-zoom' );
add_theme_support( 'wc-product-gallery-lightbox' );
add_theme_support( 'wc-product-gallery-slider' );
/*
* Add Additional image sizes
*
*/
add_image_size( 'tech-literacy-small-featured-image-width', 450,300, true );
add_image_size( 'tech-literacy-blog-large-width', 800,300, true );
add_image_size( 'tech-literacy-service-img', 100,100, true );
add_image_size( 'tech-literacy-recent-posts-img', 380,270, true );
// Add theme support for selective refresh for widgets.
add_theme_support( 'customize-selective-refresh-widgets' );
// Define and register starter content to showcase the theme on new sites.
$starter_content = array(
'widgets' => array(
'top-left' => array(
// Widget ID
'my_text' => array(
// Widget $id -> set when creating a Widget Class
'text' ,
// Widget $instance -> settings
array(
'text' => __( '<ul><li><i class="fa fa-envelope-o"></i><a href="mailto:information@mail.com">information@mail.com</a></li> <li><i class="fa fa-phone"></i> Call Us:(1)118 234 678</li></ul>','tech-literacy')
)
)
),
// Put two core-defined widgets in the footer 2 area.
'top-right' => array(
// Widget ID
'my_text' => array(
// Widget $id -> set when creating a Widget Class
'text' ,
// Widget $instance -> settings
array(
'text' => __('<ul><li><a href="#"><i class="fa fa-facebook"></i></a></li><li><a href="#"><i class="fa fa-twitter"></i></a></li><li><a href="#"><i class="fa fa-pinterest"></i></a></li><li><a href="#"><i class="fa fa-tumblr"></i></a></li></ul>','tech-literacy')
)
),
),
'header-top-right' => array(
// Widget ID
'my_text' => array(
// Widget $id -> set when creating a Widget Class
'text' ,
// Widget $instance -> settings
array(
'text' => __( '<i class="fa fa-phone twelve columns"></i><p class="four columns align-left">call us now<br><span class="clr-primary">715.248.1574</span></p>','tech-literacy')
)
)
),
'footer' => array(
// Widget ID
'my_text' => array(
// Widget $id -> set when creating a Widget Class
'text' ,
// Widget $instance -> settings
array(
'title' => __( 'About Theme', 'tech-literacy'),
'text' => __( 'Tech Literacy is a free, clean, minimalistic, responsive, mobile-friendly WordPress theme. Tech Literacy suitable for education, literacy websites, online stores, personal portfolio, agencies, start-ups and many others.', 'tech-literacy'),
)
)
),
'footer-2' => array(
// Widget ID
'archives'
),
'footer-3' => array(
// Widget ID
'categories'
),
'footer-nav' => array(
// Widget ID
'my_text' => array(
// Widget $id -> set when creating a Widget Class
'text' ,
// Widget $instance -> settings
array(
'text' => '<ul><li><a href="#"><i class="fa fa-facebook"></i></a></li><li><a href="#"><i class="fa fa-twitter"></i></a></li><li><a href="#"><i class="fa fa-pinterest"></i></a></li><li><a href="#"><i class="fa fa-tumblr"></i></a></li></ul>'
)
),
),
),
// Specify the core-defined pages to create and add custom thumbnails to some of them.
'posts' => array(
'home' => array(
'post_type' => 'page',
),
'blog' => array(
'post_type' => 'page',
),
'post-one' => array(
'post_type' => 'post',
'post_title' => __( 'Lorem Ipsum', 'tech-literacy'),
'post_content' => __( 'Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Aenean lacinia bibendum nulla sed consectetur', 'tech-literacy'),
'thumbnail' => '{{post-featured-image1}}',
),
'post-two' => array(
'post_type' => 'post',
'post_title' => __( 'Lorem Ipsum', 'tech-literacy'),
'post_content' => __( 'Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Aenean lacinia bibendum nulla sed consectetur', 'tech-literacy'),
'thumbnail' => '{{post-featured-image2}}',
),
'post-three' => array(
'post_type' => 'post',
'post_title' => __( 'Lorem Ipsum', 'tech-literacy'),
'post_content' => __( 'Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Aenean lacinia bibendum nulla sed consectetur', 'tech-literacy'),
'thumbnail' => '{{post-featured-image3}}',
),
'service-one' => array(
'post_type' => 'page',
'post_title' => __( 'Service 1', 'tech-literacy'),
'post_content' => __('You haven\'t created any service page yet. Create Page. Go to Customizer and click Theme Options => Home => Service Section #1 and select page from dropdown page list.<!--more-->','tech-literacy'),
'thumbnail' => '{{page-images}}',
),
'service-two' => array(
'post_type' => 'page',
'post_title' => __( 'Service 2', 'tech-literacy'),
'post_content' => __('You haven\'t created any service page yet. Create Page. Go to Customizer and click Theme Options => Home => Service Section #1 and select page from dropdown page list.<!--more-->','tech-literacy'),
'thumbnail' => '{{page-images}}',
),
'service-three' => array(
'post_type' => 'page',
'post_title' => __( 'Service 3', 'tech-literacy'),
'post_content' => __('You haven\'t created any service page yet. Create Page. Go to Customizer and click Theme Options => Home => Service Section #1 and select page from dropdown page list.<!--more-->','tech-literacy'),
'thumbnail' => '{{page-images}}',
),
),
// Create the custom image attachments used as post thumbnails for pages.
'attachments' => array(
'post-featured-image1' => array(
'post_title' => __( 'blog one', 'tech-literacy' ),
'file' => 'images/blog1.png', // URL relative to the template directory.
),
'post-featured-image2' => array(
'post_title' => __( 'blog one', 'tech-literacy' ),
'file' => 'images/blog2.png', // URL relative to the template directory.
),
'post-featured-image3' => array(
'post_title' => __( 'blog one', 'tech-literacy' ),
'file' => 'images/blog3.png', // URL relative to the template directory.
),
'page-images' => array(
'post_title' => __( 'Page Images', 'tech-literacy' ),
'file' => 'images/page.png', // URL relative to the template directory.
),
),
// Default to a static front page and assign the front and posts pages.
'options' => array(
'show_on_front' => 'page',
'page_on_front' => '{{home}}',
'page_for_posts' => '{{blog}}',
),
// Set the front page section theme mods to the IDs of the core-registered pages.
'theme_mods' => array(
'service_1' => '{{service-one}}',
'service_2' => '{{service-two}}',
'service_3' => '{{service-three}}',
'service_section_icon_1' => 'fa-user',
'service_section_icon_2' => 'fa-heart',
'service_section_icon_3' => 'fa-apple',
),
);
$starter_content = apply_filters( 'tech_literacy_starter_content', $starter_content );
add_theme_support( 'starter-content', $starter_content );
}
endif; // tech_literacy_setup
add_action( 'after_setup_theme', 'tech_literacy_setup' );
/**
* Register widget area.
*
* @link http://codex.wordpress.org/Function_Reference/register_sidebar
*/
function tech_literacy_widgets_init() {
register_sidebar( array(
'name' => __( 'Sidebar', 'tech-literacy' ),
'id' => 'sidebar-1',
'description' => '',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>',
) );
register_sidebar( array(
'name' => __( 'Top Left', 'tech-literacy' ),
'id' => 'top-left',
'description' => '',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>',
) );
register_sidebar( array(
'name' => __( 'Top Right', 'tech-literacy' ),
'id' => 'top-right',
'description' => '',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>',
) );
register_sidebar( array(
'name' => __( 'Header Top Right', 'tech-literacy' ),
'id' => 'header-top-right',
'description' => '',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>',
) );
register_sidebars( 3, array(
'name' => __( 'Footer %d', 'tech-literacy' ),
'id' => 'footer',
'description' => '',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>',
) );
register_sidebar( array(
'name' => __( 'Footer Nav', 'tech-literacy' ),
'id' => 'footer-nav',
'description' => '',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>',
) );
}
add_action( 'widgets_init', 'tech_literacy_widgets_init' );
/**
* Enqueue scripts and styles.
*/
require get_template_directory() . '/includes/enqueue.php';
/**
* Custom template tags for this theme.
*/
require get_template_directory() . '/includes/template-tags.php';
/**
* Custom functions that act independently of the theme templates.
*/
require get_template_directory() . '/includes/extras.php';
/**
* Implement the Custom Header feature.
*/
require get_template_directory() . '/includes/custom-header.php';
/**
* Customizer additions.
*/
require get_template_directory() . '/includes/customizer.php';
/**
* Load Jetpack compatibility file.
*/
require get_template_directory() . '/includes/jetpack.php';
/**
* Load Theme Options Panel
*/
require get_template_directory() . '/includes/theme-options.php';
/* Woocommerce support */
remove_action('woocommerce_before_main_content', 'woocommerce_output_content_wrapper');
add_action('woocommerce_before_main_content', 'tech_literacy_output_content_wrapper');
function tech_literacy_output_content_wrapper() {
echo '<div class="container"><div class="row"><div id="primary" class="content-area eleven columns">';
}
remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end' );
add_action( 'woocommerce_after_main_content', 'tech_literacy_output_content_wrapper_end' );
function tech_literacy_output_content_wrapper_end () {
echo "</div>";
}
add_action( 'wp_head', 'tech_literacy_remove_wc_breadcrumbs' );
function tech_literacy_remove_wc_breadcrumbs() {
remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0 );
}
| venkatraj/tech-literacy | functions.php | PHP | gpl-3.0 | 13,546 |
using Rubberduck.Refactorings;
using Rubberduck.Refactorings.ExtractInterface;
using Rubberduck.Resources;
namespace Rubberduck.UI.Refactorings.ExtractInterface
{
internal class ExtractInterfacePresenter : RefactoringPresenterBase<ExtractInterfaceModel>, IExtractInterfacePresenter
{
private static readonly DialogData DialogData = DialogData.Create(RubberduckUI.ExtractInterface_Caption, 339, 459);
public ExtractInterfacePresenter(ExtractInterfaceModel model,
IRefactoringDialogFactory dialogFactory) : base(DialogData, model, dialogFactory) { }
public override ExtractInterfaceModel Show()
{
if (Model.TargetDeclaration == null)
{
return null;
}
var model = base.Show();
return DialogResult != RefactoringDialogResult.Execute ? null : model;
}
}
}
| IvenBach/Rubberduck | Rubberduck.Core/UI/Refactorings/ExtractInterface/ExtractInterfacePresenter.cs | C# | gpl-3.0 | 898 |
<!-- /**
* Project Name: FrozenBlade V2 Enhanced"
* Date: 25.07.2008 inital version
* Coded by: Furt
* Template by: Kitten - wowps forums
* Email: *****
* License: GNU General Public License (GPL)
*/ -->
<td width="574" valign="top">
<div class="story-top8">
<div align="center" style="text-align:bottom"><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<!-- Header Text Image -->
<img src="images/text/connect.png">
</div></div><div class="story2"><center><div style="width:400px; text-align:left"><br>
<!-- Introduction Line -->
This guide will show you how to configure your World of Warcraft client so you can play on our server.
<br><br><center><img src="images/temp/br.png"></center>
<!-- Install World of Warcraft -->
<img src="images/temp/icon.gif"><strong> Install World of Warcraft</strong><br><br>
First you must make sure you have World of Warcaft and both expansions installed.<br><br>
You can get this either by buying it in gaming shops or you will find that there are downloads around which can be found.<br><br>
Here is the direct installer for classic and both expansions:<br><br>
<!-- Official Installers Download Links -->
<center><a href="download/InstallWoW.exe" onMouseOver="image1.src='images/text/wow-installer2.png'" onMouseOut="image1.src='images/text/wow-installer.png'"><img src="images/text/wow-installer.png"; name="image1" border="0"></a><br /><br /><img src="images/temp/br.png"></center>
<!-- Download and Install Patches -->
<img src="images/temp/icon.gif"><strong> Download and Install Patches</strong><br><br>
To make sure your client is running the same supported version as our server you need to install some patches.<br /><br />
<!-- Enter Your Supported Version Here -->
<center><font color="#FFFFFF"> Supported Version: <?php echo $config['PatchVersion']; ?> </font></center><br>
<!-- Patch Download Links -->
You can use your World of Warcraft client to download your patches automatically, or your can download them manually from here:<br/><br/>
<center><a href="http://www.wowwiki.com/Patch_mirrors" onMouseOver="image2.src='images/text/wiki.png'" onMouseOut="image2.src='images/text/wiki2.png'"><img src="images/text/wiki2.png"; name="image2" border="0"></a><br /><br /><img src="images/temp/br.png"></center>
<!-- Change Your Realmlist -->
<img src="images/temp/icon.gif"><strong> Change Your Realmlist</strong><br><br>
Now go to the folder which you installed World of Warcraft, open the file called: 'realmlist.wtf' with Notepad and change it to say:<br/><br/>
<!-- Put Your Server Realmlist Here -->
<center><font color="#FFFFFF"> set realmlist <?php echo $config['RealmIP']; ?> </font><br/><br/></center>
Then save the file and close.<br><br>
Do you play more than one WoW server and want no more realmlists? then check out this awesome program:<br/><br/>
<!-- Advertising Virtue: Realmlister -->
<center><a href="http://virtue.nadasoft.net/"><img src="images/temp/virtue.png" border="0"></a><br/><br/>
<img src="images/temp/br.png"></center>
<!-- Make Your Server Account -->
<img src="images/temp/icon.gif"><strong> Make Your Server Account</strong><br><br>
You can now make your account on our Registration page.<br><br>
Once that is done, you are all ready to log in with your account information and get playing!<br><br>
Please wait up to at most 10 minutes before your new account will be loaded into our the logon server.
</div></center></div><div class="story-bot2"></div><br /></td> | Furt/frozenbladev2enhanced | MaNGOS/pages/connect.php | PHP | gpl-3.0 | 3,638 |
package turtle.interpreterPattern.command;
import turtle.Turtle;
import turtle.interpreterPattern.visitorPattern.ICommandVisitor;
public class Turn extends Command {
private double direction;
public Turn(double direction) {
this.direction = direction;
}
@Override
public String type() {
return "turn";
}
@Override
public void execute(Turtle aTurtle) {
double currentDirection = aTurtle.getDirection();
aTurtle.setDirection(currentDirection + direction);
}
@Override
public void accept(ICommandVisitor anICommandVisitor, Turtle aTurtle) {
anICommandVisitor.visit(this, aTurtle);
}
}
| LokeshSreekanta/TurtleGraphicsDesignPatterns | src/turtle/interpreterPattern/command/Turn.java | Java | gpl-3.0 | 610 |
/*
Copyright (C) 2014-2019 de4dot@gmail.com
This file is part of dnSpy
dnSpy 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.
dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>.
*/
using dnSpy.Contracts.TreeView;
namespace dnSpy.Contracts.Documents.TreeView {
/// <summary>
/// Default <see cref="ITreeNodeGroup"/> instances
/// </summary>
public enum DocumentTreeNodeGroupType {
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
AssemblyRefTreeNodeGroupReferences,
AssemblyRefTreeNodeGroupAssemblyRef,
ModuleRefTreeNodeGroupReferences,
ReferencesFolderTreeNodeGroupModule,
ResourcesFolderTreeNodeGroupModule,
NamespaceTreeNodeGroupModule,
TypeTreeNodeGroupNamespace,
TypeTreeNodeGroupType,
BaseTypeFolderTreeNodeGroupType,
BaseTypeTreeNodeGroupBaseType,
InterfaceBaseTypeTreeNodeGroupBaseType,
DerivedTypesFolderTreeNodeGroupType,
MessageTreeNodeGroupDerivedTypes,
DerivedTypeTreeNodeGroupDerivedTypes,
MethodTreeNodeGroupType,
MethodTreeNodeGroupProperty,
MethodTreeNodeGroupEvent,
FieldTreeNodeGroupType,
EventTreeNodeGroupType,
PropertyTreeNodeGroupType,
ResourceTreeNodeGroup,
ResourceElementTreeNodeGroup,
TypeReferenceTreeNodeGroupTypeReferences,
TypeSpecsFolderTreeNodeGroupTypeReference,
MethodReferencesFolderTreeNodeGroupTypeReference,
PropertyReferencesFolderTreeNodeGroupTypeReference,
EventReferencesFolderTreeNodeGroupTypeReference,
FieldReferencesFolderTreeNodeGroupTypeReference,
TypeSpecTreeNodeGroupTypeSpecsFolder,
MethodReferenceTreeNodeGroupMethodReferencesFolder,
PropertyReferenceTreeNodeGroupPropertyReferencesFolder,
EventReferenceTreeNodeGroupEventReferencesFolder,
FieldReferenceTreeNodeGroupFieldReferencesFolder,
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
}
| manojdjoshi/dnSpy | dnSpy/dnSpy.Contracts.DnSpy/Documents/TreeView/DocumentTreeNodeGroupType.cs | C# | gpl-3.0 | 2,384 |
/*
Copyright (C) 2014-2019 de4dot@gmail.com
This file is part of dnSpy
dnSpy 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.
dnSpy 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 dnSpy. If not, see <http://www.gnu.org/licenses/>.
*/
using VSTE = Microsoft.VisualStudio.Text.Editor;
namespace dnSpy.Contracts.Hex.Editor {
/// <summary>
/// Default <see cref="HexView"/> options
/// </summary>
public static class DefaultHexViewOptions {
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public const string ShowOffsetColumnName = "HexView/ShowOffsetColumn";
public static readonly VSTE.EditorOptionKey<bool> ShowOffsetColumnId = new VSTE.EditorOptionKey<bool>(ShowOffsetColumnName);
public const string ShowValuesColumnName = "HexView/ShowValuesColumn";
public static readonly VSTE.EditorOptionKey<bool> ShowValuesColumnId = new VSTE.EditorOptionKey<bool>(ShowValuesColumnName);
public const string ShowAsciiColumnName = "HexView/ShowAsciiColumn";
public static readonly VSTE.EditorOptionKey<bool> ShowAsciiColumnId = new VSTE.EditorOptionKey<bool>(ShowAsciiColumnName);
public const string StartPositionName = "HexView/StartPosition";
public static readonly VSTE.EditorOptionKey<HexPosition> StartPositionId = new VSTE.EditorOptionKey<HexPosition>(StartPositionName);
public const string EndPositionName = "HexView/EndPosition";
public static readonly VSTE.EditorOptionKey<HexPosition> EndPositionId = new VSTE.EditorOptionKey<HexPosition>(EndPositionName);
public const string BasePositionName = "HexView/BasePosition";
public static readonly VSTE.EditorOptionKey<HexPosition> BasePositionId = new VSTE.EditorOptionKey<HexPosition>(BasePositionName);
public const string UseRelativePositionsName = "HexView/UseRelativePositions";
public static readonly VSTE.EditorOptionKey<bool> UseRelativePositionsId = new VSTE.EditorOptionKey<bool>(UseRelativePositionsName);
public const string OffsetBitSizeName = "HexView/OffsetBitSize";
public static readonly VSTE.EditorOptionKey<int> OffsetBitSizeId = new VSTE.EditorOptionKey<int>(OffsetBitSizeName);
public const string HexValuesDisplayFormatName = "HexView/HexValuesDisplayFormat";
public static readonly VSTE.EditorOptionKey<HexValuesDisplayFormat> HexValuesDisplayFormatId = new VSTE.EditorOptionKey<HexValuesDisplayFormat>(HexValuesDisplayFormatName);
public const string HexOffsetFormatName = "HexView/HexOffsetFormat";
public static readonly VSTE.EditorOptionKey<HexOffsetFormat> HexOffsetFormatId = new VSTE.EditorOptionKey<HexOffsetFormat>(HexOffsetFormatName);
public const string ValuesLowerCaseHexName = "HexView/ValuesLowerCaseHex";
public static readonly VSTE.EditorOptionKey<bool> ValuesLowerCaseHexId = new VSTE.EditorOptionKey<bool>(ValuesLowerCaseHexName);
public const string OffsetLowerCaseHexName = "HexView/OffsetLowerCaseHex";
public static readonly VSTE.EditorOptionKey<bool> OffsetLowerCaseHexId = new VSTE.EditorOptionKey<bool>(OffsetLowerCaseHexName);
public const string BytesPerLineName = "HexView/BytesPerLine";
public static readonly VSTE.EditorOptionKey<int> BytesPerLineId = new VSTE.EditorOptionKey<int>(BytesPerLineName);
public const string GroupSizeInBytesName = "HexView/GroupSizeInBytes";
public static readonly VSTE.EditorOptionKey<int> GroupSizeInBytesId = new VSTE.EditorOptionKey<int>(GroupSizeInBytesName);
public const string EnableColorizationName = "HexView/EnableColorization";
public static readonly VSTE.EditorOptionKey<bool> EnableColorizationId = new VSTE.EditorOptionKey<bool>(EnableColorizationName);
public const string ViewProhibitUserInputName = "HexView/ProhibitUserInput";
public static readonly VSTE.EditorOptionKey<bool> ViewProhibitUserInputId = new VSTE.EditorOptionKey<bool>(ViewProhibitUserInputName);
public const string RefreshScreenOnChangeName = "HexView/RefreshScreenOnChange";
public static readonly VSTE.EditorOptionKey<bool> RefreshScreenOnChangeId = new VSTE.EditorOptionKey<bool>(RefreshScreenOnChangeName);
public const string RefreshScreenOnChangeWaitMilliSecondsName = "HexView/RefreshScreenOnChangeWaitMilliSeconds";
public static readonly VSTE.EditorOptionKey<int> RefreshScreenOnChangeWaitMilliSecondsId = new VSTE.EditorOptionKey<int>(RefreshScreenOnChangeWaitMilliSecondsName);
public const int DefaultRefreshScreenOnChangeWaitMilliSeconds = 150;
public const string RemoveExtraTextLineVerticalPixelsName = "HexView/RemoveExtraTextLineVerticalPixels";
public static readonly VSTE.EditorOptionKey<bool> RemoveExtraTextLineVerticalPixelsId = new VSTE.EditorOptionKey<bool>(RemoveExtraTextLineVerticalPixelsName);
public const string ShowColumnLinesName = "HexView/ShowColumnLines";
public static readonly VSTE.EditorOptionKey<bool> ShowColumnLinesId = new VSTE.EditorOptionKey<bool>(ShowColumnLinesName);
public const string ColumnLine0Name = "HexView/ColumnLine0";
public static readonly VSTE.EditorOptionKey<HexColumnLineKind> ColumnLine0Id = new VSTE.EditorOptionKey<HexColumnLineKind>(ColumnLine0Name);
public const string ColumnLine1Name = "HexView/ColumnLine1";
public static readonly VSTE.EditorOptionKey<HexColumnLineKind> ColumnLine1Id = new VSTE.EditorOptionKey<HexColumnLineKind>(ColumnLine1Name);
public const string ColumnGroupLine0Name = "HexView/ColumnGroupLine0";
public static readonly VSTE.EditorOptionKey<HexColumnLineKind> ColumnGroupLine0Id = new VSTE.EditorOptionKey<HexColumnLineKind>(ColumnGroupLine0Name);
public const string ColumnGroupLine1Name = "HexView/ColumnGroupLine1";
public static readonly VSTE.EditorOptionKey<HexColumnLineKind> ColumnGroupLine1Id = new VSTE.EditorOptionKey<HexColumnLineKind>(ColumnGroupLine1Name);
public const string HighlightActiveColumnName = "HexView/HighlightActiveColumn";
public static readonly VSTE.EditorOptionKey<bool> HighlightActiveColumnId = new VSTE.EditorOptionKey<bool>(HighlightActiveColumnName);
public const string HighlightCurrentValueName = "HexView/HighlightCurrentValue";
public static readonly VSTE.EditorOptionKey<bool> HighlightCurrentValueId = new VSTE.EditorOptionKey<bool>(HighlightCurrentValueName);
public const string HighlightCurrentValueDelayMilliSecondsName = "HexView/HighlightCurrentValueDelayMilliSeconds";
public static readonly VSTE.EditorOptionKey<int> HighlightCurrentValueDelayMilliSecondsId = new VSTE.EditorOptionKey<int>(HighlightCurrentValueDelayMilliSecondsName);
public const int DefaultHighlightCurrentValueDelayMilliSeconds = 100;
public const string EncodingCodePageName = "HexView/EncodingCodePage";
public static readonly VSTE.EditorOptionKey<int> EncodingCodePageId = new VSTE.EditorOptionKey<int>(EncodingCodePageName);
public const string HighlightStructureUnderMouseCursorName = "HexView/HighlightStructureUnderMouseCursor";
public static readonly VSTE.EditorOptionKey<bool> HighlightStructureUnderMouseCursorId = new VSTE.EditorOptionKey<bool>(HighlightStructureUnderMouseCursorName);
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
}
| manojdjoshi/dnSpy | dnSpy/dnSpy.Contracts.DnSpy/Hex/Editor/DefaultHexViewOptions.cs | C# | gpl-3.0 | 7,568 |
<?php
/**
* @package elysio-template
* @copyright Copyright (C) 2015 Timble CVBA (http://www.timble.net)
*/
// No direct access
defined('_JEXEC') or die;
// Connect with Joomla
$app = JFactory::getApplication();
$doc = JFactory::getDocument();
$menu = $app->getMenu();
// Getting params from template
$params = JFactory::getApplication()->getTemplate(true)->params;
// Detecting Active Variables
$option = $app->input->getCmd('option', '');
$view = $app->input->getCmd('view', '');
$layout = $app->input->getCmd('layout', '');
$task = $app->input->getCmd('task', '');
$itemid = $app->input->getCmd('Itemid', '');
$sitename = $app->getCfg('sitename');
$menuactive = $menu->getActive();
$debug = $app->getCfg('debug', 0);
$cpanel = ($option === 'com_cpanel');
// Set MetaData
$doc->setCharset('utf8');
$doc->setGenerator($sitename);
$doc->setMetaData('viewport', 'width=device-width, initial-scale=1.0');
$doc->setMetaData('mobile-web-app-capable', 'yes');
$doc->setMetaData('apple-mobile-web-app-capable', 'yes');
$doc->setMetaData('apple-mobile-web-app-status-bar-style', 'black');
$doc->setMetaData('apple-mobile-web-app-title', 'Elysio');
$doc->setMetaData('X-UA-Compatible', 'IE=edge', true);
// Set links
$doc->addHeadLink($params->get('logo').'.ico', 'shortcut icon', 'rel', array('type' => 'image/ico'));
$doc->addHeadLink($params->get('logo').'.png', 'shortcut icon', 'rel', array('type' => 'image/png', "sizes" => "192x192"));
// Add Stylesheets
$doc->addStyleSheet('templates/' . $this->template . '/css/admin.css');
// Add Script
$doc->addScript('templates/'.$this->template.'/js/modernizr.js', 'text/javascript');
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" dir="<?php echo $this->direction; ?>">
<head>
<jdoc:include type="head" />
</head>
<body class="no-js">
<script type="text/javascript">function hasClass(e,t){return e.className.match(new RegExp("(\\s|^)"+t+"(\\s|$)"))}var el=document.body;var cl="no-js";if(hasClass(el,cl)){var reg=new RegExp("(\\s|^)"+cl+"(\\s|$)");el.className=el.className.replace(reg," k-js-enabled")}</script>
<!-- Koowa -->
<div class="k-ui-namespace k-ui-container">
<!-- Wrapper -->
<div class="k-wrapper k-js-wrapper">
<!-- Login container -->
<div class="k-login-container">
<!-- Login -->
<div class="k-login">
<div class="k-login__brand">
<?php if ($params->get('logo')) : ?>
<img src="<?php echo $params->get('logo'); ?>" alt="<?php echo $sitename; ?>" />
<?php else: ?>
<img src="<?php echo $this->baseurl; ?>/templates/<?php echo $this->template; ?>/images/platform-logo.png" alt="<?php echo $sitename; ?>" />
<?php endif; ?>
</div>
<div class="k-login__content">
<jdoc:include type="message" />
<jdoc:include type="component" />
</div>
</div>
</div><!-- .k-login-container -->
</div><!-- .k-wrapper -->
</div>
<script type="text/javascript">
// Autofocus on the login field
jQuery(function($) {
$( "#form-login input[name='username']" ).focus();
});
</script>
</body>
</html> | joomlatools/joomla-platform | web/administrator/templates/elysio/login.php | PHP | gpl-3.0 | 3,360 |
using FluentMigrator;
using NzbDrone.Core.Datastore.Migration.Framework;
namespace NzbDrone.Core.Datastore.Migration
{
[Migration(42)]
public class add_download_clients_table : NzbDroneMigrationBase
{
protected override void MainDbUpgrade()
{
Create.TableForModel("DownloadClients")
.WithColumn("Enable").AsBoolean().NotNullable()
.WithColumn("Name").AsString().NotNullable()
.WithColumn("Implementation").AsString().NotNullable()
.WithColumn("Settings").AsString().NotNullable()
.WithColumn("ConfigContract").AsString().NotNullable()
.WithColumn("Protocol").AsInt32().NotNullable();
}
}
}
| jamesmacwhite/Radarr | src/NzbDrone.Core/Datastore/Migration/042_add_download_clients_table.cs | C# | gpl-3.0 | 754 |
/*
* Quasar: lightweight threads and actors for the JVM.
* Copyright (c) 2013-2014, Parallel Universe Software Co. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 3.0
* as published by the Free Software Foundation.
*/
package co.paralleluniverse.strands.channels;
/**
* An empty super-interface of {@link SendPort} and {@link ReceivePort} extend.
*
* @author pron
*/
public interface Port<Message> {
}
| tbrooks8/quasar | quasar-core/src/main/java/co/paralleluniverse/strands/channels/Port.java | Java | gpl-3.0 | 672 |
/*
* 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 "PbfInputSplit.h"
// Hoot
#include <hoot/core/util/Log.h>
// Pretty Pipes
#include <pp/DataInputStream.h>
#include <pp/DataOutputStream.h>
#include <pp/Factory.h>
// Standard
#include <sstream>
#include <stdio.h>
#include <string.h>
namespace hoot
{
using namespace pp;
PP_FACTORY_REGISTER(pp::InputSplit, PbfInputSplit)
PbfInputSplit::PbfInputSplit()
{
reset();
}
PbfInputSplit::PbfInputSplit(const PbfInputSplit& from)
{
_copy(from);
}
void PbfInputSplit::_copy(const PbfInputSplit& from)
{
_start = from._start;
_length = from._length;
_headers = from._headers;
_locations = from._locations;
_path = from._path;
}
void PbfInputSplit::addHeader(long pos, long length)
{
if (_start == -1)
{
_start = pos;
_length = 0;
}
_length = std::max(_length, (pos + length) - _start);
_headers.push_back(pos);
}
void PbfInputSplit::readFields(char *byteArray, long len)
{
string s(byteArray, (size_t)len);
stringstream sin(s, stringstream::in);
DataInputStream dis(sin);
_start = dis.readLong();
_length = dis.readLong();
_path = dis.readString();
_locations = dis.readString();
int headerCount = dis.readInt();
for (int i = 0; i < headerCount; i++)
{
long h = dis.readLong();
_headers.push_back(h);
}
}
void PbfInputSplit::reset()
{
_start = -1;
_length = 0;
_headers.clear();
_path.clear();
_locations.clear();
}
signed char* PbfInputSplit::writeFields(size_t* len) const
{
stringstream sout(stringstream::out);
DataOutputStream dos(sout);
dos.writeLong(_start);
dos.writeLong(_length);
dos.writeString(_path);
dos.writeString(_locations);
dos.writeInt(_headers.size());
for (size_t i = 0; i < _headers.size(); i++)
{
dos.writeLong(_headers.at(i));
}
sout.flush();
*len = sout.str().length();
signed char* result = new signed char[*len];
memcpy(result, sout.str().data(), *len);
return result;
}
}
| nstarke/hootenanny | hoot-hadoop/src/main/cpp/hoot/hadoop/PbfInputSplit.cpp | C++ | gpl-3.0 | 2,646 |
#ifndef QUAN_OSD_DYNAMIC_DISPLAY_DEVICE_HPP_INCLUDED
#define QUAN_OSD_DYNAMIC_DISPLAY_DEVICE_HPP_INCLUDED
#include <quan/uav/osd/api.hpp>
namespace quan{ namespace uav{ namespace osd {namespace dynamic{
struct display_device{
typedef quan::uav::osd::pxp_type pxp_type;
typedef quan::uav::osd::colour_type colour_type;
typedef quan::uav::osd::size_type size_type;
virtual pxp_type transform_to_raw(pxp_type const & pos)const = 0;
virtual pxp_type transform_from_raw(pxp_type const & pos) const = 0;
virtual void set_pixel_raw(pxp_type const & px,colour_type c) = 0;
virtual colour_type get_pixel_raw(pxp_type const & px) const=0;
virtual bool set_clip_rect(pxp_type const & minimums,
pxp_type const & maximums)=0;
virtual void set_display_buffer(uint32_t offset32,uint32_t mask,colour_type c)=0;
virtual size_type get_display_size()const = 0;
// protected:
display_device(){}
virtual ~display_device(){}
private:
display_device (display_device const &) = delete;
display_device & operator = (display_device const &) = delete;
};
}}}}
#endif // QUAN_OSD_DYNAMIC_DISPLAY_DEVICE_HPP_INCLUDED
| andrewfernie/quan-trunk | quan/uav/osd/dynamic/display_device.hpp | C++ | gpl-3.0 | 1,286 |
<?php
/*
Gibbon, Flexible & Open School System
Copyright (C) 2010, Ross Parker
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 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/>.
*/
use Gibbon\FileUploader;
use Gibbon\Data\Validator;
use Gibbon\Module\Reports\Domain\ReportTemplateGateway;
use Gibbon\Module\Reports\Domain\ReportTemplateSectionGateway;
require_once '../../gibbon.php';
$_POST = $container->get(Validator::class)->sanitize($_POST, ['templateContent' => 'RAW']);
$gibbonReportTemplateID = $_POST['gibbonReportTemplateID'] ?? '';
$gibbonReportTemplateSectionID = $_POST['gibbonReportTemplateSectionID'] ?? '';
$search = $_GET['search'] ?? '';
$URL = $gibbon->session->get('absoluteURL').'/index.php?q=/modules/Reports/templates_manage_section_edit.php&gibbonReportTemplateID='.$gibbonReportTemplateID.'&gibbonReportTemplateSectionID='.$gibbonReportTemplateSectionID.'&search='.$search;
if (isActionAccessible($guid, $connection2, '/modules/Reports/templates_manage_section_edit.php') == false) {
$URL .= '&return=error0';
header("Location: {$URL}");
exit;
} else {
// Proceed!
$templateGateway = $container->get(ReportTemplateGateway::class);
$templateSectionGateway = $container->get(ReportTemplateSectionGateway::class);
$config = $_POST['config'] ?? [];
$data = [
'name' => $_POST['name'] ?? '',
'page' => $_POST['pageCustom'] ?? $_POST['page'] ?? '',
'templateParams' => json_encode($_POST['templateParams'] ?? []),
'templateContent' => $_POST['templateContent'] ?? '',
];
// Handle bitwise flags
if (!empty($_POST['flags']) && is_array($_POST['flags'])) {
$data['flags'] = array_reduce($_POST['flags'], function ($group, $item) {
return $group |= $item;
}, 0);
} else {
$data['flags'] = 0;
}
// Handle file uploads for custom config fields
foreach ($config ?? [] as $configName => $configValue) {
if (!empty($_FILES['config']['tmp_name'][$configName])) {
$file = array_reduce(array_keys($_FILES['config']), function ($group, $itemName) use ($configName) {
$group[$itemName] = $_FILES['config'][$itemName][$configName] ?? null;
return $group;
}, []);
// Upload the file, return the /uploads relative path
$fileUploader = empty($fileUploader) ? new FileUploader($pdo, $gibbon->session) : $fileUploader;
$config[$configName] = $fileUploader->uploadFromPost($file, $configName.'_file');
}
}
$data['config'] = json_encode($config);
// Validate the required values are present
if (empty($gibbonReportTemplateID) || empty($gibbonReportTemplateSectionID) || empty($data['name'])) {
$URL .= '&return=error1';
header("Location: {$URL}");
exit;
}
$result = $templateSectionGateway->selectBy([
'gibbonReportTemplateID' => $gibbonReportTemplateID,
'gibbonReportTemplateSectionID' => $gibbonReportTemplateSectionID,
]);
// Validate the database relationships exist
if ($result->rowCount() == 0) {
$URL .= '&return=error2';
header("Location: {$URL}");
exit;
}
// Update the record
$updated = $templateSectionGateway->update($gibbonReportTemplateSectionID, $data);
$URL .= !$updated
? "&return=error2"
: "&return=success0";
header("Location: {$URL}&editID=$updated");
}
| GibbonEdu/core | modules/Reports/templates_manage_section_editProcess.php | PHP | gpl-3.0 | 4,007 |
<?php
/* Copyright (C) 2012 Regis Houssin <regis.houssin@capnetworks.com>
*
* 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 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/>.
*/
$bills = array(
'CHARSET' => 'UTF-8',
'Bill' => 'Invoice',
'Bills' => 'Invoices',
'BillsCustomers' => 'Customer\'s invoices',
'BillsCustomer' => 'Customer\'s invoice',
'BillsSuppliers' => 'Supplier\'s invoices',
'BillsCustomersUnpaid' => 'Unpaid customer\'s invoices',
'BillsCustomersUnpaidForCompany' => 'Unpaid customer\'s invoices for %s',
'BillsSuppliersUnpaid' => 'Unpaid supplier\'s invoices',
'BillsSuppliersUnpaidForCompany' => 'Unpaid supplier\'s invoices for %s',
'BillsUnpaid' => 'Unpaid',
'BillsLate' => 'Late payments',
'BillsStatistics' => 'Customer\'s invoices statistics',
'BillsStatisticsSuppliers' => 'Supplier\'s invoices statistics',
'DisabledBecauseNotErasable' => 'Disabled because can not be erased',
'InvoiceStandard' => 'Standard invoice',
'InvoiceStandardAsk' => 'Standard invoice',
'InvoiceStandardDesc' => 'This kind of invoice is the common invoice.',
'InvoiceDeposit' => 'Deposit invoice',
'InvoiceDepositAsk' => 'Deposit invoice',
'InvoiceDepositDesc' => 'This kind of invoice is done when a deposit has been received.',
'InvoiceProForma' => 'Proforma invoice',
'InvoiceProFormaAsk' => 'Proforma invoice',
'InvoiceProFormaDesc' => '<b>Proforma invoice</b> is an image of a true invoice but has no accountancy value.',
'InvoiceReplacement' => 'Replacement invoice',
'InvoiceReplacementAsk' => 'Replacement invoice for invoice',
'InvoiceReplacementDesc' => '<b>Replacement invoice</b> is used to cancel and replace completely an invoice with no payment already received.<br><br>Note: Only invoice with no payment on it can be replaced. If not closed, it will be automatically closed to \'abandoned\'.',
'InvoiceAvoir' => 'Credit note',
'InvoiceAvoirAsk' => 'Credit note to correct invoice',
'InvoiceAvoirDesc' => 'The <b>credit note</b> is a negative invoice used to solve fact that an invoice has an amount that differs than amount really paid (because customer paid too much by error, or will not paid completely since he returned some products for example).',
'ReplaceInvoice' => 'Replace invoice %s',
'ReplacementInvoice' => 'Replacement invoice',
'ReplacedByInvoice' => 'Replaced by invoice %s',
'ReplacementByInvoice' => 'Replaced by invoice',
'CorrectInvoice' => 'Correct invoice %s',
'CorrectInvoice' => 'Correct invoice %s',
'CorrectionInvoice' => 'Correction invoice',
'UsedByInvoice' => 'Used to pay invoice %s',
'ConsumedBy' => 'Consumed by',
'NotConsumed' => 'Not consumed',
'NoReplacableInvoice' => 'No replacable invoices',
'NoInvoiceToCorrect' => 'No invoice to correct',
'InvoiceHasAvoir' => 'Corrected by one or several invoices',
'CardBill' => 'Invoice card',
'PredefinedInvoices' => 'Predefined Invoices',
'Invoice' => 'Invoice',
'Invoices' => 'Invoices',
'InvoiceLine' => 'Invoice line',
'BillLines' => 'Invoice lines',
'InvoiceCustomer' => 'Customer invoice',
'CustomerInvoice' => 'Customer invoice',
'CustomersInvoices' => 'Customer\'s invoices',
'SupplierInvoice' => 'Supplier invoice',
'SuppliersInvoices' => 'Supplier\'s invoices',
'SupplierBill' => 'Supplier invoice',
'SupplierBills' => 'suppliers invoices',
'Payment' => 'Payment',
'PaymentBack' => 'Payment back',
'Payments' => 'Payments',
'PaymentsBack' => 'Payments back',
'DatePayment' => 'Payment date',
'DeletePayment' => 'Delete payment',
'ConfirmDeletePayment' => 'Are you sure you want to delete this payment ?',
'ConfirmConvertToReduc' => 'Do you want to convert this credit note or deposit into an absolute discount ?<br>The amount will so be saved among all discounts and could be used as a discount for a current or a future invoice for this customer.',
'SupplierPayments' => 'Suppliers payments',
'ReceivedPayments' => 'Received payments',
'ReceivedCustomersPayments' => 'Payments received from customers',
'ReceivedCustomersPaymentsToValid' => 'Received customers payments to validate',
'PaymentsReportsForYear' => 'Payments reports for %s',
'PaymentsReports' => 'Payments reports',
'PaymentsAlreadyDone' => 'Payments already done',
'PaymentRule' => 'Payment rule',
'PaymentMode' => 'Payment type',
'PaymentConditions' => 'Payment term',
'PaymentConditionsShort' => 'Payment term',
'PaymentAmount' => 'Payment amount',
'ValidatePayment' => 'Validate payment',
'PaymentHigherThanReminderToPay' => 'Payment higher than reminder to pay',
'HelpPaymentHigherThanReminderToPay' => 'Attention, the payment amount of one or more bills is higher than the rest to pay. <br> Edit your entry, otherwise confirm and think about creating a credit note of the excess received for each overpaid invoices.',
'ClassifyPaid' => 'Classify \'Paid\'',
'ClassifyPaidPartially' => 'Classify \'Paid partially\'',
'ClassifyCanceled' => 'Classify \'Abandoned\'',
'ClassifyClosed' => 'Classify \'Closed\'',
'CreateBill' => 'Create Invoice',
'AddBill' => 'Add invoice or credit note',
'DeleteBill' => 'Delete invoice',
'SearchACustomerInvoice' => 'Search for a customer invoice',
'SearchASupplierInvoice' => 'Search for a supplier invoice',
'CancelBill' => 'Cancel an invoice',
'SendRemindByMail' => 'Send reminder by EMail',
'DoPayment' => 'Do payment',
'DoPaymentBack' => 'Do payment back',
'ConvertToReduc' => 'Convert into future discount',
'EnterPaymentReceivedFromCustomer' => 'Enter payment received from customer',
'EnterPaymentDueToCustomer' => 'Make payment due to customer',
'DisabledBecauseRemainderToPayIsZero' => 'Disabled because remainder to pay is zero',
'Amount' => 'Amount',
'PriceBase' => 'Price base',
'BillStatus' => 'Invoice status',
'BillStatusDraft' => 'Draft (needs to be validated)',
'BillStatusPaid' => 'Paid',
'BillStatusPaidBackOrConverted' => 'Paid or converted into discount',
'BillStatusPaidBack' => 'Paid back',
'BillStatusConvertedToReduc' => 'Converted into discount',
'BillStatusConverted' => 'Paid (ready for final invoice)',
'BillStatusCanceled' => 'Abandoned',
'BillStatusValidated' => 'Validated (needs to be paid)',
'BillStatusStarted' => 'Started',
'BillStatusNotPaid' => 'Not paid',
'BillStatusClosedUnpaid' => 'Closed (unpaid)',
'BillStatusClosedPaidPartially' => 'Paid (partially)',
'BillShortStatusDraft' => 'Draft',
'BillShortStatusPaid' => 'Paid',
'BillShortStatusPaidBackOrConverted' => 'Processed',
'BillShortStatusConverted' => 'Processed',
'BillShortStatusCanceled' => 'Abandoned',
'BillShortStatusValidated' => 'Validated',
'BillShortStatusStarted' => 'Started',
'BillShortStatusNotPaid' => 'Not paid',
'BillShortStatusClosedUnpaid' => 'Closed',
'BillShortStatusClosedPaidPartially' => 'Paid (partially)',
'PaymentStatusToValidShort' => 'To validate',
'ErrorVATIntraNotConfigured' => 'Intracommunautary VAT number not yet defined',
'ErrorNoPaiementModeConfigured' => 'No default payment mode defined. Go to Invoice module setup to fix this.',
'ErrorCreateBankAccount' => 'Create a bank account, then go to Setup panel of Invoice module to define payment modes',
'ErrorBillNotFound' => 'Invoice %s does not exist',
'ErrorInvoiceAlreadyReplaced' => 'Error, you try to validate an invoice to replace invoice %s. But this one has already been replaced by invoice %s.',
'ErrorDiscountAlreadyUsed' => 'Error, discount already used',
'ErrorInvoiceAvoirMustBeNegative' => 'Error, correct invoice must have a negative amount',
'ErrorInvoiceOfThisTypeMustBePositive' => 'Error, this type of invoice must have a positive amount',
'ErrorCantCancelIfReplacementInvoiceNotValidated' => 'Error, can\'t cancel an invoice that has been replaced by another invoice that is still in draft status',
'BillFrom' => 'From',
'BillTo' => 'To',
'ActionsOnBill' => 'Actions on invoice',
'NewBill' => 'New invoice',
'Prélèvements' => 'Standing order',
'Prélèvements' => 'Standing order',
'LastBills' => 'Last %s invoices',
'LastCustomersBills' => 'Last %s customers invoices',
'LastSuppliersBills' => 'Last %s suppliers invoices',
'AllBills' => 'All invoices',
'OtherBills' => 'Other invoices',
'DraftBills' => 'Draft invoices',
'CustomersDraftInvoices' => 'Customers draft invoices',
'SuppliersDraftInvoices' => 'Suppliers draft invoices',
'Unpaid' => 'Unpaid',
'ConfirmDeleteBill' => 'Are you sure you want to delete this invoice ?',
'ConfirmValidateBill' => 'Are you sure you want to validate this invoice with reference <b>%s</b> ?',
'ConfirmUnvalidateBill' => 'Are you sure you want to change invoice <b>%s</b> to draft status ?',
'ConfirmClassifyPaidBill' => 'Are you sure you want to change invoice <b>%s</b> to status paid ?',
'ConfirmCancelBill' => 'Are you sure you want to cancel invoice <b>%s</b> ?',
'ConfirmCancelBillQuestion' => 'Why do you want to classify this invoice \'abandoned\' ?',
'ConfirmClassifyPaidPartially' => 'Are you sure you want to change invoice <b>%s</b> to status paid ?',
'ConfirmClassifyPaidPartiallyQuestion' => 'This invoice has not been paid completely. What are reasons for you to close this invoice ?',
'ConfirmClassifyPaidPartiallyReasonAvoir' => 'Remainder to pay <b>(%s %s)</b> is a discount granted because payment was made before term. I regularise the VAT with a credit note.',
'ConfirmClassifyPaidPartiallyReasonDiscountNoVat' => 'Remainder to pay <b>(%s %s)</b> is a discount granted because payment was made before term. I accept to lose the VAT on this discount.',
'ConfirmClassifyPaidPartiallyReasonDiscountVat' => 'Remainder to pay <b>(%s %s)</b> is a discount granted because payment was made before term. I recover the VAT on this discount without a credit note.',
'ConfirmClassifyPaidPartiallyReasonBadCustomer' => 'Bad customer',
'ConfirmClassifyPaidPartiallyReasonProductReturned' => 'Products partially returned',
'ConfirmClassifyPaidPartiallyReasonOther' => 'Amount abandoned for other reason',
'ConfirmClassifyPaidPartiallyReasonDiscountNoVatDesc' => 'This choice is possible if your invoice have been provided with suitable comment. (Example «Only the tax corresponding to the price that have been actually paid gives rights to deduction»)',
'ConfirmClassifyPaidPartiallyReasonDiscountVatDesc' => 'In some countries, this choice might be possible only if your invoice contains correct note.',
'ConfirmClassifyPaidPartiallyReasonAvoirDesc' => 'Use this choice if all other does not suit',
'ConfirmClassifyPaidPartiallyReasonBadCustomerDesc' => 'A <b>bad customer</b> is a customer that refuse to pay his debt.',
'ConfirmClassifyPaidPartiallyReasonProductReturnedDesc' => 'This choice is used when payment is not complete because some of products were returned',
'ConfirmClassifyPaidPartiallyReasonOtherDesc' => 'Use this choice if all other does not suit, for example in following situation:<br>- payment not complete because some products were shipped back<br>- amount claimed too important because a discount was forgotten<br>In all cases, amount over-claimed must be corrected in accountancy system by creating a credit note.',
'ConfirmClassifyAbandonReasonOther' => 'Other',
'ConfirmClassifyAbandonReasonOtherDesc' => 'This choice will be used in all other cases. For example because you plan to create a replacing invoice.',
'ConfirmCustomerPayment' => 'Do you confirm this payment input for <b>%s</b> %s ?',
'ConfirmValidatePayment' => 'Are you sure you want to validate this payment ? No change can be made once payment is validated.',
'ValidateBill' => 'Validate invoice',
'UnvalidateBill' => 'Unvalidate invoice',
'NumberOfBills' => 'Nb of invoices',
'NumberOfBillsByMonth' => 'Nb of invoices by month',
'AmountOfBills' => 'Amount of invoices',
'AmountOfBillsByMonthHT' => 'Amount of invoices by month (net of tax)',
'ShowSocialContribution' => 'Show social contribution',
'ShowBill' => 'Show invoice',
'ShowInvoice' => 'Show invoice',
'ShowInvoiceReplace' => 'Show replacing invoice',
'ShowInvoiceAvoir' => 'Show credit note',
'ShowInvoiceDeposit' => 'Show deposit invoice',
'ShowPayment' => 'Show payment',
'File' => 'File',
'AlreadyPaid' => 'Already paid',
'AlreadyPaidNoCreditNotesNoDeposits' => 'Déjà réglé (hors notes de crédit et acomptes)',
'Abandoned' => 'Abandoned',
'RemainderToPay' => 'Remainder to pay',
'RemainderToTake' => 'Remainder to take',
'AmountExpected' => 'Amount claimed',
'ExcessReceived' => 'Excess received',
'EscompteOffered' => 'Discount offered (payment before term)',
'SendBillRef' => 'Send invoice %s',
'SendReminderBillRef' => 'Send invoice %s (reminder)',
'StandingOrders' => 'Standing orders',
'StandingOrder' => 'Standing order',
'NoDraftBills' => 'No draft invoices',
'NoOtherDraftBills' => 'No other draft invoices',
'RefBill' => 'Invoice ref',
'ToBill' => 'To bill',
'RemainderToBill' => 'Remainder to bill',
'SendBillByMail' => 'Send invoice by email',
'SendReminderBillByMail' => 'Send reminder by email',
'RelatedCommercialProposals' => 'Related commercial proposals',
'MenuToValid' => 'To valid',
'DateMaxPayment' => 'Payment due before',
'DateEcheance' => 'Due date limit',
'DateInvoice' => 'Invoice date',
'NoInvoice' => 'No invoice',
'ClassifyBill' => 'Classify invoice',
'NoSupplierBillsUnpaid' => 'No suppliers invoices unpaid',
'SupplierBillsToPay' => 'Suppliers invoices to pay',
'CustomerBillsUnpaid' => 'Unpaid customers invoices',
'DispenseMontantLettres' => 'The bill drafted by mechanographical are exempt from the order in letters',
'DispenseMontantLettres' => 'The bill drafted by mechanographical are exempt from the order in letters',
'NonPercuRecuperable' => 'Non-recoverable',
'SetConditions' => 'Set payment terms',
'SetMode' => 'Set payment mode',
'SetDate' => 'Set date',
'SelectDate' => 'Select a date',
'Billed' => 'Billed',
'RepeatableInvoice' => 'Pre-defined invoice',
'RepeatableInvoices' => 'Pre-defined invoices',
'Repeatable' => 'Pre-defined',
'Repeatables' => 'Pre-defined',
'ChangeIntoRepeatableInvoice' => 'Convert into pre-defined',
'CreateRepeatableInvoice' => 'Create pre-defined invoice',
'CreateFromRepeatableInvoice' => 'Create from pre-defined invoice',
'CustomersInvoicesAndInvoiceLines' => 'Customer invoices and invoice\'s lines',
'CustomersInvoicesAndPayments' => 'Customer invoices and payments',
'ExportDataset_invoice_1' => 'Customer invoices list and invoice\'s lines',
'ExportDataset_invoice_2' => 'Customer invoices and payments',
'ProformaBill' => 'Proforma Bill:',
'Reduction' => 'Reduction',
'ReductionShort' => 'Reduc.',
'Reductions' => 'Reductions',
'ReductionsShort' => 'Reduc.',
'Discount' => 'Discount',
'Discounts' => 'Discounts',
'AddDiscount' => 'Create discount',
'AddRelativeDiscount' => 'Create relative discount',
'EditRelativeDiscount' => 'Edit relative discount',
'AddGlobalDiscount' => 'Create absolute discount',
'EditGlobalDiscounts' => 'Edit absolute discounts',
'AddCreditNote' => 'Create credit note',
'ShowDiscount' => 'Visualiser la note de crédit',
'ShowReduc' => 'Show the deduction',
'RelativeDiscount' => 'Relative discount',
'GlobalDiscount' => 'Global discount',
'CreditNote' => 'Note de crédit',
'CreditNotes' => 'Notes de crédit',
'Deposit' => 'Deposit',
'Deposits' => 'Deposits',
'DiscountFromCreditNote' => 'Remise issue de la note de crédit %s',
'DiscountFromDeposit' => 'Payments from deposit invoice %s',
'AbsoluteDiscountUse' => 'This kind of credit can be used on invoice before its validation',
'CreditNoteDepositUse' => 'Invoice must be validated to use this king of credits',
'NewGlobalDiscount' => 'New absolute discount',
'NewRelativeDiscount' => 'New relative discount',
'NoteReason' => 'Note/Reason',
'ReasonDiscount' => 'Reason',
'DiscountOfferedBy' => 'Granted by',
'DiscountStillRemaining' => 'Discounts still remaining',
'DiscountAlreadyCounted' => 'Discounts already counted',
'BillAddress' => 'Bill address',
'HelpEscompte' => 'This discount is a discount granted to customer because its payment was made before term.',
'HelpAbandonBadCustomer' => 'This amount has been abandoned (customer said to be a bad customer) and is considered as an exceptional loose.',
'HelpAbandonOther' => 'This amount has been abandoned since it was an error (wrong customer or invoice replaced by an other for example)',
'IdSocialContribution' => 'Social contribution id',
'PaymentId' => 'Payment id',
'InvoiceId' => 'Invoice id',
'InvoiceRef' => 'Invoice ref.',
'InvoiceDateCreation' => 'Invoice creation date',
'InvoiceStatus' => 'Invoice status',
'InvoiceNote' => 'Invoice note',
'InvoicePaid' => 'Invoice paid',
'PaymentNumber' => 'Payment number',
'RemoveDiscount' => 'Remove discount',
'WatermarkOnDraftBill' => 'Watermark on draft invoices (nothing if empty)',
'InvoiceNotChecked' => 'No invoice selected',
'CloneInvoice' => 'Clone invoice',
'ConfirmCloneInvoice' => 'Are you sure you want to clone this invoice <b>%s</b> ?',
'DisabledBecauseReplacedInvoice' => 'Action disabled because invoice has been replaced',
'DescTaxAndDividendsArea' => 'This area presents a summary of all payments made for tax or social contributions. Only records with payment during the fixed year are included here.',
'NbOfPayments' => 'Nb of payments',
'SplitDiscount' => 'Split discount in two',
'ConfirmSplitDiscount' => 'Are you sure you want to split this discount of <b>%s</b> %s into 2 lower discounts ?',
'TypeAmountOfEachNewDiscount' => 'Input amount for each of two parts :',
'TotalOfTwoDiscountMustEqualsOriginal' => 'Total of two new discount must be equal to original discount amount.',
'ConfirmRemoveDiscount' => 'Are you sure you want to remove this discount ?',
'RelatedBill' => 'Related invoice',
'RelatedBills' => 'Related invoices',
// PaymentConditions
'PaymentConditionShortRECEP' => 'Immediate',
'PaymentConditionRECEP' => 'Immediate',
'PaymentConditionShort30D' => '30 days',
'PaymentCondition30D' => '30 days',
'PaymentConditionShort30DENDMONTH' => '30 days end of month',
'PaymentCondition30DENDMONTH' => '30 days end of month',
'PaymentConditionShort60D' => '60 days',
'PaymentCondition60D' => '60 days',
'PaymentConditionShort60DENDMONTH' => '60 days end of month',
'PaymentCondition60DENDMONTH' => '60 days end of month',
'PaymentConditionShortPT_DELIVERY' => 'Delivery',
'PaymentConditionPT_DELIVERY' => 'On delivery',
'PaymentConditionShortPT_ORDER' => 'On order',
'PaymentConditionPT_ORDER' => 'On order',
'PaymentConditionShortPT_5050' => '50-50',
'PaymentConditionPT_5050' => '50%% in advance, 50%% on delivery',
// PaymentType
'PaymentTypeVIR' => 'Bank deposit',
'PaymentTypeShortVIR' => 'Bank deposit',
'PaymentTypePRE' => 'Bank\'s order',
'PaymentTypeShortPRE' => 'Bank\'s order',
'PaymentTypeLIQ' => 'Cash',
'PaymentTypeShortLIQ' => 'Cash',
'PaymentTypeCB' => 'Credit card',
'PaymentTypeShortCB' => 'Credit card',
'PaymentTypeCHQ' => 'Check',
'PaymentTypeShortCHQ' => 'Check',
'PaymentTypeTIP' => 'TIP',
'PaymentTypeShortTIP' => 'TIP',
'PaymentTypeVAD' => 'On line payment',
'PaymentTypeShortVAD' => 'On line payment',
'PaymentTypeTRA' => 'Bill payment',
'PaymentTypeShortTRA' => 'Bill',
'BankDetails' => 'Bank details',
'BankCode' => 'Bank code',
'DeskCode' => 'Desk code',
'BankAccountNumber' => 'Account number',
'BankAccountNumberKey' => 'Key',
'Residence' => 'Domiciliation',
'IBANNumber' => 'IBAN number',
'IBAN' => 'IBAN',
'BIC' => 'BIC/SWIFT',
'BICNumber' => 'BIC/SWIFT number',
'ExtraInfos' => 'Extra infos',
'RegulatedOn' => 'Regulated on',
'ChequeNumber' => 'Check N°',
'ChequeOrTransferNumber' => 'Check/Transfer N°',
'ChequeMaker' => 'Check transmitter',
'ChequeBank' => 'Bank of Check',
'NetToBePaid' => 'Net to be paid',
'PhoneNumber' => 'Tel',
'FullPhoneNumber' => 'Telephone',
'TeleFax' => 'Fax',
'PrettyLittleSentence' => 'Accept the amount of payments due by checks issued in my name as a Member of an accounting association approved by the Fiscal Administration.',
'IntracommunityVATNumber' => 'Intracommunity number of VAT',
'PaymentByChequeOrderedTo' => 'Check payment (including tax) are payable to %s send to',
'PaymentByChequeOrderedToShort' => 'Check payment (including tax) are payable to',
'SendTo' => 'sent to',
'PaymentByTransferOnThisBankAccount' => 'Payment by transfer on the following bank account',
'VATIsNotUsedForInvoice' => '* Non applicable VAT art-293B of CGI',
'LawApplicationPart1' => 'By application of the law 80.335 of 12/05/80',
'LawApplicationPart2' => 'the goods remain the property of',
'LawApplicationPart3' => 'the seller until the complete cashing of',
'LawApplicationPart4' => 'their price.',
'LimitedLiabilityCompanyCapital' => 'SARL with Capital of',
'UseLine' => 'Apply',
'UseDiscount' => 'Use discount',
'UseCredit' => 'Use credit',
'UseCreditNoteInInvoicePayment' => 'Reduce amount to pay with this credit',
'MenuChequeDeposits' => 'Checks deposits',
'MenuCheques' => 'Checks',
'MenuChequesReceipts' => 'Checks receipts',
'NewChequeDeposit' => 'New deposit',
'ChequesReceipts' => 'Checks receipts',
'ChequesArea' => 'Checks deposits area',
'ChequeDeposits' => 'Checks deposits',
'Cheques' => 'Checks',
'CreditNoteConvertedIntoDiscount' => 'Cette note de crédit ou acompte a été converti en %s',
'UsBillingContactAsIncoiveRecipientIfExist' => 'Use customer billing contact address instead of third party address as recipient for invoices',
'ShowUnpaidAll' => 'Show all unpaid invoices',
'ShowUnpaidLateOnly' => 'Show late unpaid invoices only',
'PaymentInvoiceRef' => 'Payment invoice %s',
'ValidateInvoice' => 'Validate invoice',
'Cash' => 'Cash',
'Reported' => 'Delayed',
'DisabledBecausePayments' => 'Not possible since there is some payments',
'CantRemovePaymentWithOneInvoicePaid' => 'Can\'t remove payment since there is at least one invoice classified payed',
'ExpectedToPay' => 'Expected payment',
'PayedByThisPayment' => 'Payed by this payment',
'ClosePaidInvoicesAutomatically' => 'Classify "Payed" all standard or replacement invoices entierely payed.',
'AllCompletelyPayedInvoiceWillBeClosed' => 'All invoice with no remain to pay will be automatically closed to status "Payed".',
////////// Types de contacts //////////
'TypeContact_facture_internal_SALESREPFOLL' => 'Representative following-up customer invoice',
'TypeContact_facture_external_BILLING' => 'Customer invoice contact',
'TypeContact_facture_external_SHIPPING' => 'Customer shipping contact',
'TypeContact_facture_external_SERVICE' => 'Customer service contact',
'TypeContact_invoice_supplier_internal_SALESREPFOLL' => 'Representative following-up supplier invoice',
'TypeContact_invoice_supplier_external_BILLING' => 'Supplier invoice contact',
'TypeContact_invoice_supplier_external_SHIPPING' => 'Supplier shipping contact',
'TypeContact_invoice_supplier_external_SERVICE' => 'Supplier service contact',
// crabe PDF Model
'PDFCrabeDescription' => 'Invoice PDF template Crabe. A complete invoice template (Template recommanded)',
// oursin PDF Model
'PDFOursinDescription' => 'Invoice PDF template Oursin. A complete invoice template (Template alternative)',
// NumRef Modules
'TerreNumRefModelDesc1' => 'Renvoie le numéro sous la forme %syymm-nnnn pour les factures et %syymm-nnnn pour les notes de crédit où yy est l\'année, mm le mois et nnnn un compteur séquentiel sans rupture et sans remise à 0',
'TerreNumRefModelError' => 'A bill starting with $syymm already exists and is not compatible with this model of sequence. Remove it or rename it to activate this module.'
);
?> | woakes070048/crm-php | htdocs/langs/fr_CH/bills.lang.php | PHP | gpl-3.0 | 24,507 |
import unittest
from gtrackcore.input.wrappers.GEDependentAttributesHolder import GEDependentAttributesHolder
from gtrackcore.test.common.Asserts import assertBoundingRegions, TestCaseWithImprovedAsserts
from gtrackcore.util.CommonConstants import BINARY_MISSING_VAL
class TestGEDependentAttributesHolder(TestCaseWithImprovedAsserts):
def setUp(self):
pass
def _assertCounting(self, processedBRList, origBRTuples, origGEList):
assertBoundingRegions(GEDependentAttributesHolder, self.assertEqual, \
processedBRList, origBRTuples, origGEList)
def testCountElements(self):
self._assertCounting([], \
[], \
[])
self._assertCounting([['A', 'chr1', 0, 1000, 1]], \
[['A', 'chr1', 0, 1000, 1]], \
[['A', 'chr1', 10, 100]])
self._assertCounting([['A', 'chr1', 0, 1000, 2], ['A', 'chr2', 0, 1000, 1]], \
[['A', 'chr1', 0, 1000, 2], ['A', 'chr2', 0, 1000, 1]], \
[['A', 'chr1', 10, 100], ['A', 'chr1', 80, 120], ['A', 'chr2', 10, 100]])
self._assertCounting([['A', 'chr1', 0, 1000, 2], ['A', 'chr1', 1000, 2000, 0], ['A', 'chr2', 0, 1000, 1]], \
[['A', 'chr1', 0, 1000, 2], ['A', 'chr1', 1000, 2000, 0], ['A', 'chr2', 0, 1000, 1]], \
[['A', 'chr1', 10, 100], ['A', 'chr1', 80, 120], ['A', 'chr2', 10, 100]])
def runTest(self):
pass
self.testCountElements()
if __name__ == "__main__":
#TestGEDependentAttributesHolder().debug()
unittest.main() | sveinugu/gtrackcore | gtrackcore/test/input/wrappers/TestGEDependentAttributesHolder.py | Python | gpl-3.0 | 1,731 |
#Copyright 2013 Paul Barton
#
#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 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/>.
import Quartz
from AppKit import NSEvent
from .base import PyMouseMeta, PyMouseEventMeta
pressID = [None, Quartz.kCGEventLeftMouseDown,
Quartz.kCGEventRightMouseDown, Quartz.kCGEventOtherMouseDown]
releaseID = [None, Quartz.kCGEventLeftMouseUp,
Quartz.kCGEventRightMouseUp, Quartz.kCGEventOtherMouseUp]
class PyMouse(PyMouseMeta):
def press(self, x, y, button=1):
event = Quartz.CGEventCreateMouseEvent(None,
pressID[button],
(x, y),
button - 1)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)
def release(self, x, y, button=1):
event = Quartz.CGEventCreateMouseEvent(None,
releaseID[button],
(x, y),
button - 1)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)
def move(self, x, y):
move = Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventMouseMoved, (x, y), 0)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, move)
def drag(self, x, y):
drag = Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventLeftMouseDragged, (x, y), 0)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, drag)
def position(self):
loc = NSEvent.mouseLocation()
return loc.x, Quartz.CGDisplayPixelsHigh(0) - loc.y
def screen_size(self):
return Quartz.CGDisplayPixelsWide(0), Quartz.CGDisplayPixelsHigh(0)
def scroll(self, vertical=None, horizontal=None, depth=None):
#Local submethod for generating Mac scroll events in one axis at a time
def scroll_event(y_move=0, x_move=0, z_move=0, n=1):
for _ in range(abs(n)):
scrollWheelEvent = Quartz.CGEventCreateScrollWheelEvent(
None, # No source
Quartz.kCGScrollEventUnitLine, # Unit of measurement is lines
3, # Number of wheels(dimensions)
y_move,
x_move,
z_move)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, scrollWheelEvent)
#Execute vertical then horizontal then depth scrolling events
if vertical is not None:
vertical = int(vertical)
if vertical == 0: # Do nothing with 0 distance
pass
elif vertical > 0: # Scroll up if positive
scroll_event(y_move=1, n=vertical)
else: # Scroll down if negative
scroll_event(y_move=-1, n=abs(vertical))
if horizontal is not None:
horizontal = int(horizontal)
if horizontal == 0: # Do nothing with 0 distance
pass
elif horizontal > 0: # Scroll right if positive
scroll_event(x_move=1, n=horizontal)
else: # Scroll left if negative
scroll_event(x_move=-1, n=abs(horizontal))
if depth is not None:
depth = int(depth)
if depth == 0: # Do nothing with 0 distance
pass
elif vertical > 0: # Scroll "out" if positive
scroll_event(z_move=1, n=depth)
else: # Scroll "in" if negative
scroll_event(z_move=-1, n=abs(depth))
class PyMouseEvent(PyMouseEventMeta):
def run(self):
tap = Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap,
Quartz.kCGHeadInsertEventTap,
Quartz.kCGEventTapOptionDefault,
Quartz.CGEventMaskBit(Quartz.kCGEventMouseMoved) |
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseUp),
self.handler,
None)
loopsource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0)
loop = Quartz.CFRunLoopGetCurrent()
Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode)
Quartz.CGEventTapEnable(tap, True)
while self.state:
Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False)
def handler(self, proxy, type, event, refcon):
(x, y) = Quartz.CGEventGetLocation(event)
if type in pressID:
self.click(x, y, pressID.index(type), True)
elif type in releaseID:
self.click(x, y, releaseID.index(type), False)
else:
self.move(x, y)
if self.capture:
Quartz.CGEventSetType(event, Quartz.kCGEventNull)
return event
| icomfred/mouse | app/python/pymouse/mac.py | Python | gpl-3.0 | 5,514 |
# -*- encoding: utf-8 -*-
def timespan_2_stops_during_timespan_1(
timespan_1=None,
timespan_2=None,
hold=False,
):
r'''Makes time relation indicating that `timespan_2` stops
during `timespan_1`.
::
>>> relation = timespantools.timespan_2_stops_during_timespan_1()
>>> print(format(relation))
timespantools.TimespanTimespanTimeRelation(
inequality=timespantools.CompoundInequality(
[
timespantools.SimpleInequality('timespan_1.start_offset < timespan_2.stop_offset'),
timespantools.SimpleInequality('timespan_2.stop_offset <= timespan_1.stop_offset'),
],
logical_operator='and',
),
)
Returns time relation or boolean.
'''
from abjad.tools import timespantools
inequality = timespantools.CompoundInequality([
'timespan_1.start_offset < timespan_2.stop_offset',
'timespan_2.stop_offset <= timespan_1.stop_offset'
])
time_relation = timespantools.TimespanTimespanTimeRelation(
inequality,
timespan_1=timespan_1,
timespan_2=timespan_2,
)
if time_relation.is_fully_loaded and not hold:
return time_relation()
else:
return time_relation
| mscuthbert/abjad | abjad/tools/timespantools/timespan_2_stops_during_timespan_1.py | Python | gpl-3.0 | 1,322 |
# -*- coding: utf-8 -*-
#
# gccjit documentation build configuration file, created by
# sphinx-quickstart on Wed May 7 17:57:19 2014.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'gccjit'
copyright = u'2014-2015, David Malcolm'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.4'
# The full version, including alpha/beta/rc tags.
release = '0.4'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'gccjitdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'gccjit.tex', u'gccjit Documentation',
u'David Malcolm', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'gccjit', u'gccjit Documentation',
[u'David Malcolm'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'gccjit', u'gccjit Documentation',
u'David Malcolm', 'gccjit', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
| vickenty/pygccjit | doc/conf.py | Python | gpl-3.0 | 7,721 |
process.on('uncaughtException', function (err) {
console.log(err)
if (err.code !== 'ENOTFOUND') {
process.exit()
}
})
var fs = require('fs')
var Path = require('path')
var createSbot = require('../lib/ssb-server')
var electron = require('electron')
var openWindow = require('../lib/window')
var TorrentTracker = require('bittorrent-tracker/server')
var magnet = require('magnet-uri')
var pull = require('pull-stream')
var ssbConfig = require('../lib/ssb-config')('ferment')
var backgroundProcess = require('../models/background-remote')(ssbConfig)
var windows = {}
var context = {
sbot: createSbot(ssbConfig),
config: ssbConfig
}
console.log('address:', context.sbot.getAddress())
ssbConfig.manifest = context.sbot.getManifest()
fs.writeFileSync(Path.join(ssbConfig.path, 'manifest.json'), JSON.stringify(ssbConfig.manifest))
electron.app.on('ready', function () {
windows.background = openWindow(context, Path.join(__dirname, '..', 'background-window.js'), {
center: true,
fullscreen: false,
fullscreenable: false,
height: 150,
maximizable: false,
minimizable: false,
resizable: false,
show: true,
skipTaskbar: true,
title: 'ferment-background-window',
useContentSize: true,
width: 150
})
backgroundProcess.target = windows.background
})
// torrent tracker (with whitelist)
var torrentWhiteList = new Set()
var tracker = TorrentTracker({
udp: true,
http: false,
stats: false,
ws: true,
filter (infoHash, params, cb) {
cb(torrentWhiteList.has(infoHash))
}
})
// only allow tracking torrents added by contacts
electron.ipcMain.once('ipcBackgroundReady', (e) => {
pull(
context.sbot.createLogStream({ live: true }),
ofType(['ferment/audio', 'ferment/update']),
pull.drain((item) => {
if (item.sync) {
tracker.listen(ssbConfig.trackerPort, ssbConfig.host, (err) => {
if (err) console.log('Cannot start tracker')
else console.log(`Tracker started at ws://${ssbConfig.host || 'localhost'}:${ssbConfig.trackerPort}`)
})
} else if (item.value && typeof item.value.content.audioSrc === 'string') {
var torrent = magnet.decode(item.value.content.audioSrc)
if (torrent.infoHash) {
torrentWhiteList.add(torrent.infoHash)
}
}
})
)
})
function ofType (types) {
types = Array.isArray(types) ? types : [types]
return pull.filter((item) => {
if (item.value) {
return types.includes(item.value.content.type)
} else {
return true
}
})
}
| fermentation/ferment | server/index.js | JavaScript | gpl-3.0 | 2,551 |
require 'spec_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec. Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.
describe EventShiftsController do
# This should return the minimal set of attributes required to create a valid
# EventShift. As you add validations to EventShift, be sure to
# adjust the attributes here as well.
let(:valid_attributes) { { "event_staffer" => "" } }
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# EventShiftsController. Be sure to keep this updated too.
let(:valid_session) { {} }
describe "GET index" do
it "assigns all event_shifts as @event_shifts" do
event_shift = EventShift.create! valid_attributes
get :index, {}, valid_session
assigns(:event_shifts).should eq([event_shift])
end
end
describe "GET show" do
it "assigns the requested event_shift as @event_shift" do
event_shift = EventShift.create! valid_attributes
get :show, {:id => event_shift.to_param}, valid_session
assigns(:event_shift).should eq(event_shift)
end
end
describe "GET new" do
it "assigns a new event_shift as @event_shift" do
get :new, {}, valid_session
assigns(:event_shift).should be_a_new(EventShift)
end
end
describe "GET edit" do
it "assigns the requested event_shift as @event_shift" do
event_shift = EventShift.create! valid_attributes
get :edit, {:id => event_shift.to_param}, valid_session
assigns(:event_shift).should eq(event_shift)
end
end
describe "POST create" do
describe "with valid params" do
it "creates a new EventShift" do
expect {
post :create, {:event_shift => valid_attributes}, valid_session
}.to change(EventShift, :count).by(1)
end
it "assigns a newly created event_shift as @event_shift" do
post :create, {:event_shift => valid_attributes}, valid_session
assigns(:event_shift).should be_a(EventShift)
assigns(:event_shift).should be_persisted
end
it "redirects to the created event_shift" do
post :create, {:event_shift => valid_attributes}, valid_session
response.should redirect_to(EventShift.last)
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved event_shift as @event_shift" do
# Trigger the behavior that occurs when invalid params are submitted
EventShift.any_instance.stub(:save).and_return(false)
post :create, {:event_shift => { "event_staffer" => "invalid value" }}, valid_session
assigns(:event_shift).should be_a_new(EventShift)
end
it "re-renders the 'new' template" do
# Trigger the behavior that occurs when invalid params are submitted
EventShift.any_instance.stub(:save).and_return(false)
post :create, {:event_shift => { "event_staffer" => "invalid value" }}, valid_session
response.should render_template("new")
end
end
end
describe "PUT update" do
describe "with valid params" do
it "updates the requested event_shift" do
event_shift = EventShift.create! valid_attributes
# Assuming there are no other event_shifts in the database, this
# specifies that the EventShift created on the previous line
# receives the :update_attributes message with whatever params are
# submitted in the request.
EventShift.any_instance.should_receive(:update_attributes).with({ "event_staffer" => "" })
put :update, {:id => event_shift.to_param, :event_shift => { "event_staffer" => "" }}, valid_session
end
it "assigns the requested event_shift as @event_shift" do
event_shift = EventShift.create! valid_attributes
put :update, {:id => event_shift.to_param, :event_shift => valid_attributes}, valid_session
assigns(:event_shift).should eq(event_shift)
end
it "redirects to the event_shift" do
event_shift = EventShift.create! valid_attributes
put :update, {:id => event_shift.to_param, :event_shift => valid_attributes}, valid_session
response.should redirect_to(event_shift)
end
end
describe "with invalid params" do
it "assigns the event_shift as @event_shift" do
event_shift = EventShift.create! valid_attributes
# Trigger the behavior that occurs when invalid params are submitted
EventShift.any_instance.stub(:save).and_return(false)
put :update, {:id => event_shift.to_param, :event_shift => { "event_staffer" => "invalid value" }}, valid_session
assigns(:event_shift).should eq(event_shift)
end
it "re-renders the 'edit' template" do
event_shift = EventShift.create! valid_attributes
# Trigger the behavior that occurs when invalid params are submitted
EventShift.any_instance.stub(:save).and_return(false)
put :update, {:id => event_shift.to_param, :event_shift => { "event_staffer" => "invalid value" }}, valid_session
response.should render_template("edit")
end
end
end
describe "DELETE destroy" do
it "destroys the requested event_shift" do
event_shift = EventShift.create! valid_attributes
expect {
delete :destroy, {:id => event_shift.to_param}, valid_session
}.to change(EventShift, :count).by(-1)
end
it "redirects to the event_shifts list" do
event_shift = EventShift.create! valid_attributes
delete :destroy, {:id => event_shift.to_param}, valid_session
response.should redirect_to(event_shifts_url)
end
end
end
| aliceriot/borges | spec/controllers/event_shifts_controller_spec.rb | Ruby | gpl-3.0 | 6,619 |
# Unix SMB/CIFS implementation.
# Copyright (C) Kai Blin <kai@samba.org> 2011
#
# 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 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/>.
#
import os
import sys
import struct
import random
import socket
import samba.ndr as ndr
from samba import credentials, param
from samba.tests import TestCase
from samba.dcerpc import dns, dnsp, dnsserver
from samba.netcmd.dns import TXTRecord, dns_record_match, data_to_dns_record
from samba.tests.subunitrun import SubunitOptions, TestProgram
import samba.getopt as options
import optparse
parser = optparse.OptionParser("dns.py <server name> <server ip> [options]")
sambaopts = options.SambaOptions(parser)
parser.add_option_group(sambaopts)
# This timeout only has relevance when testing against Windows
# Format errors tend to return patchy responses, so a timeout is needed.
parser.add_option("--timeout", type="int", dest="timeout",
help="Specify timeout for DNS requests")
# use command line creds if available
credopts = options.CredentialsOptions(parser)
parser.add_option_group(credopts)
subunitopts = SubunitOptions(parser)
parser.add_option_group(subunitopts)
opts, args = parser.parse_args()
lp = sambaopts.get_loadparm()
creds = credopts.get_credentials(lp)
timeout = opts.timeout
if len(args) < 2:
parser.print_usage()
sys.exit(1)
server_name = args[0]
server_ip = args[1]
creds.set_krb_forwardable(credentials.NO_KRB_FORWARDABLE)
def make_txt_record(records):
rdata_txt = dns.txt_record()
s_list = dnsp.string_list()
s_list.count = len(records)
s_list.str = records
rdata_txt.txt = s_list
return rdata_txt
class DNSTest(TestCase):
def setUp(self):
global server, server_ip, lp, creds
super(DNSTest, self).setUp()
self.server = server_name
self.server_ip = server_ip
self.lp = lp
self.creds = creds
def errstr(self, errcode):
"Return a readable error code"
string_codes = [
"OK",
"FORMERR",
"SERVFAIL",
"NXDOMAIN",
"NOTIMP",
"REFUSED",
"YXDOMAIN",
"YXRRSET",
"NXRRSET",
"NOTAUTH",
"NOTZONE",
]
return string_codes[errcode]
def assert_dns_rcode_equals(self, packet, rcode):
"Helper function to check return code"
p_errcode = packet.operation & 0x000F
self.assertEquals(p_errcode, rcode, "Expected RCODE %s, got %s" %
(self.errstr(rcode), self.errstr(p_errcode)))
def assert_dns_opcode_equals(self, packet, opcode):
"Helper function to check opcode"
p_opcode = packet.operation & 0x7800
self.assertEquals(p_opcode, opcode, "Expected OPCODE %s, got %s" %
(opcode, p_opcode))
def make_name_packet(self, opcode, qid=None):
"Helper creating a dns.name_packet"
p = dns.name_packet()
if qid is None:
p.id = random.randint(0x0, 0xffff)
p.operation = opcode
p.questions = []
return p
def finish_name_packet(self, packet, questions):
"Helper to finalize a dns.name_packet"
packet.qdcount = len(questions)
packet.questions = questions
def make_name_question(self, name, qtype, qclass):
"Helper creating a dns.name_question"
q = dns.name_question()
q.name = name
q.question_type = qtype
q.question_class = qclass
return q
def get_dns_domain(self):
"Helper to get dns domain"
return self.creds.get_realm().lower()
def dns_transaction_udp(self, packet, host=server_ip,
dump=False, timeout=timeout):
"send a DNS query and read the reply"
s = None
try:
send_packet = ndr.ndr_pack(packet)
if dump:
print self.hexdump(send_packet)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
s.settimeout(timeout)
s.connect((host, 53))
s.send(send_packet, 0)
recv_packet = s.recv(2048, 0)
if dump:
print self.hexdump(recv_packet)
return ndr.ndr_unpack(dns.name_packet, recv_packet)
finally:
if s is not None:
s.close()
def dns_transaction_tcp(self, packet, host=server_ip,
dump=False, timeout=timeout):
"send a DNS query and read the reply"
s = None
try:
send_packet = ndr.ndr_pack(packet)
if dump:
print self.hexdump(send_packet)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
s.settimeout(timeout)
s.connect((host, 53))
tcp_packet = struct.pack('!H', len(send_packet))
tcp_packet += send_packet
s.send(tcp_packet, 0)
recv_packet = s.recv(0xffff + 2, 0)
if dump:
print self.hexdump(recv_packet)
return ndr.ndr_unpack(dns.name_packet, recv_packet[2:])
finally:
if s is not None:
s.close()
def make_txt_update(self, prefix, txt_array):
p = self.make_name_packet(dns.DNS_OPCODE_UPDATE)
updates = []
name = self.get_dns_domain()
u = self.make_name_question(name, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
updates.append(u)
self.finish_name_packet(p, updates)
updates = []
r = dns.res_rec()
r.name = "%s.%s" % (prefix, self.get_dns_domain())
r.rr_type = dns.DNS_QTYPE_TXT
r.rr_class = dns.DNS_QCLASS_IN
r.ttl = 900
r.length = 0xffff
rdata = make_txt_record(txt_array)
r.rdata = rdata
updates.append(r)
p.nscount = len(updates)
p.nsrecs = updates
return p
def check_query_txt(self, prefix, txt_array):
name = "%s.%s" % (prefix, self.get_dns_domain())
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
q = self.make_name_question(name, dns.DNS_QTYPE_TXT, dns.DNS_QCLASS_IN)
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.assertEquals(response.ancount, 1)
self.assertEquals(response.answers[0].rdata.txt.str, txt_array)
class TestSimpleQueries(DNSTest):
def test_one_a_query(self):
"create a query packet containing one query record"
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
name = "%s.%s" % (self.server, self.get_dns_domain())
q = self.make_name_question(name, dns.DNS_QTYPE_A, dns.DNS_QCLASS_IN)
print "asking for ", q.name
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.assert_dns_opcode_equals(response, dns.DNS_OPCODE_QUERY)
self.assertEquals(response.ancount, 1)
self.assertEquals(response.answers[0].rdata,
self.server_ip)
def test_one_a_query_tcp(self):
"create a query packet containing one query record via TCP"
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
name = "%s.%s" % (self.server, self.get_dns_domain())
q = self.make_name_question(name, dns.DNS_QTYPE_A, dns.DNS_QCLASS_IN)
print "asking for ", q.name
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_tcp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.assert_dns_opcode_equals(response, dns.DNS_OPCODE_QUERY)
self.assertEquals(response.ancount, 1)
self.assertEquals(response.answers[0].rdata,
self.server_ip)
def test_one_mx_query(self):
"create a query packet causing an empty RCODE_OK answer"
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
name = "%s.%s" % (self.server, self.get_dns_domain())
q = self.make_name_question(name, dns.DNS_QTYPE_MX, dns.DNS_QCLASS_IN)
print "asking for ", q.name
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.assert_dns_opcode_equals(response, dns.DNS_OPCODE_QUERY)
self.assertEquals(response.ancount, 0)
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
name = "invalid-%s.%s" % (self.server, self.get_dns_domain())
q = self.make_name_question(name, dns.DNS_QTYPE_MX, dns.DNS_QCLASS_IN)
print "asking for ", q.name
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_NXDOMAIN)
self.assert_dns_opcode_equals(response, dns.DNS_OPCODE_QUERY)
self.assertEquals(response.ancount, 0)
def test_two_queries(self):
"create a query packet containing two query records"
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
name = "%s.%s" % (self.server, self.get_dns_domain())
q = self.make_name_question(name, dns.DNS_QTYPE_A, dns.DNS_QCLASS_IN)
questions.append(q)
name = "%s.%s" % ('bogusname', self.get_dns_domain())
q = self.make_name_question(name, dns.DNS_QTYPE_A, dns.DNS_QCLASS_IN)
questions.append(q)
self.finish_name_packet(p, questions)
try:
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_FORMERR)
except socket.timeout:
# Windows chooses not to respond to incorrectly formatted queries.
# Although this appears to be non-deterministic even for the same
# request twice, it also appears to be based on a how poorly the
# request is formatted.
pass
def test_qtype_all_query(self):
"create a QTYPE_ALL query"
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
name = "%s.%s" % (self.server, self.get_dns_domain())
q = self.make_name_question(name, dns.DNS_QTYPE_ALL, dns.DNS_QCLASS_IN)
print "asking for ", q.name
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
num_answers = 1
dc_ipv6 = os.getenv('SERVER_IPV6')
if dc_ipv6 is not None:
num_answers += 1
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.assert_dns_opcode_equals(response, dns.DNS_OPCODE_QUERY)
self.assertEquals(response.ancount, num_answers)
self.assertEquals(response.answers[0].rdata,
self.server_ip)
if dc_ipv6 is not None:
self.assertEquals(response.answers[1].rdata, dc_ipv6)
def test_qclass_none_query(self):
"create a QCLASS_NONE query"
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
name = "%s.%s" % (self.server, self.get_dns_domain())
q = self.make_name_question(name, dns.DNS_QTYPE_ALL, dns.DNS_QCLASS_NONE)
questions.append(q)
self.finish_name_packet(p, questions)
try:
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_NOTIMP)
except socket.timeout:
# Windows chooses not to respond to incorrectly formatted queries.
# Although this appears to be non-deterministic even for the same
# request twice, it also appears to be based on a how poorly the
# request is formatted.
pass
# Only returns an authority section entry in BIND and Win DNS
# FIXME: Enable one Samba implements this feature
# def test_soa_hostname_query(self):
# "create a SOA query for a hostname"
# p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
# questions = []
#
# name = "%s.%s" % (os.getenv('SERVER'), self.get_dns_domain())
# q = self.make_name_question(name, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
# questions.append(q)
#
# self.finish_name_packet(p, questions)
# response = self.dns_transaction_udp(p)
# self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
# self.assert_dns_opcode_equals(response, dns.DNS_OPCODE_QUERY)
# # We don't get SOA records for single hosts
# self.assertEquals(response.ancount, 0)
def test_soa_domain_query(self):
"create a SOA query for a domain"
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
name = self.get_dns_domain()
q = self.make_name_question(name, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.assert_dns_opcode_equals(response, dns.DNS_OPCODE_QUERY)
self.assertEquals(response.ancount, 1)
self.assertEquals(response.answers[0].rdata.minimum, 3600)
class TestDNSUpdates(DNSTest):
def test_two_updates(self):
"create two update requests"
p = self.make_name_packet(dns.DNS_OPCODE_UPDATE)
updates = []
name = "%s.%s" % (self.server, self.get_dns_domain())
u = self.make_name_question(name, dns.DNS_QTYPE_A, dns.DNS_QCLASS_IN)
updates.append(u)
name = self.get_dns_domain()
u = self.make_name_question(name, dns.DNS_QTYPE_A, dns.DNS_QCLASS_IN)
updates.append(u)
self.finish_name_packet(p, updates)
try:
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_FORMERR)
except socket.timeout:
# Windows chooses not to respond to incorrectly formatted queries.
# Although this appears to be non-deterministic even for the same
# request twice, it also appears to be based on a how poorly the
# request is formatted.
pass
def test_update_wrong_qclass(self):
"create update with DNS_QCLASS_NONE"
p = self.make_name_packet(dns.DNS_OPCODE_UPDATE)
updates = []
name = self.get_dns_domain()
u = self.make_name_question(name, dns.DNS_QTYPE_A, dns.DNS_QCLASS_NONE)
updates.append(u)
self.finish_name_packet(p, updates)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_NOTIMP)
def test_update_prereq_with_non_null_ttl(self):
"test update with a non-null TTL"
p = self.make_name_packet(dns.DNS_OPCODE_UPDATE)
updates = []
name = self.get_dns_domain()
u = self.make_name_question(name, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
updates.append(u)
self.finish_name_packet(p, updates)
prereqs = []
r = dns.res_rec()
r.name = "%s.%s" % (self.server, self.get_dns_domain())
r.rr_type = dns.DNS_QTYPE_TXT
r.rr_class = dns.DNS_QCLASS_NONE
r.ttl = 1
r.length = 0
prereqs.append(r)
p.ancount = len(prereqs)
p.answers = prereqs
try:
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_FORMERR)
except socket.timeout:
# Windows chooses not to respond to incorrectly formatted queries.
# Although this appears to be non-deterministic even for the same
# request twice, it also appears to be based on a how poorly the
# request is formatted.
pass
def test_update_prereq_with_non_null_length(self):
"test update with a non-null length"
p = self.make_name_packet(dns.DNS_OPCODE_UPDATE)
updates = []
name = self.get_dns_domain()
u = self.make_name_question(name, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
updates.append(u)
self.finish_name_packet(p, updates)
prereqs = []
r = dns.res_rec()
r.name = "%s.%s" % (self.server, self.get_dns_domain())
r.rr_type = dns.DNS_QTYPE_TXT
r.rr_class = dns.DNS_QCLASS_ANY
r.ttl = 0
r.length = 1
prereqs.append(r)
p.ancount = len(prereqs)
p.answers = prereqs
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_NXRRSET)
def test_update_prereq_nonexisting_name(self):
"test update with a nonexisting name"
p = self.make_name_packet(dns.DNS_OPCODE_UPDATE)
updates = []
name = self.get_dns_domain()
u = self.make_name_question(name, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
updates.append(u)
self.finish_name_packet(p, updates)
prereqs = []
r = dns.res_rec()
r.name = "idontexist.%s" % self.get_dns_domain()
r.rr_type = dns.DNS_QTYPE_TXT
r.rr_class = dns.DNS_QCLASS_ANY
r.ttl = 0
r.length = 0
prereqs.append(r)
p.ancount = len(prereqs)
p.answers = prereqs
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_NXRRSET)
def test_update_add_txt_record(self):
"test adding records works"
prefix, txt = 'textrec', ['"This is a test"']
p = self.make_txt_update(prefix, txt)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, txt)
def test_delete_record(self):
"Test if deleting records works"
NAME = "deleterec.%s" % self.get_dns_domain()
# First, create a record to make sure we have a record to delete.
p = self.make_name_packet(dns.DNS_OPCODE_UPDATE)
updates = []
name = self.get_dns_domain()
u = self.make_name_question(name, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
updates.append(u)
self.finish_name_packet(p, updates)
updates = []
r = dns.res_rec()
r.name = NAME
r.rr_type = dns.DNS_QTYPE_TXT
r.rr_class = dns.DNS_QCLASS_IN
r.ttl = 900
r.length = 0xffff
rdata = make_txt_record(['"This is a test"'])
r.rdata = rdata
updates.append(r)
p.nscount = len(updates)
p.nsrecs = updates
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
# Now check the record is around
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
q = self.make_name_question(NAME, dns.DNS_QTYPE_TXT, dns.DNS_QCLASS_IN)
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
# Now delete the record
p = self.make_name_packet(dns.DNS_OPCODE_UPDATE)
updates = []
name = self.get_dns_domain()
u = self.make_name_question(name, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
updates.append(u)
self.finish_name_packet(p, updates)
updates = []
r = dns.res_rec()
r.name = NAME
r.rr_type = dns.DNS_QTYPE_TXT
r.rr_class = dns.DNS_QCLASS_NONE
r.ttl = 0
r.length = 0xffff
rdata = make_txt_record(['"This is a test"'])
r.rdata = rdata
updates.append(r)
p.nscount = len(updates)
p.nsrecs = updates
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
# And finally check it's gone
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
q = self.make_name_question(NAME, dns.DNS_QTYPE_TXT, dns.DNS_QCLASS_IN)
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_NXDOMAIN)
def test_readd_record(self):
"Test if adding, deleting and then readding a records works"
NAME = "readdrec.%s" % self.get_dns_domain()
# Create the record
p = self.make_name_packet(dns.DNS_OPCODE_UPDATE)
updates = []
name = self.get_dns_domain()
u = self.make_name_question(name, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
updates.append(u)
self.finish_name_packet(p, updates)
updates = []
r = dns.res_rec()
r.name = NAME
r.rr_type = dns.DNS_QTYPE_TXT
r.rr_class = dns.DNS_QCLASS_IN
r.ttl = 900
r.length = 0xffff
rdata = make_txt_record(['"This is a test"'])
r.rdata = rdata
updates.append(r)
p.nscount = len(updates)
p.nsrecs = updates
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
# Now check the record is around
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
q = self.make_name_question(NAME, dns.DNS_QTYPE_TXT, dns.DNS_QCLASS_IN)
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
# Now delete the record
p = self.make_name_packet(dns.DNS_OPCODE_UPDATE)
updates = []
name = self.get_dns_domain()
u = self.make_name_question(name, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
updates.append(u)
self.finish_name_packet(p, updates)
updates = []
r = dns.res_rec()
r.name = NAME
r.rr_type = dns.DNS_QTYPE_TXT
r.rr_class = dns.DNS_QCLASS_NONE
r.ttl = 0
r.length = 0xffff
rdata = make_txt_record(['"This is a test"'])
r.rdata = rdata
updates.append(r)
p.nscount = len(updates)
p.nsrecs = updates
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
# check it's gone
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
q = self.make_name_question(NAME, dns.DNS_QTYPE_TXT, dns.DNS_QCLASS_IN)
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_NXDOMAIN)
# recreate the record
p = self.make_name_packet(dns.DNS_OPCODE_UPDATE)
updates = []
name = self.get_dns_domain()
u = self.make_name_question(name, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
updates.append(u)
self.finish_name_packet(p, updates)
updates = []
r = dns.res_rec()
r.name = NAME
r.rr_type = dns.DNS_QTYPE_TXT
r.rr_class = dns.DNS_QCLASS_IN
r.ttl = 900
r.length = 0xffff
rdata = make_txt_record(['"This is a test"'])
r.rdata = rdata
updates.append(r)
p.nscount = len(updates)
p.nsrecs = updates
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
# Now check the record is around
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
q = self.make_name_question(NAME, dns.DNS_QTYPE_TXT, dns.DNS_QCLASS_IN)
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
def test_update_add_mx_record(self):
"test adding MX records works"
p = self.make_name_packet(dns.DNS_OPCODE_UPDATE)
updates = []
name = self.get_dns_domain()
u = self.make_name_question(name, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
updates.append(u)
self.finish_name_packet(p, updates)
updates = []
r = dns.res_rec()
r.name = "%s" % self.get_dns_domain()
r.rr_type = dns.DNS_QTYPE_MX
r.rr_class = dns.DNS_QCLASS_IN
r.ttl = 900
r.length = 0xffff
rdata = dns.mx_record()
rdata.preference = 10
rdata.exchange = 'mail.%s' % self.get_dns_domain()
r.rdata = rdata
updates.append(r)
p.nscount = len(updates)
p.nsrecs = updates
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
name = "%s" % self.get_dns_domain()
q = self.make_name_question(name, dns.DNS_QTYPE_MX, dns.DNS_QCLASS_IN)
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.assertEqual(response.ancount, 1)
ans = response.answers[0]
self.assertEqual(ans.rr_type, dns.DNS_QTYPE_MX)
self.assertEqual(ans.rdata.preference, 10)
self.assertEqual(ans.rdata.exchange, 'mail.%s' % self.get_dns_domain())
class TestComplexQueries(DNSTest):
def setUp(self):
super(TestComplexQueries, self).setUp()
p = self.make_name_packet(dns.DNS_OPCODE_UPDATE)
updates = []
name = self.get_dns_domain()
u = self.make_name_question(name, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
updates.append(u)
self.finish_name_packet(p, updates)
updates = []
r = dns.res_rec()
r.name = "cname_test.%s" % self.get_dns_domain()
r.rr_type = dns.DNS_QTYPE_CNAME
r.rr_class = dns.DNS_QCLASS_IN
r.ttl = 900
r.length = 0xffff
r.rdata = "%s.%s" % (self.server, self.get_dns_domain())
updates.append(r)
p.nscount = len(updates)
p.nsrecs = updates
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
def tearDown(self):
super(TestComplexQueries, self).tearDown()
p = self.make_name_packet(dns.DNS_OPCODE_UPDATE)
updates = []
name = self.get_dns_domain()
u = self.make_name_question(name, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
updates.append(u)
self.finish_name_packet(p, updates)
updates = []
r = dns.res_rec()
r.name = "cname_test.%s" % self.get_dns_domain()
r.rr_type = dns.DNS_QTYPE_CNAME
r.rr_class = dns.DNS_QCLASS_NONE
r.ttl = 0
r.length = 0xffff
r.rdata = "%s.%s" % (self.server, self.get_dns_domain())
updates.append(r)
p.nscount = len(updates)
p.nsrecs = updates
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
def test_one_a_query(self):
"create a query packet containing one query record"
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
name = "cname_test.%s" % self.get_dns_domain()
q = self.make_name_question(name, dns.DNS_QTYPE_A, dns.DNS_QCLASS_IN)
print "asking for ", q.name
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.assert_dns_opcode_equals(response, dns.DNS_OPCODE_QUERY)
self.assertEquals(response.ancount, 2)
self.assertEquals(response.answers[0].rr_type, dns.DNS_QTYPE_CNAME)
self.assertEquals(response.answers[0].rdata, "%s.%s" %
(self.server, self.get_dns_domain()))
self.assertEquals(response.answers[1].rr_type, dns.DNS_QTYPE_A)
self.assertEquals(response.answers[1].rdata,
self.server_ip)
class TestInvalidQueries(DNSTest):
def test_one_a_query(self):
"send 0 bytes follows by create a query packet containing one query record"
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
s.connect((self.server_ip, 53))
s.send("", 0)
finally:
if s is not None:
s.close()
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
name = "%s.%s" % (self.server, self.get_dns_domain())
q = self.make_name_question(name, dns.DNS_QTYPE_A, dns.DNS_QCLASS_IN)
print "asking for ", q.name
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.assert_dns_opcode_equals(response, dns.DNS_OPCODE_QUERY)
self.assertEquals(response.ancount, 1)
self.assertEquals(response.answers[0].rdata,
self.server_ip)
def test_one_a_reply(self):
"send a reply instead of a query"
global timeout
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
name = "%s.%s" % ('fakefakefake', self.get_dns_domain())
q = self.make_name_question(name, dns.DNS_QTYPE_A, dns.DNS_QCLASS_IN)
print "asking for ", q.name
questions.append(q)
self.finish_name_packet(p, questions)
p.operation |= dns.DNS_FLAG_REPLY
s = None
try:
send_packet = ndr.ndr_pack(p)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
s.settimeout(timeout)
host=self.server_ip
s.connect((host, 53))
tcp_packet = struct.pack('!H', len(send_packet))
tcp_packet += send_packet
s.send(tcp_packet, 0)
recv_packet = s.recv(0xffff + 2, 0)
self.assertEquals(0, len(recv_packet))
except socket.timeout:
# Windows chooses not to respond to incorrectly formatted queries.
# Although this appears to be non-deterministic even for the same
# request twice, it also appears to be based on a how poorly the
# request is formatted.
pass
finally:
if s is not None:
s.close()
class TestZones(DNSTest):
def setUp(self):
super(TestZones, self).setUp()
self.zone = "test.lan"
self.rpc_conn = dnsserver.dnsserver("ncacn_ip_tcp:%s[sign]" % (self.server_ip),
self.lp, self.creds)
def tearDown(self):
super(TestZones, self).tearDown()
try:
self.delete_zone(self.zone)
except RuntimeError, (num, string):
if num != 9601: #WERR_DNS_ERROR_ZONE_DOES_NOT_EXIST
raise
def create_zone(self, zone):
zone_create = dnsserver.DNS_RPC_ZONE_CREATE_INFO_LONGHORN()
zone_create.pszZoneName = zone
zone_create.dwZoneType = dnsp.DNS_ZONE_TYPE_PRIMARY
zone_create.fAllowUpdate = dnsp.DNS_ZONE_UPDATE_SECURE
zone_create.fAging = 0
zone_create.dwDpFlags = dnsserver.DNS_DP_DOMAIN_DEFAULT
self.rpc_conn.DnssrvOperation2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0,
self.server_ip,
None,
0,
'ZoneCreate',
dnsserver.DNSSRV_TYPEID_ZONE_CREATE,
zone_create)
def delete_zone(self, zone):
self.rpc_conn.DnssrvOperation2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0,
self.server_ip,
zone,
0,
'DeleteZoneFromDs',
dnsserver.DNSSRV_TYPEID_NULL,
None)
def test_soa_query(self):
zone = "test.lan"
p = self.make_name_packet(dns.DNS_OPCODE_QUERY)
questions = []
q = self.make_name_question(zone, dns.DNS_QTYPE_SOA, dns.DNS_QCLASS_IN)
questions.append(q)
self.finish_name_packet(p, questions)
response = self.dns_transaction_udp(p)
# Windows returns OK while BIND logically seems to return NXDOMAIN
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_NXDOMAIN)
self.assert_dns_opcode_equals(response, dns.DNS_OPCODE_QUERY)
self.assertEquals(response.ancount, 0)
self.create_zone(zone)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.assert_dns_opcode_equals(response, dns.DNS_OPCODE_QUERY)
self.assertEquals(response.ancount, 1)
self.assertEquals(response.answers[0].rr_type, dns.DNS_QTYPE_SOA)
self.delete_zone(zone)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_NXDOMAIN)
self.assert_dns_opcode_equals(response, dns.DNS_OPCODE_QUERY)
self.assertEquals(response.ancount, 0)
class TestRPCRoundtrip(DNSTest):
def setUp(self):
super(TestRPCRoundtrip, self).setUp()
self.rpc_conn = dnsserver.dnsserver("ncacn_ip_tcp:%s[sign]" % (self.server_ip),
self.lp, self.creds)
def tearDown(self):
super(TestRPCRoundtrip, self).tearDown()
def test_update_add_txt_rpc_to_dns(self):
prefix, txt = 'rpctextrec', ['"This is a test"']
name = "%s.%s" % (prefix, self.get_dns_domain())
rec = data_to_dns_record(dnsp.DNS_TYPE_TXT, '"\\"This is a test\\""')
add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF()
add_rec_buf.rec = rec
try:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, add_rec_buf, None)
self.check_query_txt(prefix, txt)
finally:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, None, add_rec_buf)
def test_update_add_null_padded_txt_record(self):
"test adding records works"
prefix, txt = 'pad1textrec', ['"This is a test"', '', '']
p = self.make_txt_update(prefix, txt)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, txt)
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, '"\\"This is a test\\"" "" ""'))
prefix, txt = 'pad2textrec', ['"This is a test"', '', '', 'more text']
p = self.make_txt_update(prefix, txt)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, txt)
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, '"\\"This is a test\\"" "" "" "more text"'))
prefix, txt = 'pad3textrec', ['', '', '"This is a test"']
p = self.make_txt_update(prefix, txt)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, txt)
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, '"" "" "\\"This is a test\\""'))
def test_update_add_padding_rpc_to_dns(self):
prefix, txt = 'pad1textrec', ['"This is a test"', '', '']
prefix = 'rpc' + prefix
name = "%s.%s" % (prefix, self.get_dns_domain())
rec = data_to_dns_record(dnsp.DNS_TYPE_TXT, '"\\"This is a test\\"" "" ""')
add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF()
add_rec_buf.rec = rec
try:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, add_rec_buf, None)
self.check_query_txt(prefix, txt)
finally:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, None, add_rec_buf)
prefix, txt = 'pad2textrec', ['"This is a test"', '', '', 'more text']
prefix = 'rpc' + prefix
name = "%s.%s" % (prefix, self.get_dns_domain())
rec = data_to_dns_record(dnsp.DNS_TYPE_TXT, '"\\"This is a test\\"" "" "" "more text"')
add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF()
add_rec_buf.rec = rec
try:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, add_rec_buf, None)
self.check_query_txt(prefix, txt)
finally:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, None, add_rec_buf)
prefix, txt = 'pad3textrec', ['', '', '"This is a test"']
prefix = 'rpc' + prefix
name = "%s.%s" % (prefix, self.get_dns_domain())
rec = data_to_dns_record(dnsp.DNS_TYPE_TXT, '"" "" "\\"This is a test\\""')
add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF()
add_rec_buf.rec = rec
try:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, add_rec_buf, None)
self.check_query_txt(prefix, txt)
finally:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, None, add_rec_buf)
# Test is incomplete due to strlen against txt records
def test_update_add_null_char_txt_record(self):
"test adding records works"
prefix, txt = 'nulltextrec', ['NULL\x00BYTE']
p = self.make_txt_update(prefix, txt)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, ['NULL'])
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, '"NULL"'))
prefix, txt = 'nulltextrec2', ['NULL\x00BYTE', 'NULL\x00BYTE']
p = self.make_txt_update(prefix, txt)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, ['NULL', 'NULL'])
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, '"NULL" "NULL"'))
def test_update_add_null_char_rpc_to_dns(self):
prefix, txt = 'nulltextrec', ['NULL\x00BYTE']
prefix = 'rpc' + prefix
name = "%s.%s" % (prefix, self.get_dns_domain())
rec = data_to_dns_record(dnsp.DNS_TYPE_TXT, '"NULL"')
add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF()
add_rec_buf.rec = rec
try:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, add_rec_buf, None)
self.check_query_txt(prefix, ['NULL'])
finally:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, None, add_rec_buf)
def test_update_add_hex_char_txt_record(self):
"test adding records works"
prefix, txt = 'hextextrec', ['HIGH\xFFBYTE']
p = self.make_txt_update(prefix, txt)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, txt)
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, '"HIGH\xFFBYTE"'))
def test_update_add_hex_rpc_to_dns(self):
prefix, txt = 'hextextrec', ['HIGH\xFFBYTE']
prefix = 'rpc' + prefix
name = "%s.%s" % (prefix, self.get_dns_domain())
rec = data_to_dns_record(dnsp.DNS_TYPE_TXT, '"HIGH\xFFBYTE"')
add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF()
add_rec_buf.rec = rec
try:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, add_rec_buf, None)
self.check_query_txt(prefix, txt)
finally:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, None, add_rec_buf)
def test_update_add_slash_txt_record(self):
"test adding records works"
prefix, txt = 'slashtextrec', ['Th\\=is=is a test']
p = self.make_txt_update(prefix, txt)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, txt)
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, '"Th\\\\=is=is a test"'))
# This test fails against Windows as it eliminates slashes in RPC
# One typical use for a slash is in records like 'var=value' to
# escape '=' characters.
def test_update_add_slash_rpc_to_dns(self):
prefix, txt = 'slashtextrec', ['Th\\=is=is a test']
prefix = 'rpc' + prefix
name = "%s.%s" % (prefix, self.get_dns_domain())
rec = data_to_dns_record(dnsp.DNS_TYPE_TXT, '"Th\\\\=is=is a test"')
add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF()
add_rec_buf.rec = rec
try:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, add_rec_buf, None)
self.check_query_txt(prefix, txt)
finally:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, None, add_rec_buf)
def test_update_add_two_txt_records(self):
"test adding two txt records works"
prefix, txt = 'textrec2', ['"This is a test"',
'"and this is a test, too"']
p = self.make_txt_update(prefix, txt)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, txt)
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, '"\\"This is a test\\""' +
' "\\"and this is a test, too\\""'))
def test_update_add_two_rpc_to_dns(self):
prefix, txt = 'textrec2', ['"This is a test"',
'"and this is a test, too"']
prefix = 'rpc' + prefix
name = "%s.%s" % (prefix, self.get_dns_domain())
rec = data_to_dns_record(dnsp.DNS_TYPE_TXT,
'"\\"This is a test\\""' +
' "\\"and this is a test, too\\""')
add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF()
add_rec_buf.rec = rec
try:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, add_rec_buf, None)
self.check_query_txt(prefix, txt)
finally:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, None, add_rec_buf)
def test_update_add_empty_txt_records(self):
"test adding two txt records works"
prefix, txt = 'emptytextrec', []
p = self.make_txt_update(prefix, txt)
response = self.dns_transaction_udp(p)
self.assert_dns_rcode_equals(response, dns.DNS_RCODE_OK)
self.check_query_txt(prefix, txt)
self.assertIsNotNone(dns_record_match(self.rpc_conn, self.server_ip,
self.get_dns_domain(),
"%s.%s" % (prefix, self.get_dns_domain()),
dnsp.DNS_TYPE_TXT, ''))
def test_update_add_empty_rpc_to_dns(self):
prefix, txt = 'rpcemptytextrec', []
name = "%s.%s" % (prefix, self.get_dns_domain())
rec = data_to_dns_record(dnsp.DNS_TYPE_TXT, '')
add_rec_buf = dnsserver.DNS_RPC_RECORD_BUF()
add_rec_buf.rec = rec
try:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, add_rec_buf, None)
self.check_query_txt(prefix, txt)
finally:
self.rpc_conn.DnssrvUpdateRecord2(dnsserver.DNS_CLIENT_VERSION_LONGHORN,
0, self.server_ip, self.get_dns_domain(),
name, None, add_rec_buf)
TestProgram(module=__name__, opts=subunitopts)
| Zentyal/samba | python/samba/tests/dns.py | Python | gpl-3.0 | 48,654 |
/*
* This file is part of the SYMPLER package.
* https://github.com/kauzlari/sympler
*
* Copyright 2002-2013,
* David Kauzlaric <david.kauzlaric@frias.uni-freiburg.de>,
* and others authors stated in the AUTHORS file in the top-level
* source directory.
*
* SYMPLER 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.
*
* SYMPLER 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 SYMPLER. If not, see <http://www.gnu.org/licenses/>.
*
* Please cite the research papers on SYMPLER in your own publications.
* Check out the PUBLICATIONS file in the top-level source directory.
*
* You are very welcome to contribute extensions to the code. Please do
* so by making a pull request on https://github.com/kauzlari/sympler
*
*/
#include "f_wall_repulsion.h"
#include "random.h"
#include "simulation.h"
#define M_SIMULATION ((Simulation*) m_parent)
#define M_PHASE M_SIMULATION->phase()
#define M_MANAGER M_PHASE->manager()
#define M_CONTROLLER M_SIMULATION->controller()
const GenFTypeConcr<FWallRepulsion> f_wall_repulsion("FWallRepulsion");
//---- Constructors/Destructor ----
FWallRepulsion::FWallRepulsion(Simulation *simulation)
: FParticle(simulation)
{
init();
}
FWallRepulsion::~FWallRepulsion()
{
}
void FWallRepulsion::init()
{
m_properties.setClassName("FWallRepulsion");
m_properties.setDescription
("Heat flux from two parallel walls to the fluid."
);
DOUBLEPC
(cutoff, m_cutoff, 0,
"Cut-off distance from the wall.");
DOUBLEPC
(force, m_force, 0,
"Heat conduction coefficient.");
INTPC
(wallDir, m_wall_dir, -1,
"Direction in which to find the wall: 0 = x, 1 = y, 2 = z.");
m_properties.addProperty
("leftWall", PropertyList::DOUBLE, &m_left_wall, NULL,
"Position of the wall to the left.");
m_properties.addProperty
("rightWall", PropertyList::DOUBLE, &m_right_wall, NULL,
"Position of the wall to the right.");
m_wall_dir = 0;
m_cutoff = 1;
m_force = 1;
m_left_wall = -10;
m_right_wall = 10;
m_is_pair_force = false;
m_is_particle_force = true;
}
//---- Methods ----
void FWallRepulsion::computeForces(Particle* part, int force_index)
{
Phase *phase = M_PHASE;
point_t n = {{{ 0, 0, 0 }}};
n[m_wall_dir] = 1;
FOR_EACH_PARTICLE_C
(phase,
m_colour,
double weight = 0;
if (__iSLFE->r[m_wall_dir] < m_left_wall+m_cutoff) {
weight = 1-(__iSLFE->r[m_wall_dir]-m_left_wall)*m_rcinv;
} else if (__iSLFE->r[m_wall_dir] > m_right_wall-m_cutoff) {
weight = -(1-(m_right_wall-__iSLFE->r[m_wall_dir])*m_rcinv);
}
__iSLFE->force[force_index] += weight * m_force * n;
);
}
#ifndef _OPENMP
void FWallRepulsion::computeForces(Pairdist* pair, int force_index)
#else
void FWallRepulsion::computeForces(Pairdist* pair, int force_index, int thread_no)
#endif
{
throw gError("FWallRepulsion::computeForces", "Fatal error: do not call FWallRepulsion::computeForces(Pairdist* pair, int force_index)!!! Needs a Particle argument. Please contact the programmer!");
}
void FWallRepulsion::computeForces(int force_index)
{
throw gError("FWallRepulsion::computeForces", "Fatal error: do not call FWallRepulsion::computeForces(int force_index)!!! Needs a Particle argument. Please contact the programmer!");
}
void FWallRepulsion::setup()
{
FParticle::setup();
m_rcinv = 1/m_cutoff;
}
| argreiner/sympler | source/src/force/f_wall_repulsion.cpp | C++ | gpl-3.0 | 3,841 |
#
# The Python Imaging Library.
# $Id$
#
# base class for image file handlers
#
# history:
# 1995-09-09 fl Created
# 1996-03-11 fl Fixed load mechanism.
# 1996-04-15 fl Added pcx/xbm decoders.
# 1996-04-30 fl Added encoders.
# 1996-12-14 fl Added load helpers
# 1997-01-11 fl Use encode_to_file where possible
# 1997-08-27 fl Flush output in _save
# 1998-03-05 fl Use memory mapping for some modes
# 1999-02-04 fl Use memory mapping also for "I;16" and "I;16B"
# 1999-05-31 fl Added image parser
# 2000-10-12 fl Set readonly flag on memory-mapped images
# 2002-03-20 fl Use better messages for common decoder errors
# 2003-04-21 fl Fall back on mmap/map_buffer if map is not available
# 2003-10-30 fl Added StubImageFile class
# 2004-02-25 fl Made incremental parser more robust
#
# Copyright (c) 1997-2004 by Secret Labs AB
# Copyright (c) 1995-2004 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#
from . import Image
from ._util import isPath
import io
import sys
import struct
MAXBLOCK = 65536
SAFEBLOCK = 1024*1024
LOAD_TRUNCATED_IMAGES = False
ERRORS = {
-1: "image buffer overrun error",
-2: "decoding error",
-3: "unknown error",
-8: "bad configuration",
-9: "out of memory error"
}
def raise_ioerror(error):
try:
message = Image.core.getcodecstatus(error)
except AttributeError:
message = ERRORS.get(error)
if not message:
message = "decoder error %d" % error
raise IOError(message + " when reading image file")
#
# --------------------------------------------------------------------
# Helpers
def _tilesort(t):
# sort on offset
return t[2]
#
# --------------------------------------------------------------------
# ImageFile base class
class ImageFile(Image.Image):
"Base class for image file format handlers."
def __init__(self, fp=None, filename=None):
Image.Image.__init__(self)
self._min_frame = 0
self.tile = None
self.readonly = 1 # until we know better
self.decoderconfig = ()
self.decodermaxblock = MAXBLOCK
if isPath(fp):
# filename
self.fp = open(fp, "rb")
self.filename = fp
self._exclusive_fp = True
else:
# stream
self.fp = fp
self.filename = filename
# can be overridden
self._exclusive_fp = None
try:
self._open()
except (IndexError, # end of data
TypeError, # end of data (ord)
KeyError, # unsupported mode
EOFError, # got header but not the first frame
struct.error) as v:
# close the file only if we have opened it this constructor
if self._exclusive_fp:
self.fp.close()
raise SyntaxError(v)
if not self.mode or self.size[0] <= 0:
raise SyntaxError("not identified by this driver")
def draft(self, mode, size):
"Set draft mode"
pass
def get_format_mimetype(self):
if self.format is None:
return
return Image.MIME.get(self.format.upper())
def verify(self):
"Check file integrity"
# raise exception if something's wrong. must be called
# directly after open, and closes file when finished.
if self._exclusive_fp:
self.fp.close()
self.fp = None
def load(self):
"Load image data based on tile list"
pixel = Image.Image.load(self)
if self.tile is None:
raise IOError("cannot load this image")
if not self.tile:
return pixel
self.map = None
use_mmap = self.filename and len(self.tile) == 1
# As of pypy 2.1.0, memory mapping was failing here.
use_mmap = use_mmap and not hasattr(sys, 'pypy_version_info')
readonly = 0
# look for read/seek overrides
try:
read = self.load_read
# don't use mmap if there are custom read/seek functions
use_mmap = False
except AttributeError:
read = self.fp.read
try:
seek = self.load_seek
use_mmap = False
except AttributeError:
seek = self.fp.seek
if use_mmap:
# try memory mapping
decoder_name, extents, offset, args = self.tile[0]
if decoder_name == "raw" and len(args) >= 3 and \
args[0] == self.mode and \
args[0] in Image._MAPMODES:
try:
if hasattr(Image.core, "map"):
# use built-in mapper WIN32 only
self.map = Image.core.map(self.filename)
self.map.seek(offset)
self.im = self.map.readimage(
self.mode, self.size, args[1], args[2]
)
else:
# use mmap, if possible
import mmap
with open(self.filename, "r") as fp:
self.map = mmap.mmap(fp.fileno(), 0,
access=mmap.ACCESS_READ)
self.im = Image.core.map_buffer(
self.map, self.size, decoder_name, extents,
offset, args)
readonly = 1
# After trashing self.im,
# we might need to reload the palette data.
if self.palette:
self.palette.dirty = 1
except (AttributeError, EnvironmentError, ImportError):
self.map = None
self.load_prepare()
err_code = -3 # initialize to unknown error
if not self.map:
# sort tiles in file order
self.tile.sort(key=_tilesort)
try:
# FIXME: This is a hack to handle TIFF's JpegTables tag.
prefix = self.tile_prefix
except AttributeError:
prefix = b""
for decoder_name, extents, offset, args in self.tile:
decoder = Image._getdecoder(self.mode, decoder_name,
args, self.decoderconfig)
try:
seek(offset)
decoder.setimage(self.im, extents)
if decoder.pulls_fd:
decoder.setfd(self.fp)
status, err_code = decoder.decode(b"")
else:
b = prefix
while True:
try:
s = read(self.decodermaxblock)
except (IndexError, struct.error):
# truncated png/gif
if LOAD_TRUNCATED_IMAGES:
break
else:
raise IOError("image file is truncated")
if not s: # truncated jpeg
if LOAD_TRUNCATED_IMAGES:
break
else:
self.tile = []
raise IOError("image file is truncated "
"(%d bytes not processed)" %
len(b))
b = b + s
n, err_code = decoder.decode(b)
if n < 0:
break
b = b[n:]
finally:
# Need to cleanup here to prevent leaks
decoder.cleanup()
self.tile = []
self.readonly = readonly
self.load_end()
if self._exclusive_fp and self._close_exclusive_fp_after_loading:
self.fp.close()
self.fp = None
if not self.map and not LOAD_TRUNCATED_IMAGES and err_code < 0:
# still raised if decoder fails to return anything
raise_ioerror(err_code)
return Image.Image.load(self)
def load_prepare(self):
# create image memory if necessary
if not self.im or\
self.im.mode != self.mode or self.im.size != self.size:
self.im = Image.core.new(self.mode, self.size)
# create palette (optional)
if self.mode == "P":
Image.Image.load(self)
def load_end(self):
# may be overridden
pass
# may be defined for contained formats
# def load_seek(self, pos):
# pass
# may be defined for blocked formats (e.g. PNG)
# def load_read(self, bytes):
# pass
def _seek_check(self, frame):
if (frame < self._min_frame or
# Only check upper limit on frames if additional seek operations
# are not required to do so
(not (hasattr(self, "_n_frames") and self._n_frames is None) and
frame >= self.n_frames+self._min_frame)):
raise EOFError("attempt to seek outside sequence")
return self.tell() != frame
class StubImageFile(ImageFile):
"""
Base class for stub image loaders.
A stub loader is an image loader that can identify files of a
certain format, but relies on external code to load the file.
"""
def _open(self):
raise NotImplementedError(
"StubImageFile subclass must implement _open"
)
def load(self):
loader = self._load()
if loader is None:
raise IOError("cannot find loader for this %s file" % self.format)
image = loader.load(self)
assert image is not None
# become the other object (!)
self.__class__ = image.__class__
self.__dict__ = image.__dict__
def _load(self):
"(Hook) Find actual image loader."
raise NotImplementedError(
"StubImageFile subclass must implement _load"
)
class Parser(object):
"""
Incremental image parser. This class implements the standard
feed/close consumer interface.
"""
incremental = None
image = None
data = None
decoder = None
offset = 0
finished = 0
def reset(self):
"""
(Consumer) Reset the parser. Note that you can only call this
method immediately after you've created a parser; parser
instances cannot be reused.
"""
assert self.data is None, "cannot reuse parsers"
def feed(self, data):
"""
(Consumer) Feed data to the parser.
:param data: A string buffer.
:exception IOError: If the parser failed to parse the image file.
"""
# collect data
if self.finished:
return
if self.data is None:
self.data = data
else:
self.data = self.data + data
# parse what we have
if self.decoder:
if self.offset > 0:
# skip header
skip = min(len(self.data), self.offset)
self.data = self.data[skip:]
self.offset = self.offset - skip
if self.offset > 0 or not self.data:
return
n, e = self.decoder.decode(self.data)
if n < 0:
# end of stream
self.data = None
self.finished = 1
if e < 0:
# decoding error
self.image = None
raise_ioerror(e)
else:
# end of image
return
self.data = self.data[n:]
elif self.image:
# if we end up here with no decoder, this file cannot
# be incrementally parsed. wait until we've gotten all
# available data
pass
else:
# attempt to open this file
try:
with io.BytesIO(self.data) as fp:
im = Image.open(fp)
except IOError:
# traceback.print_exc()
pass # not enough data
else:
flag = hasattr(im, "load_seek") or hasattr(im, "load_read")
if flag or len(im.tile) != 1:
# custom load code, or multiple tiles
self.decode = None
else:
# initialize decoder
im.load_prepare()
d, e, o, a = im.tile[0]
im.tile = []
self.decoder = Image._getdecoder(
im.mode, d, a, im.decoderconfig
)
self.decoder.setimage(im.im, e)
# calculate decoder offset
self.offset = o
if self.offset <= len(self.data):
self.data = self.data[self.offset:]
self.offset = 0
self.image = im
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(self):
"""
(Consumer) Close the stream.
:returns: An image object.
:exception IOError: If the parser failed to parse the image file either
because it cannot be identified or cannot be
decoded.
"""
# finish decoding
if self.decoder:
# get rid of what's left in the buffers
self.feed(b"")
self.data = self.decoder = None
if not self.finished:
raise IOError("image was incomplete")
if not self.image:
raise IOError("cannot parse this image")
if self.data:
# incremental parsing not possible; reopen the file
# not that we have all data
with io.BytesIO(self.data) as fp:
try:
self.image = Image.open(fp)
finally:
self.image.load()
return self.image
# --------------------------------------------------------------------
def _save(im, fp, tile, bufsize=0):
"""Helper to save image based on tile list
:param im: Image object.
:param fp: File object.
:param tile: Tile list.
:param bufsize: Optional buffer size
"""
im.load()
if not hasattr(im, "encoderconfig"):
im.encoderconfig = ()
tile.sort(key=_tilesort)
# FIXME: make MAXBLOCK a configuration parameter
# It would be great if we could have the encoder specify what it needs
# But, it would need at least the image size in most cases. RawEncode is
# a tricky case.
bufsize = max(MAXBLOCK, bufsize, im.size[0] * 4) # see RawEncode.c
if fp == sys.stdout:
fp.flush()
return
try:
fh = fp.fileno()
fp.flush()
except (AttributeError, io.UnsupportedOperation):
# compress to Python file-compatible object
for e, b, o, a in tile:
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
if o > 0:
fp.seek(o, 0)
e.setimage(im.im, b)
if e.pushes_fd:
e.setfd(fp)
l, s = e.encode_to_pyfd()
else:
while True:
l, s, d = e.encode(bufsize)
fp.write(d)
if s:
break
if s < 0:
raise IOError("encoder error %d when writing image file" % s)
e.cleanup()
else:
# slight speedup: compress to real file object
for e, b, o, a in tile:
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
if o > 0:
fp.seek(o, 0)
e.setimage(im.im, b)
if e.pushes_fd:
e.setfd(fp)
l, s = e.encode_to_pyfd()
else:
s = e.encode_to_file(fh, bufsize)
if s < 0:
raise IOError("encoder error %d when writing image file" % s)
e.cleanup()
if hasattr(fp, "flush"):
fp.flush()
def _safe_read(fp, size):
"""
Reads large blocks in a safe way. Unlike fp.read(n), this function
doesn't trust the user. If the requested size is larger than
SAFEBLOCK, the file is read block by block.
:param fp: File handle. Must implement a <b>read</b> method.
:param size: Number of bytes to read.
:returns: A string containing up to <i>size</i> bytes of data.
"""
if size <= 0:
return b""
if size <= SAFEBLOCK:
return fp.read(size)
data = []
while size > 0:
block = fp.read(min(size, SAFEBLOCK))
if not block:
break
data.append(block)
size -= len(block)
return b"".join(data)
class PyCodecState(object):
def __init__(self):
self.xsize = 0
self.ysize = 0
self.xoff = 0
self.yoff = 0
def extents(self):
return (self.xoff, self.yoff,
self.xoff+self.xsize, self.yoff+self.ysize)
class PyDecoder(object):
"""
Python implementation of a format decoder. Override this class and
add the decoding logic in the `decode` method.
See :ref:`Writing Your Own File Decoder in Python<file-decoders-py>`
"""
_pulls_fd = False
def __init__(self, mode, *args):
self.im = None
self.state = PyCodecState()
self.fd = None
self.mode = mode
self.init(args)
def init(self, args):
"""
Override to perform decoder specific initialization
:param args: Array of args items from the tile entry
:returns: None
"""
self.args = args
@property
def pulls_fd(self):
return self._pulls_fd
def decode(self, buffer):
"""
Override to perform the decoding process.
:param buffer: A bytes object with the data to be decoded.
If `handles_eof` is set, then `buffer` will be empty and `self.fd`
will be set.
:returns: A tuple of (bytes consumed, errcode).
If finished with decoding return <0 for the bytes consumed.
Err codes are from `ERRORS`
"""
raise NotImplementedError()
def cleanup(self):
"""
Override to perform decoder specific cleanup
:returns: None
"""
pass
def setfd(self, fd):
"""
Called from ImageFile to set the python file-like object
:param fd: A python file-like object
:returns: None
"""
self.fd = fd
def setimage(self, im, extents=None):
"""
Called from ImageFile to set the core output image for the decoder
:param im: A core image object
:param extents: a 4 tuple of (x0, y0, x1, y1) defining the rectangle
for this tile
:returns: None
"""
# following c code
self.im = im
if extents:
(x0, y0, x1, y1) = extents
else:
(x0, y0, x1, y1) = (0, 0, 0, 0)
if x0 == 0 and x1 == 0:
self.state.xsize, self.state.ysize = self.im.size
else:
self.state.xoff = x0
self.state.yoff = y0
self.state.xsize = x1 - x0
self.state.ysize = y1 - y0
if self.state.xsize <= 0 or self.state.ysize <= 0:
raise ValueError("Size cannot be negative")
if (self.state.xsize + self.state.xoff > self.im.size[0] or
self.state.ysize + self.state.yoff > self.im.size[1]):
raise ValueError("Tile cannot extend outside image")
def set_as_raw(self, data, rawmode=None):
"""
Convenience method to set the internal image from a stream of raw data
:param data: Bytes to be set
:param rawmode: The rawmode to be used for the decoder.
If not specified, it will default to the mode of the image
:returns: None
"""
if not rawmode:
rawmode = self.mode
d = Image._getdecoder(self.mode, 'raw', (rawmode))
d.setimage(self.im, self.state.extents())
s = d.decode(data)
if s[0] >= 0:
raise ValueError("not enough image data")
if s[1] != 0:
raise ValueError("cannot decode image data")
| kenshay/ImageScript | ProgramData/SystemFiles/Python/Lib/site-packages/PIL/ImageFile.py | Python | gpl-3.0 | 20,762 |
<?php
/**
* Trending script for graphing objects.
*
* @package OpenEMR
* @link http://www.open-emr.org
* @author Brady Miller <brady.g.miller@gmail.com>
* @author Rod Roark <rod@sunsetsystems.com>
* @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
* @copyright Copyright (c) 2010-2017 Brady Miller <brady.g.miller@gmail.com>
* @copyright Copyright (c) 2011 Rod Roark <rod@sunsetsystems.com>
*/
$special_timeout = 3600;
include_once("../../globals.php");
$formname = $_GET["formname"];
$is_lbf = substr($formname, 0, 3) === 'LBF';
if ($is_lbf) {
// Determine the default field ID and its title for graphing.
// This is from the last graphable field in the form.
$default = sqlQuery(
"SELECT field_id, title FROM layout_options WHERE " .
"form_id = ? AND uor > 0 AND edit_options LIKE '%G%' " .
"ORDER BY group_name DESC, seq DESC, title DESC LIMIT 1",
array($formname)
);
}
//Bring in the style sheet
?>
<?php require $GLOBALS['srcdir'] . '/js/xl/dygraphs.js.php'; ?>
<link rel="stylesheet" href="<?php echo $css_header;?>" type="text/css">
<link rel="stylesheet" href="<?php echo $GLOBALS['assets_static_relative']; ?>/modified/dygraphs-2-0-0/dygraph.css" type="text/css"></script>
<?php
// Hide the current value css entries. This is currently specific
// for the vitals form but could use this mechanism for other
// forms.
// Hiding classes:
// currentvalues - input boxes
// valuesunfocus - input boxes that are auto-calculated
// editonly - the edit and cancel buttons
// Showing class:
// readonly - the link back to summary screen
// Also customize the 'graph' class to look like links.
?>
<style>
.currentvalues { display: none;}
.valuesunfocus { display: none;}
.editonly { display: none;}
.graph {color:#0000cc;}
#chart {
margin:0em 1em 2em 2em;
}
</style>
<script type="text/javascript" src="<?php echo $GLOBALS['assets_static_relative']; ?>/jquery-min-1-7-2/index.js"></script>
<script type="text/javascript" src="<?php echo $GLOBALS['assets_static_relative']; ?>/modified/dygraphs-2-0-0/dygraph.js?v=<?php echo $v_js_includes; ?>"></script>
<script type="text/javascript">
// Show the selected chart in the 'chart' div element
function show_graph(table_graph, name_graph, title_graph)
{
top.restoreSession();
$.ajax({ url: '../../../library/ajax/graphs.php',
type: 'POST',
data: ({
table: table_graph,
name: name_graph,
title: title_graph
}),
dataType: "json",
success: function(returnData){
g2 = new Dygraph(
document.getElementById("chart"),
returnData.data_final,
{
title: returnData.title,
delimiter: '\t',
xRangePad: 20,
yRangePad: 20,
xlabel: xlabel_translate
}
);
// ensure show the chart div
$('#chart').show();
},
error: function() {
// hide the chart div
$('#chart').hide();
}
});
}
$(document).ready(function(){
// Use jquery to show the 'readonly' class entries
$('.readonly').show();
// Place click callback for graphing
<?php if ($is_lbf) { ?>
// For LBF the <td> has an id of label_id_$fieldid
$(".graph").click(function(e){ show_graph('<?php echo $formname; ?>', this.id.substring(9), $(this).text()) });
<?php } else { ?>
$(".graph").click(function(e){ show_graph('form_vitals', this.id, $(this).text()) });
<?php } ?>
// Show hovering effects for the .graph links
$(".graph").hover(
function(){
$(this).css({color:'#ff5555'}); //mouseover
},
function(){
$(this).css({color:'#0000cc'}); // mouseout
}
);
// show blood pressure graph by default
<?php if ($is_lbf) { ?>
show_graph('<?php echo $formname; ?>','<?php echo $default['field_id']; ?>','<?php echo $default['title']; ?>');
<?php } else { ?>
show_graph('form_vitals','bps','');
<?php } ?>
});
</script>
<?php
if ($is_lbf) {
// Use the List Based Forms engine for all LBFxxxxx forms.
include_once("$incdir/forms/LBF/new.php");
} else {
// ensure the path variable has no illegal characters
check_file_dir_name($formname);
include_once("$incdir/forms/$formname/new.php");
}
?>
| Jeffrey-P-McAteer/openemr | interface/patient_file/encounter/trend_form.php | PHP | gpl-3.0 | 4,401 |
/// Check the behavior of toolchain for NEC Aurora VE
/// REQUIRES: ve-registered-target
///-----------------------------------------------------------------------------
/// Checking dwarf-version
// RUN: %clangxx -### -g -target ve %s 2>&1 | FileCheck -check-prefix=DWARF_VER %s
// DWARF_VER: "-dwarf-version=4"
///-----------------------------------------------------------------------------
/// Checking include-path
// RUN: %clangxx -### -target ve --sysroot %S/Inputs/basic_ve_tree %s \
// RUN: -resource-dir=%S/Input/basic_ve_tree/resource_dir \
// RUN: 2>&1 | FileCheck -check-prefix=DEFINC %s
// DEFINC: clang{{.*}} "-cc1"
// DEFINC-SAME: "-nostdsysteminc"
// DEFINC-SAME: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// DEFINC-SAME: "-isysroot" "[[SYSROOT:[^"]+]]"
// DEFINC-SAME: "-internal-isystem" "[[RESOURCE_DIR]]/include/c++/v1"
// DEFINC-SAME: "-internal-isystem" "[[RESOURCE_DIR]]/include"
// DEFINC-SAME: "-internal-isystem" "[[SYSROOT]]/opt/nec/ve/include"
// RUN: %clangxx -### -target ve --sysroot %S/Inputs/basic_ve_tree %s \
// RUN: -resource-dir=%S/Input/basic_ve_tree/resource_dir \
// RUN: -nostdlibinc 2>&1 | FileCheck -check-prefix=NOSTDLIBINC %s
// NOSTDLIBINC: clang{{.*}} "-cc1"
// NOSTDLIBINC-SAME: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// NOSTDLIBINC-SAME: "-isysroot" "[[SYSROOT:[^"]+]]"
// NOSTDLIBINC-NOT: "-internal-isystem" "[[RESOURCE_DIR]]/include/c++/v1"
// NOSTDLIBINC-SAME: "-internal-isystem" "[[RESOURCE_DIR]]/include"
// NOSTDLIBINC-NOT: "-internal-isystem" "[[SYSROOT]]/opt/nec/ve/include"
// RUN: %clangxx -### -target ve --sysroot %S/Inputs/basic_ve_tree %s \
// RUN: -resource-dir=%S/Input/basic_ve_tree/resource_dir \
// RUN: -nobuiltininc 2>&1 | FileCheck -check-prefix=NOBUILTININC %s
// NOBUILTININC: clang{{.*}} "-cc1"
// NOBUILTININC-SAME: "-nobuiltininc"
// NOBUILTININC-SAME: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// NOBUILTININC-SAME: "-isysroot" "[[SYSROOT:[^"]+]]"
// NOBUILTININC-SAME: "-internal-isystem" "[[RESOURCE_DIR]]/include/c++/v1"
// NOBUILTININC-NOT: "-internal-isystem" "[[RESOURCE_DIR]]/include"
// NOBUILTININC-SAME: "-internal-isystem" "[[SYSROOT]]/opt/nec/ve/include"
// RUN: %clangxx -### -target ve --sysroot %S/Inputs/basic_ve_tree %s \
// RUN: -resource-dir=%S/Input/basic_ve_tree/resource_dir \
// RUN: -nostdinc 2>&1 | FileCheck -check-prefix=NOSTDINC %s
// NOSTDINC: clang{{.*}} "-cc1"
// NOSTDINC-SAME: "-nobuiltininc"
// NOSTDINC-SAME: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// NOSTDINC-SAME: "-isysroot" "[[SYSROOT:[^"]+]]"
// NOSTDINC-NOT: "-internal-isystem" "[[RESOURCE_DIR]]/include/c++/v1"
// NOSTDINC-NOT: "-internal-isystem" "[[RESOURCE_DIR]]/include"
// NOSTDINC-NOT: "-internal-isystem" "[[SYSROOT]]/opt/nec/ve/include"
// RUN: %clangxx -### -target ve --sysroot %S/Inputs/basic_ve_tree %s \
// RUN: -resource-dir=%S/Input/basic_ve_tree/resource_dir \
// RUN: -nostdinc++ 2>&1 | FileCheck -check-prefix=NOSTDINCXX %s
// NOSTDINCXX: clang{{.*}} "-cc1"
// NOSTDINCXX-SAME: "-nostdinc++"
// NOSTDINCXX-SAME: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// NOSTDINCXX-SAME: "-isysroot" "[[SYSROOT:[^"]+]]"
// NOSTDINCXX-NOT: "-internal-isystem" "[[RESOURCE_DIR]]/include/c++/v1"
// NOSTDINCXX-SAME: "-internal-isystem" "[[RESOURCE_DIR]]/include"
// NOSTDINCXX-SAME: "-internal-isystem" "[[SYSROOT]]/opt/nec/ve/include"
///-----------------------------------------------------------------------------
/// Checking environment variable NCC_CPLUS_INCLUDE_PATH
// RUN: env NCC_CPLUS_INCLUDE_PATH=/test/test %clangxx -### -target ve %s \
// RUN: --sysroot %S/Inputs/basic_ve_tree \
// RUN: -resource-dir=%S/Input/basic_ve_tree/resource_dir \
// RUN: 2>&1 | FileCheck -check-prefix=DEFINCENV %s
// DEFINCENV: clang{{.*}} "-cc1"
// DEFINCENV-SAME: "-nostdsysteminc"
// DEFINCENV-SAME: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// DEFINCENV-SAME: "-isysroot" "[[SYSROOT:[^"]+]]"
// DEFINCENV-SAME: "-internal-isystem" "/test/test"
// DEFINCENV-SAME: "-internal-isystem" "[[RESOURCE_DIR]]/include"
// DEFINCENV-SAME: "-internal-isystem" "[[SYSROOT]]/opt/nec/ve/include"
///-----------------------------------------------------------------------------
/// Checking -faddrsig
// RUN: %clangxx -### -target ve %s 2>&1 | FileCheck -check-prefix=DEFADDRSIG %s
// DEFADDRSIG: clang{{.*}} "-cc1"
// DEFADDRSIG-NOT: "-faddrsig"
///-----------------------------------------------------------------------------
/// Checking -fintegrated-as
// RUN: %clangxx -### -target ve -x assembler %s 2>&1 | \
// RUN: FileCheck -check-prefix=AS %s
// RUN: %clangxx -### -target ve -fno-integrated-as -x assembler %s 2>&1 | \
// RUN: FileCheck -check-prefix=NAS %s
// AS: clang{{.*}} "-cc1as"
// AS: nld{{.*}}
// NAS: nas{{.*}}
// NAS: nld{{.*}}
///-----------------------------------------------------------------------------
/// Checking default behavior:
/// - dynamic linker
/// - library paths
/// - nld VE specific options
/// - sjlj exception
// RUN: %clangxx -### -target ve-unknown-linux-gnu \
// RUN: --sysroot %S/Inputs/basic_ve_tree \
// RUN: -resource-dir=%S/Inputs/basic_ve_tree/resource_dir \
// RUN: --stdlib=c++ %s 2>&1 | FileCheck -check-prefix=DEF %s
// DEF: clang{{.*}}" "-cc1"
// DEF-SAME: "-resource-dir" "[[RESOURCE_DIR:[^"]+]]"
// DEF-SAME: "-isysroot" "[[SYSROOT:[^"]+]]"
// DEF-SAME: "-exception-model=sjlj"
// DEF: nld"
// DEF-SAME: "--sysroot=[[SYSROOT]]"
// DEF-SAME: "-dynamic-linker" "/opt/nec/ve/lib/ld-linux-ve.so.1"
// DEF-SAME: "[[SYSROOT]]/opt/nec/ve/lib/crt1.o"
// DEF-SAME: "[[SYSROOT]]/opt/nec/ve/lib/crti.o"
// DEF-SAME: "-z" "max-page-size=0x4000000"
// DEF-SAME: "[[RESOURCE_DIR]]/lib/linux/clang_rt.crtbegin-ve.o"
// DEF-SAME: "-lc++" "-lc++abi" "-lunwind" "-lpthread" "-ldl"
// DEF-SAME: "[[RESOURCE_DIR]]/lib/linux/libclang_rt.builtins-ve.a" "-lc"
// DEF-SAME: "[[RESOURCE_DIR]]/lib/linux/libclang_rt.builtins-ve.a"
// DEF-SAME: "[[RESOURCE_DIR]]/lib/linux/clang_rt.crtend-ve.o"
// DEF-SAME: "[[SYSROOT]]/opt/nec/ve/lib/crtn.o"
| sabel83/metashell | 3rd/templight/clang/test/Driver/ve-toolchain.cpp | C++ | gpl-3.0 | 6,036 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "findincurrentfile.h"
#include "texteditor.h"
#include "textdocument.h"
#include <utils/filesearch.h>
#include <utils/fileutils.h>
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/editormanager/editormanager.h>
#include <QSettings>
using namespace TextEditor;
using namespace TextEditor::Internal;
FindInCurrentFile::FindInCurrentFile()
{
connect(Core::EditorManager::instance(), &Core::EditorManager::currentEditorChanged,
this, &FindInCurrentFile::handleFileChange);
handleFileChange(Core::EditorManager::currentEditor());
}
QString FindInCurrentFile::id() const
{
return QLatin1String("Current File");
}
QString FindInCurrentFile::displayName() const
{
return tr("Current File");
}
Utils::FileIterator *FindInCurrentFile::files(const QStringList &nameFilters,
const QStringList &exclusionFilters,
const QVariant &additionalParameters) const
{
Q_UNUSED(nameFilters)
Q_UNUSED(exclusionFilters)
QString fileName = additionalParameters.toString();
QMap<QString, QTextCodec *> openEditorEncodings = TextDocument::openedTextDocumentEncodings();
QTextCodec *codec = openEditorEncodings.value(fileName);
if (!codec)
codec = Core::EditorManager::defaultTextCodec();
return new Utils::FileListIterator({fileName}, {codec});
}
QVariant FindInCurrentFile::additionalParameters() const
{
return QVariant::fromValue(m_currentDocument->filePath().toString());
}
QString FindInCurrentFile::label() const
{
return tr("File \"%1\":").arg(m_currentDocument->filePath().fileName());
}
QString FindInCurrentFile::toolTip() const
{
// %2 is filled by BaseFileFind::runNewSearch
return tr("File path: %1\n%2").arg(m_currentDocument->filePath().toUserOutput());
}
bool FindInCurrentFile::isEnabled() const
{
return m_currentDocument && !m_currentDocument->filePath().isEmpty();
}
void FindInCurrentFile::handleFileChange(Core::IEditor *editor)
{
if (!editor) {
if (m_currentDocument) {
m_currentDocument = nullptr;
emit enabledChanged(isEnabled());
}
} else {
Core::IDocument *document = editor->document();
if (document != m_currentDocument) {
m_currentDocument = document;
emit enabledChanged(isEnabled());
}
}
}
void FindInCurrentFile::writeSettings(QSettings *settings)
{
settings->beginGroup(QLatin1String("FindInCurrentFile"));
writeCommonSettings(settings);
settings->endGroup();
}
void FindInCurrentFile::readSettings(QSettings *settings)
{
settings->beginGroup(QLatin1String("FindInCurrentFile"));
readCommonSettings(settings, "*", "");
settings->endGroup();
}
| qtproject/qt-creator | src/plugins/texteditor/findincurrentfile.cpp | C++ | gpl-3.0 | 4,015 |
# coding=utf-8
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**QGIS plugin implementation.**
Contact : ole.moller.nielsen@gmail.com
.. note:: 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.
.. note:: This source code was copied from the 'postgis viewer' application
with original authors:
Copyright (c) 2010 by Ivan Mincik, ivan.mincik@gista.sk
Copyright (c) 2011 German Carrillo, geotux_tuxman@linuxmail.org
"""
__author__ = 'tim@kartoza.com'
__revision__ = '$Format:%H$'
__date__ = '10/01/2011'
__copyright__ = (
'Copyright (c) 2010 by Ivan Mincik, ivan.mincik@gista.sk and '
'Copyright (c) 2011 German Carrillo, geotux_tuxman@linuxmail.org'
'Copyright (c) 2014 Tim Sutton, tim@kartoza.com'
)
import logging
from qgis.core import QgsMapLayerRegistry, QGis, QgsMapLayer
# pylint: disable=no-name-in-module
from qgis.gui import (
QgsMapCanvasLayer,
QgsMessageBar)
from PyQt4.QtCore import QObject, pyqtSlot, pyqtSignal
from safe.gis.qgis_legend_interface import QgisLegend
LOGGER = logging.getLogger('InaSAFE')
# noinspection PyMethodMayBeStatic,PyPep8Naming
class QgisInterface(QObject):
"""Class to expose qgis objects and functions to plugins.
This class is here for enabling us to run unit tests only,
so most methods are simply stubs.
"""
currentLayerChanged = pyqtSignal(QgsMapCanvasLayer)
layerSavedAs = pyqtSignal(QgsMapLayer, str)
def __init__(self, canvas):
"""Constructor
:param canvas:
"""
QObject.__init__(self)
self.canvas = canvas
self.legend = QgisLegend(canvas)
self.message_bar = QgsMessageBar(None)
# Set up slots so we can mimic the behaviour of QGIS when layers
# are added.
LOGGER.debug('Initialising canvas...')
# noinspection PyArgumentList
QgsMapLayerRegistry.instance().layersAdded.connect(self.addLayers)
# noinspection PyArgumentList
QgsMapLayerRegistry.instance().layerWasAdded.connect(self.addLayer)
# noinspection PyArgumentList
QgsMapLayerRegistry.instance().removeAll.connect(self.removeAllLayers)
# For processing module
self.destCrs = None
# For keeping track of which layer is active in the legend.
self.active_layer = None
# In the next section of code, we are going to do some monkey patching
# to make the QGIS processing framework think that this mock QGIS IFACE
# instance is the actual one. It will also ensure that the processing
# algorithms are nicely loaded and available for use.
# Since QGIS > 2.0, the module is moved from QGisLayers to dataobjects
# pylint: disable=F0401, E0611
if QGis.QGIS_VERSION_INT > 20001:
# noinspection PyUnresolvedReferences
from processing.tools import dataobjects
else:
# noinspection PyUnresolvedReferences
from processing.core import QGisLayers as dataobjects
# noinspection PyUnresolvedReferences
import processing
# noinspection PyUnresolvedReferences
from processing.core.Processing import Processing
# pylint: enable=F0401, E0611
processing.classFactory(self)
# We create our own getAlgorithm function below which will will monkey
# patch in to the Processing class in QGIS in order to ensure that the
# Processing.initialize() call is made before asking for an alg.
@staticmethod
def mock_getAlgorithm(name):
"""
Modified version of the original getAlgorithm function.
:param name: Name of the algorithm to load.
:type name: str
:return: An algorithm concrete class.
:rtype: QgsAlgorithm ?
"""
Processing.initialize()
for provider in Processing.algs.values():
if name in provider:
return provider[name]
return None
# Now we let the monkey loose!
Processing.getAlgorithm = mock_getAlgorithm
# We also need to make dataobjects think that this iface is 'the one'
# Note. the placement here (after the getAlgorithm monkey patch above)
# is significant, so don't move it!
dataobjects.iface = self
def __getattr__(self, *args, **kwargs):
# It's for processing module
def dummy(*a, **kwa):
_ = a, kwa
return QgisInterface(self.canvas)
return dummy
def __iter__(self):
# It's for processing module
return self
def next(self):
# It's for processing module
raise StopIteration
def layers(self):
# It's for processing module
# simulate iface.legendInterface().layers()
return QgsMapLayerRegistry.instance().mapLayers().values()
@pyqtSlot('QStringList')
def addLayers(self, layers):
"""Handle layers being added to the registry so they show up in canvas.
:param layers: list<QgsMapLayer> list of map layers that were added
.. note:: The QgsInterface api does not include this method,
it is added here as a helper to facilitate testing.
"""
# LOGGER.debug('addLayers called on qgis_interface')
# LOGGER.debug('Number of layers being added: %s' % len(layers))
# LOGGER.debug('Layer Count Before: %s' % len(self.canvas.layers()))
current_layers = self.canvas.layers()
final_layers = []
# We need to keep the record of the registered layers on our canvas!
registered_layers = []
for layer in current_layers:
final_layers.append(QgsMapCanvasLayer(layer))
registered_layers.append(layer.id())
for layer in layers:
if layer.id() not in registered_layers:
final_layers.append(QgsMapCanvasLayer(layer))
self.canvas.setLayerSet(final_layers)
# LOGGER.debug('Layer Count After: %s' % len(self.canvas.layers()))
@pyqtSlot('QgsMapLayer')
def addLayer(self, layer):
"""Handle a layer being added to the registry so it shows up in canvas.
:param layer: list<QgsMapLayer> list of map layers that were added
.. note: The QgsInterface api does not include this method, it is added
here as a helper to facilitate testing.
.. note: The addLayer method was deprecated in QGIS 1.8 so you should
not need this method much.
"""
pass
@pyqtSlot()
def removeAllLayers(self, ):
"""Remove layers from the canvas before they get deleted.
.. note:: This is NOT part of the QGisInterface API but is needed
to support QgsMapLayerRegistry.removeAllLayers().
"""
self.canvas.setLayerSet([])
self.active_layer = None
def newProject(self):
"""Create new project."""
# noinspection PyArgumentList
QgsMapLayerRegistry.instance().removeAllMapLayers()
# ---------------- API Mock for QgsInterface follows -------------------
def zoomFull(self):
"""Zoom to the map full extent."""
pass
def zoomToPrevious(self):
"""Zoom to previous view extent."""
pass
def zoomToNext(self):
"""Zoom to next view extent."""
pass
def zoomToActiveLayer(self):
"""Zoom to extent of active layer."""
pass
def addVectorLayer(self, path, base_name, provider_key):
"""Add a vector layer.
:param path: Path to layer.
:type path: str
:param base_name: Base name for layer.
:type base_name: str
:param provider_key: Provider key e.g. 'ogr'
:type provider_key: str
"""
pass
def addRasterLayer(self, path, base_name):
"""Add a raster layer given a raster layer file name
:param path: Path to layer.
:type path: str
:param base_name: Base name for layer.
:type base_name: str
"""
pass
def setActiveLayer(self, layer):
"""Set the currently active layer in the legend.
:param layer: Layer to make active.
:type layer: QgsMapLayer, QgsVectorLayer, QgsRasterLayer
"""
self.active_layer = layer
def activeLayer(self):
"""Get pointer to the active layer (layer selected in the legend)."""
if self.active_layer is not None:
return self.active_layer
else:
return None
def addToolBarIcon(self, action):
"""Add an icon to the plugins toolbar.
:param action: Action to add to the toolbar.
:type action: QAction
"""
pass
def removeToolBarIcon(self, action):
"""Remove an action (icon) from the plugin toolbar.
:param action: Action to add to the toolbar.
:type action: QAction
"""
pass
def addToolBar(self, name):
"""Add toolbar with specified name.
:param name: Name for the toolbar.
:type name: str
"""
pass
def mapCanvas(self):
"""Return a pointer to the map canvas."""
return self.canvas
def mainWindow(self):
"""Return a pointer to the main window.
In case of QGIS it returns an instance of QgisApp.
"""
pass
def addDockWidget(self, area, dock_widget):
"""Add a dock widget to the main window.
:param area: Where in the ui the dock should be placed.
:type area:
:param dock_widget: A dock widget to add to the UI.
:type dock_widget: QDockWidget
"""
pass
def legendInterface(self):
"""Get the legend.
See also discussion at:
https://github.com/AIFDR/inasafe/pull/924/
Implementation added for version 3.2.
"""
return self.legend
def messageBar(self):
"""Get the message bar.
.. versionadded:: 3.2
:returns: A QGIS message bar instance
:rtype: QgsMessageBar
"""
return self.message_bar
| MariaSolovyeva/inasafe | safe/gis/qgis_interface.py | Python | gpl-3.0 | 10,359 |
package com.encens.khipus.service.employees;
import com.encens.khipus.model.contacts.Salutation;
import javax.ejb.Local;
/**
* User: Ariel
* Date: 22-03-2010
* Time: 09:05:12 PM
*/
@Local
public interface SalutationService {
Salutation getDefaultSalutation(String gender);
} | borboton13/sisk13 | src/main/com/encens/khipus/service/employees/SalutationService.java | Java | gpl-3.0 | 285 |
// srvice supported commands. These functions run the JSON-encoded commands
// sent by the server.
var srvice$actions = (function($) {
function statements(json) {
for (var i = 0; i < json.data.length; i++) {
srvice.exec(json.data[i]);
}
}
function redirect(json) {
if (json.as_link) {
window.location.href = json.url;
} else {
window.location.replace(json.url);
}
}
function dialog(json) {
srvice.show_dialog(json.data, json);
}
function refresh() {
window.location.replace('.');
}
function jquery(json) {
var method;
if (json.selector !== undefined) {
method = $[json.action];
} else {
method = $(json.selector)[json.action];
delete json.selector;
}
// Execute method
if (method !== undefined) {
throw 'invalid jQuery method: ' + json.action;
}
delete json.action;
return jsoncall(method, json);
}
function jquery_chain(json){
var action;
var query = $(json.selector);
for (var node in json.actions) {
if (json.actions.hasOwnProperty(node)) {
action = node.action;
delete node.action;
query = jsoncall(query[action], node);
}
}
return query;
}
return {statements: statements, redirect: redirect, refresh: refresh,
dialog:dialog, jquery_chain: jquery_chain };
})(jQuery); | jonnatas/codeschool | src/srvice/static/js/srvice/commands.js | JavaScript | gpl-3.0 | 1,568 |
from river.models.proceeding import Proceeding
from river.services.proceeding import ProceedingService
__author__ = 'ahmetdal'
# noinspection PyClassHasNoInit
class ObjectService:
@staticmethod
def register_object(workflow_object, field):
proceedings = Proceeding.objects.filter(workflow_object=workflow_object, field=field)
if proceedings.count() == 0:
ProceedingService.init_proceedings(workflow_object, field)
return {'state': getattr(workflow_object, field).details()}
@staticmethod
def get_objects_waiting_for_approval(content_type, field, user):
object_pks = []
WorkflowObjectClass = content_type.model_class()
for workflow_object in WorkflowObjectClass.objects.all():
current_state = getattr(workflow_object, field)
proceedings = ProceedingService.get_available_proceedings(workflow_object, field, [current_state], user=user)
if proceedings.count():
object_pks.append(workflow_object.pk)
return WorkflowObjectClass.objects.filter(pk__in=object_pks)
@staticmethod
def get_object_count_waiting_for_approval(content_type, field, user):
return ObjectService.get_objects_waiting_for_approval(content_type, field, user).count()
@staticmethod
def is_workflow_completed(workflow_object, field):
current_state = getattr(workflow_object, field)
return Proceeding.objects.filter(workflow_object=workflow_object, meta__transition__source_state=current_state).count() == 0
| mstzn36/django-river | river/services/object.py | Python | gpl-3.0 | 1,550 |
/*
* Copyright (C) 2015 Matthias Gabriel
*
* 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 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 com.gabm.fancyplaces.functional;
/**
* Created by gabm on 10/06/15.
*/
public interface IOnListModeChangeListener {
int MODE_NORMAL = 0;
int MODE_MULTI_SELECT = 1;
void onListModeChange(int newMode);
}
| gabm/FancyPlaces | app/src/main/java/com/gabm/fancyplaces/functional/IOnListModeChangeListener.java | Java | gpl-3.0 | 922 |
import _ from "lodash";
import { Meteor } from "meteor/meteor";
import { Tracker } from "meteor/tracker";
import { AnalyticsEvents, Packages } from "/lib/collections";
import { Reaction, i18next, Logger } from "/client/api";
import Alerts from "/imports/plugins/core/layout/client/templates/layout/alerts/inlineAlerts";
// Create a queue, but don't obliterate an existing one!
analytics = window.analytics = window.analytics || [];
// If the real analytics.js is already on the page return.
if (analytics.initialize) return;
// If the snippet was invoked already show an error.
if (analytics.invoked) {
Logger.warn("Segment snippet included twice.");
return;
}
// Invoked flag, to make sure the snippet
// is never invoked twice.
analytics.invoked = true;
// A list of the methods in Analytics.js to stub.
analytics.methods = [
"trackSubmit",
"trackClick",
"trackLink",
"trackForm",
"pageview",
"identify",
"reset",
"group",
"track",
"ready",
"alias",
"page",
"once",
"off",
"on"
];
// Define a factory to create stubs. These are placeholders
// for methods in Analytics.js so that you never have to wait
// for it to load to actually record data. The `method` is
// stored as the first argument, so we can replay the data.
analytics.factory = function (method) {
return function () {
const args = Array.prototype.slice.call(arguments);
args.unshift(method);
analytics.push(args);
return analytics;
};
};
// For each of our methods, generate a queueing stub.
for (let i = 0; i < analytics.methods.length; i++) {
const key = analytics.methods[i];
analytics[key] = analytics.factory(key);
}
// Define a method to load Analytics.js from our CDN,
// and that will be sure to only ever load it once.
analytics.load = function (key) {
// Create an async script element based on your key.
const script = document.createElement("script");
script.type = "text/javascript";
script.async = true;
script.src = (document.location.protocol === "https:" ? "https://" : "http://") +
"cdn.segment.com/analytics.js/v1/" + key + "/analytics.min.js";
// Insert our script next to the first script element.
const first = document.getElementsByTagName("script")[0];
first.parentNode.insertBefore(script, first);
};
// Add a version to keep track of what"s in the wild.
analytics.SNIPPET_VERSION = "3.1.0";
// Load Analytics.js with your key, which will automatically
// load the tools you"ve enabled for your account. Boosh!
// analytics.load("YOUR_WRITE_KEY");
// Make the first page call to load the integrations. If
// you"d like to manually name or tag the page, edit or
// move this call however you"d like.
// analytics.page();
//
// Initialize analytics page tracking
//
// segment page tracking
function notifySegment(context) {
if (typeof analytics !== "undefined") {
analytics.page({
userId: Meteor.userId(),
properties: {
url: context.path,
shopId: Reaction.getShopId()
}
});
}
}
// google analytics page tracking
function notifyGoogleAnalytics(context) {
if (typeof ga !== "undefined") {
ga("send", "pageview", context.path);
}
}
// mixpanel page tracking
function notifyMixpanel(context) {
if (typeof mixpanel !== "undefined") {
mixpanel.track("page viewed", {
"page name": document.title,
"url": context.path
});
}
}
Reaction.Router.triggers.enter([notifySegment, notifyGoogleAnalytics, notifyMixpanel]);
//
// Initialize analytics event tracking
//
Meteor.startup(function () {
Tracker.autorun(function () {
const coreAnalytics = Packages.findOne({
name: "reaction-analytics"
});
// check if installed and enabled
if (!coreAnalytics || !coreAnalytics.enabled) {
return Alerts.removeType("analytics-not-configured");
}
const googleAnalytics = coreAnalytics.settings.public.googleAnalytics;
const mixpanel = coreAnalytics.settings.public.mixpanel;
const segmentio = coreAnalytics.settings.public.segmentio;
//
// segment.io
//
if (segmentio.enabled) {
if (segmentio.api_key && analytics.invoked === true) {
analytics.load(segmentio.api_key);
} else if (!segmentio.api_key && Reaction.hasAdminAccess()) {
_.defer(function () {
return Alerts.toast(
`${i18next.t("admin.settings.segmentNotConfigured")}`,
"danger", {
html: true,
sticky: true
});
});
}
}
//
// Google Analytics
//
if (googleAnalytics.enabled) {
if (googleAnalytics.api_key) {
ga("create", googleAnalytics.api_key, "auto");
} else if (!googleAnalytics.api_key && Reaction.hasAdminAccess()) {
_.defer(function () {
return Alerts.toast(
`${i18next.t("admin.settings.googleAnalyticsNotConfigured")}`,
"error", {
type: "analytics-not-configured",
html: true,
sticky: true
});
});
}
}
//
// mixpanel
//
if (mixpanel.enabled) {
if (mixpanel.api_key) {
mixpanel.init(mixpanel.api_key);
} else if (!mixpanel.api_key && Reaction.hasAdminAccess()) {
_.defer(function () {
return Alerts.toast(
`${i18next.t("admin.settings.mixpanelNotConfigured")}`,
"error", {
type: "analytics-not-configured",
html: true,
sticky: true
});
});
}
}
if (!Reaction.hasAdminAccess()) {
return Alerts.removeType("analytics-not-configured");
}
return null;
});
//
// analytics event processing
//
return $(document.body).click(function (e) {
let $targets = $(e.target).closest("*[data-event-action]");
$targets = $targets.parents("*[data-event-action]").add($targets);
return $targets.each(function (index, element) {
const $element = $(element);
const analyticsEvent = {
eventType: "event",
category: $element.data("event-category"),
action: $element.data("event-action"),
label: $element.data("event-label"),
value: $element.data("event-value")
};
if (typeof ga === "function") {
ga("send", "event", analyticsEvent.category, analyticsEvent.action, analyticsEvent.label,
analyticsEvent.value);
}
if (typeof mixpanel === "object" && mixpanel.length > 0) {
mixpanel.track(analyticsEvent.action, {
Category: analyticsEvent.category,
Label: analyticsEvent.label,
Value: analyticsEvent.value
});
}
if (typeof analytics === "object") {
analytics.track(analyticsEvent.action, {
Category: analyticsEvent.category,
Label: analyticsEvent.label,
Value: analyticsEvent.value
});
}
// we could add a hook here, but not needed as
// you can trigger using the collection hooks
return AnalyticsEvents.insert(analyticsEvent);
});
});
});
| evereveofficial/reaction | imports/plugins/included/analytics/client/startup.js | JavaScript | gpl-3.0 | 7,072 |
// Generated on 04/17/2013 22:30:01
using System;
using System.Collections.Generic;
using System.Linq;
using BiM.Protocol.Types;
using BiM.Core.IO;
using BiM.Core.Network;
namespace BiM.Protocol.Messages
{
public class InventoryPresetSaveResultMessage : NetworkMessage
{
public const uint Id = 6170;
public override uint MessageId
{
get { return Id; }
}
public sbyte presetId;
public sbyte code;
public InventoryPresetSaveResultMessage()
{
}
public InventoryPresetSaveResultMessage(sbyte presetId, sbyte code)
{
this.presetId = presetId;
this.code = code;
}
public override void Serialize(IDataWriter writer)
{
writer.WriteSByte(presetId);
writer.WriteSByte(code);
}
public override void Deserialize(IDataReader reader)
{
presetId = reader.ReadSByte();
if (presetId < 0)
throw new Exception("Forbidden value on presetId = " + presetId + ", it doesn't respect the following condition : presetId < 0");
code = reader.ReadSByte();
if (code < 0)
throw new Exception("Forbidden value on code = " + code + ", it doesn't respect the following condition : code < 0");
}
}
} | Emudofus/BehaviorIsManaged | Protocol/Messages/game/inventory/preset/InventoryPresetSaveResultMessage.cs | C# | gpl-3.0 | 1,423 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package moodlecore
* @subpackage backup-moodle2
* @copyright 2011 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* restore plugin class that provides the necessary information
* needed to restore one varnumeric qtype plugin
*
* @copyright 2011 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class restore_qtype_varnumeric_plugin extends restore_qtype_plugin {
/**
* Returns the paths to be handled by the plugin at question level
*/
protected function define_question_plugin_structure() {
$paths = array();
// This qtype uses question_answers, add them
$this->add_question_question_answers($paths);
$elements = array('qtype_varnumeric' => '/varnumeric',
'qtype_varnumeric_answer' => '/varnumeric_answers/varnumeric_answer',
'qtype_varnumeric_var' => '/vars/var',
'qtype_varnumeric_variant' => '/vars/var/variants/variant');
foreach ($elements as $elename => $path) {
$elepath = $this->get_pathfor($path);
$paths[] = new restore_path_element($elename, $elepath);
}
return $paths; // And we return the interesting paths
}
/**
* Process the qtype/varnumeric element
*/
public function process_qtype_varnumeric($data) {
global $DB;
$data = (object)$data;
$oldid = $data->id;
// Detect if the question is created or mapped
$oldquestionid = $this->get_old_parentid('question');
$newquestionid = $this->get_new_parentid('question');
$questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
// If the question has been created by restore, we need to create its
// question_varnumeric too
if ($questioncreated) {
// Adjust some columns
$data->questionid = $newquestionid;
// Insert record
$newitemid = $DB->insert_record('qtype_varnumeric', $data);
// Create mapping
$this->set_mapping('qtype_varnumeric', $oldid, $newitemid);
}
}
/**
* Process the qtype/varnumeric_answer element
*/
public function process_qtype_varnumeric_answer($data) {
global $DB;
$data = (object)$data;
$data->answerid = $this->get_mappingid('question_answer', $data->answerid);
// Detect if the question is created
$oldquestionid = $this->get_old_parentid('question');
$questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
if ($questioncreated) {
// Insert record
$newitemid = $DB->insert_record('qtype_varnumeric_answers', $data);
// Create mapping
$this->set_mapping('qtype_varnumeric_answer', $data->id, $newitemid);
}
}
public function process_qtype_varnumeric_var($data) {
global $DB;
$data = (object)$data;
// Detect if the question is created
$oldquestionid = $this->get_old_parentid('question');
$newquestionid = $this->get_new_parentid('question');
$questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
if ($questioncreated) {
$data->questionid = $newquestionid;
// Insert record
$newitemid = $DB->insert_record('qtype_varnumeric_vars', $data);
// Create mapping
$this->set_mapping('qtype_varnumeric_var', $data->id, $newitemid);
}
}
public function process_qtype_varnumeric_variant($data) {
global $DB;
$data = (object)$data;
$data->varid = $this->get_new_parentid('qtype_varnumeric_var');
// Detect if the question is created
$oldquestionid = $this->get_old_parentid('question');
$questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
if ($questioncreated) {
// Insert record
$newitemid = $DB->insert_record('qtype_varnumeric_variants', $data);
// Create mapping
$this->set_mapping('qtype_varnumeric_variant', $data->id, $newitemid);
}
}
}
| marigianna/HierarchyContagMoodle | question/type/varnumeric/backup/moodle2/restore_qtype_varnumeric_plugin.class.php | PHP | gpl-3.0 | 5,105 |
<?php
// This file is part of the Election plugin for Moodle
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package mod_referendum
* @copyright 2015 LTS.ie
* @author Bas Brands
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die(); | wit-ctel/moodle-3-1 | mod/referendum/db/log.php | PHP | gpl-3.0 | 893 |
/*********************************************************************************************
*
* 'IParameter.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and simulation platform.
* (c) 2007-2016 UMI 209 UMMISCO IRD/UPMC & Partners
*
* Visit https://github.com/gama-platform/gama for license information and developers contact.
*
*
**********************************************************************************************/
package msi.gama.kernel.experiment;
import java.util.List;
import java.util.Set;
import msi.gama.runtime.IScope;
import msi.gama.runtime.exceptions.GamaRuntimeException;
import msi.gaml.types.IType;
/**
* Written by drogoul Modified on 4 juin 2010
*
* @todo Description
*
*/
public interface IParameter extends IExperimentDisplayable {
// public abstract Integer getDefinitionOrder();
public abstract void setValue(IScope scope, Object value);
public abstract Object value(IScope scope) throws GamaRuntimeException;
@SuppressWarnings ("rawtypes")
public abstract IType getType();
public String serialize(boolean includingBuiltIn);
public abstract Object getInitialValue(IScope scope);
public abstract Number getMinValue(IScope scope);
public abstract Number getMaxValue(IScope scope);
@SuppressWarnings ("rawtypes")
public abstract List getAmongValue(IScope scope);
public abstract boolean isEditable();
public abstract boolean acceptsSlider(IScope scope);
public abstract Number getStepValue(IScope scope);
public boolean isDefined();
public interface Batch extends IParameter {
public Object value();
public void setCategory(String cat);
public void reinitRandomly(IScope scope);
public abstract Set<Object> neighborValues(IScope scope) throws GamaRuntimeException;
public void setEditable(boolean b);
public boolean canBeExplored();
}
/**
* @param b
*/
public abstract void setDefined(boolean b);
}
| hqnghi88/gamaClone | msi.gama.core/src/msi/gama/kernel/experiment/IParameter.java | Java | gpl-3.0 | 1,942 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.07.23 at 10:09:05 AM PDT
//
package edu.isi.bmkeg.lapdf.pmcXml;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}tr" maxOccurs="unbounded"/>
* </sequence>
* <attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" />
* <attribute name="content-type" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
* <attribute name="style" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
* <attribute name="align">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="left"/>
* <enumeration value="center"/>
* <enumeration value="right"/>
* <enumeration value="justify"/>
* <enumeration value="char"/>
* </restriction>
* </simpleType>
* </attribute>
* <attribute name="char" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
* <attribute name="charoff" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
* <attribute name="valign">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="top"/>
* <enumeration value="middle"/>
* <enumeration value="bottom"/>
* <enumeration value="baseline"/>
* </restriction>
* </simpleType>
* </attribute>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"trs"
})
@XmlRootElement(name = "tbody")
public class PmcXmlTbody {
@XmlElement(name = "tr", required = true)
protected List<PmcXmlTr> trs;
@XmlAttribute(name = "id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected String id;
@XmlAttribute(name = "content-type")
@XmlSchemaType(name = "anySimpleType")
protected String contentType;
@XmlAttribute(name = "style")
@XmlSchemaType(name = "anySimpleType")
protected String style;
@XmlAttribute(name = "align")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String align;
@XmlAttribute(name = "char")
@XmlSchemaType(name = "anySimpleType")
protected String _char;
@XmlAttribute(name = "charoff")
@XmlSchemaType(name = "anySimpleType")
protected String charoff;
@XmlAttribute(name = "valign")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String valign;
/**
* Gets the value of the trs property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the trs property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTrs().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PmcXmlTr }
*
*
*/
public List<PmcXmlTr> getTrs() {
if (trs == null) {
trs = new ArrayList<PmcXmlTr>();
}
return this.trs;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the contentType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContentType() {
return contentType;
}
/**
* Sets the value of the contentType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContentType(String value) {
this.contentType = value;
}
/**
* Gets the value of the style property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStyle() {
return style;
}
/**
* Sets the value of the style property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStyle(String value) {
this.style = value;
}
/**
* Gets the value of the align property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAlign() {
return align;
}
/**
* Sets the value of the align property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAlign(String value) {
this.align = value;
}
/**
* Gets the value of the char property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getChar() {
return _char;
}
/**
* Sets the value of the char property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setChar(String value) {
this._char = value;
}
/**
* Gets the value of the charoff property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCharoff() {
return charoff;
}
/**
* Sets the value of the charoff property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCharoff(String value) {
this.charoff = value;
}
/**
* Gets the value of the valign property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValign() {
return valign;
}
/**
* Sets the value of the valign property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValign(String value) {
this.valign = value;
}
}
| benmccann/lapdftext | src/main/java/edu/isi/bmkeg/lapdf/pmcXml/PmcXmlTbody.java | Java | gpl-3.0 | 7,715 |
/*
*/
package org.schemaanalyst.mutation.equivalence;
import org.schemaanalyst.sqlrepresentation.Column;
import org.schemaanalyst.sqlrepresentation.Schema;
import org.schemaanalyst.sqlrepresentation.Table;
import org.schemaanalyst.sqlrepresentation.constraint.*;
/**
* <p>
* An {@link EquivalenceChecker} that compares two {@link Schema} objects to
* determine if they are equivalent.
* </p>
*
* <p>
* This class delegates much of the equivalence testing to a collection of
* classes that extend the
* {@link org.schemaanalyst.mutation.equivalence.EquivalenceChecker} class, to
* compare each sub-component of a schema for equivalence. Altering this
* behaviour, e.g. for a specific DBMS that has different semantics, can be
* achieved by providing alternative
* {@link org.schemaanalyst.mutation.equivalence.EquivalenceChecker} classes.
* </p>
*
* @author Chris J. Wright
*/
public class SchemaEquivalenceChecker extends EquivalenceChecker<Schema> {
protected EquivalenceChecker<Table> tableEquivalenceChecker;
protected EquivalenceChecker<Column> columnEquivalenceChecker;
protected EquivalenceChecker<PrimaryKeyConstraint> primaryKeyEquivalenceChecker;
protected EquivalenceChecker<ForeignKeyConstraint> foreignKeyEquivalenceChecker;
protected EquivalenceChecker<UniqueConstraint> uniqueEquivalenceChecker;
protected EquivalenceChecker<CheckConstraint> checkEquivalenceChecker;
protected EquivalenceChecker<NotNullConstraint> notNullEquivalenceChecker;
/**
* Constructor with specified equivalence testers for each sub-component of
* a {@link org.schemaanalyst.sqlrepresentation.Schema} object.
*
* @param tableEquivalenceChecker
* @param columnEquivalenceChecker
* @param primaryKeyEquivalenceChecker
* @param foreignKeyEquivalenceChecker
* @param uniqueEquivalenceChecker
* @param checkEquivalenceChecker
* @param notNullEquivalenceChecker
*/
public SchemaEquivalenceChecker(TableEquivalenceChecker tableEquivalenceChecker, ColumnEquivalenceChecker columnEquivalenceChecker, PrimaryKeyEquivalenceChecker primaryKeyEquivalenceChecker, ForeignKeyEquivalenceChecker foreignKeyEquivalenceChecker, UniqueEquivalenceChecker uniqueEquivalenceChecker, CheckEquivalenceChecker checkEquivalenceChecker, NotNullEquivalenceChecker notNullEquivalenceChecker) {
this.tableEquivalenceChecker = tableEquivalenceChecker;
this.columnEquivalenceChecker = columnEquivalenceChecker;
this.primaryKeyEquivalenceChecker = primaryKeyEquivalenceChecker;
this.foreignKeyEquivalenceChecker = foreignKeyEquivalenceChecker;
this.uniqueEquivalenceChecker = uniqueEquivalenceChecker;
this.checkEquivalenceChecker = checkEquivalenceChecker;
this.notNullEquivalenceChecker = notNullEquivalenceChecker;
}
/**
* Constructor that uses a default set of equivalence testers for each
* sub-component of a {@link org.schemaanalyst.sqlrepresentation.Schema}
* object.
*/
public SchemaEquivalenceChecker() {
this.columnEquivalenceChecker = new ColumnEquivalenceChecker();
this.tableEquivalenceChecker = new TableEquivalenceChecker(columnEquivalenceChecker);
this.primaryKeyEquivalenceChecker = new PrimaryKeyEquivalenceChecker();
this.foreignKeyEquivalenceChecker = new ForeignKeyEquivalenceChecker();
this.uniqueEquivalenceChecker = new UniqueEquivalenceChecker();
this.checkEquivalenceChecker = new CheckEquivalenceChecker();
this.notNullEquivalenceChecker = new NotNullEquivalenceChecker();
}
/**
* {@inheritDoc }
*/
@Override
public boolean areEquivalent(Schema a, Schema b) {
if (super.areEquivalent(a, b)) {
return true;
} else if (!a.getIdentifier().equals(b.getIdentifier())) {
return false;
} else if (a.getTables().size() != b.getTables().size()) {
return false;
} else if (!tableEquivalenceChecker.areEquivalent(a.getTablesInOrder(), b.getTablesInOrder())) {
return false;
} else if (!primaryKeyEquivalenceChecker.areEquivalent(a.getPrimaryKeyConstraints(), b.getPrimaryKeyConstraints())) {
return false;
} else if (!foreignKeyEquivalenceChecker.areEquivalent(a.getForeignKeyConstraints(), b.getForeignKeyConstraints())) {
return false;
} else if (!uniqueEquivalenceChecker.areEquivalent(a.getUniqueConstraints(), b.getUniqueConstraints())) {
return false;
} else if (!checkEquivalenceChecker.areEquivalent(a.getCheckConstraints(), b.getCheckConstraints())) {
return false;
} else return notNullEquivalenceChecker.areEquivalent(a.getNotNullConstraints(), b.getNotNullConstraints());
}
}
| schemaanalyst-team/schemaanalyst | src/main/java/org/schemaanalyst/mutation/equivalence/SchemaEquivalenceChecker.java | Java | gpl-3.0 | 4,819 |
var searchData=
[
['k',['k',['../a00008.html#ad4adeba1dac18ef43f26892b9878c3c3',1,'gaml::xtree::classification::Learner::k()'],['../a00020.html#a0d4642365c5cb8a02327248e79f6314e',1,'gaml::xtree::regression::Learner::k()']]]
];
| HerveFrezza-Buet/gaml | doc/gaml-xtree/html/search/variables_1.js | JavaScript | gpl-3.0 | 229 |