code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MEDIA_VIDEO_H264_POC_H_
#define MEDIA_VIDEO_H264_POC_H_
#include <stdint.h>
#include "base/macros.h"
namespace media {
struct H264SPS;
struct H264SliceHeader;
class MEDIA_EXPORT H264POC {
public:
H264POC();
~H264POC();
// Returns the picture order count for a slice.
base::Optional<int32_t> ComputePicOrderCnt(const H264SPS* sps,
const H264SliceHeader& slice_hdr);
// As specified, the POC of a frame with MMCO5 changes (to zero) after
// decoding. We instead return 0 immediately, and flag that this has occurred
// by returning true here until ComputePicOrderCnt() is called again.
//
// Frames with MMCO5 do not reorder relative to frames earlier in decode
// order, but may reorder relative to frames later in decode order (just like
// IDRs).
bool IsPendingMMCO5() { return pending_mmco5_; }
// Reset computation state. It's best (although not strictly required) to call
// this after a seek.
void Reset();
private:
int32_t ref_pic_order_cnt_msb_;
int32_t ref_pic_order_cnt_lsb_;
int32_t prev_frame_num_;
int32_t prev_frame_num_offset_;
bool pending_mmco5_;
DISALLOW_COPY_AND_ASSIGN(H264POC);
};
} // namespace media
#endif // MEDIA_VIDEO_H264_POC_H_
|
endlessm/chromium-browser
|
media/video/h264_poc.h
|
C
|
bsd-3-clause
| 1,433
|
// $Id$
//
// Copyright (C) 2003-2014 Greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#define NO_IMPORT_ARRAY
#include "rdmolops.h"
#include <RDBoost/python.h>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>
#include <string>
#include <math.h>
#include <DataStructs/ExplicitBitVect.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/RDKitQueries.h>
#include <GraphMol/MonomerInfo.h>
#include <GraphMol/Substruct/SubstructMatch.h>
#include <GraphMol/Subgraphs/Subgraphs.h>
#include <GraphMol/Subgraphs/SubgraphUtils.h>
#include <GraphMol/Fingerprints/Fingerprints.h>
#include <GraphMol/FileParsers/MolFileStereochem.h>
#include <GraphMol/ChemTransforms/ChemTransforms.h>
#include <RDBoost/Wrap.h>
#include <RDBoost/python_streambuf.h>
#include <sstream>
#include <GraphMol/MolDraw2D/MolDraw2DSVG.h>
namespace python = boost::python;
using boost_adaptbx::python::streambuf;
namespace RDKit {
std::string molToSVG(const ROMol &mol, unsigned int width, unsigned int height,
python::object pyHighlightAtoms, bool kekulize,
unsigned int lineWidthMult, unsigned int fontSize,
bool includeAtomCircles, int confId) {
RDUNUSED_PARAM(kekulize);
rdk_auto_ptr<std::vector<int> > highlightAtoms =
pythonObjectToVect(pyHighlightAtoms, static_cast<int>(mol.getNumAtoms()));
std::stringstream outs;
MolDraw2DSVG drawer(width, height, outs);
drawer.setFontSize(fontSize / 24.);
drawer.setLineWidth(drawer.lineWidth() * lineWidthMult);
drawer.drawOptions().circleAtoms = includeAtomCircles;
drawer.drawMolecule(mol, highlightAtoms.get(), NULL, NULL, confId);
drawer.finishDrawing();
return outs.str();
}
python::tuple fragmentOnSomeBondsHelper(const ROMol &mol,
python::object pyBondIndices,
unsigned int nToBreak, bool addDummies,
python::object pyDummyLabels,
python::object pyBondTypes,
bool returnCutsPerAtom) {
rdk_auto_ptr<std::vector<unsigned int> > bondIndices =
pythonObjectToVect(pyBondIndices, mol.getNumBonds());
if (!bondIndices.get()) throw_value_error("empty bond indices");
std::vector<std::pair<unsigned int, unsigned int> > *dummyLabels = 0;
if (pyDummyLabels) {
unsigned int nVs =
python::extract<unsigned int>(pyDummyLabels.attr("__len__")());
dummyLabels = new std::vector<std::pair<unsigned int, unsigned int> >(nVs);
for (unsigned int i = 0; i < nVs; ++i) {
unsigned int v1 = python::extract<unsigned int>(pyDummyLabels[i][0]);
unsigned int v2 = python::extract<unsigned int>(pyDummyLabels[i][1]);
(*dummyLabels)[i] = std::make_pair(v1, v2);
}
}
std::vector<Bond::BondType> *bondTypes = 0;
if (pyBondTypes) {
unsigned int nVs =
python::extract<unsigned int>(pyBondTypes.attr("__len__")());
if (nVs != bondIndices->size()) {
throw_value_error("bondTypes shorter than bondIndices");
}
bondTypes = new std::vector<Bond::BondType>(nVs);
for (unsigned int i = 0; i < nVs; ++i) {
(*bondTypes)[i] = python::extract<Bond::BondType>(pyBondTypes[i]);
}
}
std::vector<std::vector<unsigned int> > *cutsPerAtom = 0;
if (returnCutsPerAtom) {
cutsPerAtom = new std::vector<std::vector<unsigned int> >;
}
std::vector<ROMOL_SPTR> frags;
MolFragmenter::fragmentOnSomeBonds(mol, *bondIndices, frags, nToBreak,
addDummies, dummyLabels, bondTypes,
cutsPerAtom);
python::list res;
for (unsigned int i = 0; i < frags.size(); ++i) {
res.append(frags[i]);
}
delete dummyLabels;
delete bondTypes;
if (cutsPerAtom) {
python::list pyCutsPerAtom;
for (unsigned int i = 0; i < cutsPerAtom->size(); ++i) {
python::list localL;
for (unsigned int j = 0; j < mol.getNumAtoms(); ++j) {
localL.append((*cutsPerAtom)[i][j]);
}
pyCutsPerAtom.append(python::tuple(localL));
}
delete cutsPerAtom;
python::list tres;
tres.append(python::tuple(res));
tres.append(python::tuple(pyCutsPerAtom));
return python::tuple(tres);
} else {
return python::tuple(res);
}
}
python::tuple getShortestPathHelper(const ROMol &mol, int aid1, int aid2) {
if (aid1 < 0 || aid1 >= rdcast<int>(mol.getNumAtoms()) || aid2 < 0 ||
aid2 >= rdcast<int>(mol.getNumAtoms())) {
throw_value_error("bad atom index");
}
return static_cast<python::tuple>(MolOps::getShortestPath(mol, aid1, aid2));
}
ROMol *fragmentOnBondsHelper(const ROMol &mol, python::object pyBondIndices,
bool addDummies, python::object pyDummyLabels,
python::object pyBondTypes,
python::list pyCutsPerAtom) {
rdk_auto_ptr<std::vector<unsigned int> > bondIndices =
pythonObjectToVect(pyBondIndices, mol.getNumBonds());
if (!bondIndices.get()) throw_value_error("empty bond indices");
std::vector<std::pair<unsigned int, unsigned int> > *dummyLabels = 0;
if (pyDummyLabels) {
unsigned int nVs =
python::extract<unsigned int>(pyDummyLabels.attr("__len__")());
dummyLabels = new std::vector<std::pair<unsigned int, unsigned int> >(nVs);
for (unsigned int i = 0; i < nVs; ++i) {
unsigned int v1 = python::extract<unsigned int>(pyDummyLabels[i][0]);
unsigned int v2 = python::extract<unsigned int>(pyDummyLabels[i][1]);
(*dummyLabels)[i] = std::make_pair(v1, v2);
}
}
std::vector<Bond::BondType> *bondTypes = 0;
if (pyBondTypes) {
unsigned int nVs =
python::extract<unsigned int>(pyBondTypes.attr("__len__")());
if (nVs != bondIndices->size()) {
throw_value_error("bondTypes shorter than bondIndices");
}
bondTypes = new std::vector<Bond::BondType>(nVs);
for (unsigned int i = 0; i < nVs; ++i) {
(*bondTypes)[i] = python::extract<Bond::BondType>(pyBondTypes[i]);
}
}
std::vector<unsigned int> *cutsPerAtom = 0;
if (pyCutsPerAtom) {
cutsPerAtom = new std::vector<unsigned int>;
unsigned int nAts =
python::extract<unsigned int>(pyCutsPerAtom.attr("__len__")());
if (nAts < mol.getNumAtoms()) {
throw_value_error("cutsPerAtom shorter than the number of atoms");
}
cutsPerAtom->resize(nAts);
}
ROMol *res = MolFragmenter::fragmentOnBonds(
mol, *bondIndices, addDummies, dummyLabels, bondTypes, cutsPerAtom);
if (cutsPerAtom) {
for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) {
pyCutsPerAtom[i] = (*cutsPerAtom)[i];
}
delete cutsPerAtom;
}
delete dummyLabels;
delete bondTypes;
return res;
}
ROMol *renumberAtomsHelper(const ROMol &mol, python::object &pyNewOrder) {
if (python::extract<unsigned int>(pyNewOrder.attr("__len__")()) <
mol.getNumAtoms()) {
throw_value_error("atomCounts shorter than the number of atoms");
}
rdk_auto_ptr<std::vector<unsigned int> > newOrder =
pythonObjectToVect(pyNewOrder, mol.getNumAtoms());
ROMol *res = MolOps::renumberAtoms(mol, *newOrder);
return res;
}
namespace {
std::string getResidue(const ROMol &m, const Atom *at) {
RDUNUSED_PARAM(m);
if (at->getMonomerInfo()->getMonomerType() != AtomMonomerInfo::PDBRESIDUE)
return "";
return static_cast<const AtomPDBResidueInfo *>(at->getMonomerInfo())
->getResidueName();
}
std::string getChainId(const ROMol &m, const Atom *at) {
RDUNUSED_PARAM(m);
if (at->getMonomerInfo()->getMonomerType() != AtomMonomerInfo::PDBRESIDUE)
return "";
return static_cast<const AtomPDBResidueInfo *>(at->getMonomerInfo())
->getChainId();
}
}
python::dict splitMolByPDBResidues(const ROMol &mol, python::object pyWhiteList,
bool negateList) {
std::vector<std::string> *whiteList = NULL;
if (pyWhiteList) {
unsigned int nVs =
python::extract<unsigned int>(pyWhiteList.attr("__len__")());
whiteList = new std::vector<std::string>(nVs);
for (unsigned int i = 0; i < nVs; ++i) {
(*whiteList)[i] = python::extract<std::string>(pyWhiteList[i]);
}
}
std::map<std::string, boost::shared_ptr<ROMol> > res =
MolOps::getMolFragsWithQuery(mol, getResidue, false, whiteList,
negateList);
delete whiteList;
python::dict pyres;
for (std::map<std::string, boost::shared_ptr<ROMol> >::const_iterator iter =
res.begin();
iter != res.end(); ++iter) {
pyres[iter->first] = iter->second;
}
return pyres;
}
python::dict splitMolByPDBChainId(const ROMol &mol, python::object pyWhiteList,
bool negateList) {
std::vector<std::string> *whiteList = NULL;
if (pyWhiteList) {
unsigned int nVs =
python::extract<unsigned int>(pyWhiteList.attr("__len__")());
whiteList = new std::vector<std::string>(nVs);
for (unsigned int i = 0; i < nVs; ++i) {
(*whiteList)[i] = python::extract<std::string>(pyWhiteList[i]);
}
}
std::map<std::string, boost::shared_ptr<ROMol> > res =
MolOps::getMolFragsWithQuery(mol, getChainId, false, whiteList,
negateList);
delete whiteList;
python::dict pyres;
for (std::map<std::string, boost::shared_ptr<ROMol> >::const_iterator iter =
res.begin();
iter != res.end(); ++iter) {
pyres[iter->first] = iter->second;
}
return pyres;
}
python::dict parseQueryDefFileHelper(python::object &input, bool standardize,
std::string delimiter, std::string comment,
unsigned int nameColumn,
unsigned int smartsColumn) {
python::extract<std::string> get_filename(input);
std::map<std::string, ROMOL_SPTR> queryDefs;
if (get_filename.check()) {
parseQueryDefFile(get_filename(), queryDefs, standardize, delimiter,
comment, nameColumn, smartsColumn);
} else {
streambuf *sb = new streambuf(input);
std::istream *istr = new streambuf::istream(*sb);
parseQueryDefFile(istr, queryDefs, standardize, delimiter, comment,
nameColumn, smartsColumn);
delete istr;
delete sb;
}
python::dict res;
for (std::map<std::string, ROMOL_SPTR>::const_iterator iter =
queryDefs.begin();
iter != queryDefs.end(); ++iter) {
res[iter->first] = iter->second;
}
return res;
}
void addRecursiveQueriesHelper(ROMol &mol, python::dict replDict,
std::string propName) {
std::map<std::string, ROMOL_SPTR> replacements;
for (unsigned int i = 0;
i < python::extract<unsigned int>(replDict.keys().attr("__len__")());
++i) {
ROMol *m = python::extract<ROMol *>(replDict.values()[i]);
ROMOL_SPTR nm(new ROMol(*m));
std::string k = python::extract<std::string>(replDict.keys()[i]);
replacements[k] = nm;
}
addRecursiveQueries(mol, replacements, propName);
}
ROMol *addHs(const ROMol &orig, bool explicitOnly, bool addCoords,
python::object onlyOnAtoms) {
rdk_auto_ptr<std::vector<unsigned int> > onlyOn;
if (onlyOnAtoms) {
onlyOn = pythonObjectToVect(onlyOnAtoms, orig.getNumAtoms());
}
ROMol *res = MolOps::addHs(orig, explicitOnly, addCoords, onlyOn.get());
return res;
}
int getSSSR(ROMol &mol) {
VECT_INT_VECT rings;
int nr = MolOps::findSSSR(mol, rings);
return nr;
}
PyObject *replaceSubstructures(const ROMol &orig, const ROMol &query,
const ROMol &replacement,
bool replaceAll = false,
unsigned int replacementConnectionPoint = 0,
bool useChirality=false) {
std::vector<ROMOL_SPTR> v = replaceSubstructs(
orig, query, replacement, replaceAll, replacementConnectionPoint,
useChirality);
PyObject *res = PyTuple_New(v.size());
for (unsigned int i = 0; i < v.size(); ++i) {
PyTuple_SetItem(res, i, python::converter::shared_ptr_to_python(v[i]));
}
return res;
}
void addRecursiveQuery(ROMol &mol, const ROMol &query, unsigned int atomIdx,
bool preserveExistingQuery) {
if (atomIdx >= mol.getNumAtoms()) {
throw_value_error("atom index exceeds mol.GetNumAtoms()");
}
RecursiveStructureQuery *q = new RecursiveStructureQuery(new ROMol(query));
Atom *oAt = mol.getAtomWithIdx(atomIdx);
if (!oAt->hasQuery()) {
QueryAtom qAt(*oAt);
static_cast<RWMol &>(mol).replaceAtom(atomIdx, &qAt);
oAt = mol.getAtomWithIdx(atomIdx);
}
if (!preserveExistingQuery) {
delete oAt->getQuery();
oAt->setQuery(q);
} else {
oAt->expandQuery(q, Queries::COMPOSITE_AND);
}
}
#ifdef RDK_32BIT_BUILD
MolOps::SanitizeFlags sanitizeMol(ROMol &mol, int sanitizeOps,
bool catchErrors) {
#else
MolOps::SanitizeFlags sanitizeMol(ROMol &mol, unsigned int sanitizeOps,
bool catchErrors) {
#endif
RWMol &wmol = static_cast<RWMol &>(mol);
unsigned int operationThatFailed;
if (catchErrors) {
try {
MolOps::sanitizeMol(wmol, operationThatFailed, sanitizeOps);
} catch (...) {
}
} else {
MolOps::sanitizeMol(wmol, operationThatFailed, sanitizeOps);
}
return static_cast<MolOps::SanitizeFlags>(operationThatFailed);
}
RWMol *getEditable(const ROMol &mol) {
RWMol *res = static_cast<RWMol *>(new ROMol(mol, false));
return res;
}
ROMol *getNormal(const RWMol &mol) {
ROMol *res = static_cast<ROMol *>(new RWMol(mol));
return res;
}
void kekulizeMol(ROMol &mol, bool clearAromaticFlags = false) {
RWMol &wmol = static_cast<RWMol &>(mol);
MolOps::Kekulize(wmol, clearAromaticFlags);
}
void cleanupMol(ROMol &mol) {
RWMol &rwmol = static_cast<RWMol &>(mol);
MolOps::cleanUp(rwmol);
}
void setAromaticityMol(ROMol &mol, MolOps::AromaticityModel model) {
RWMol &wmol = static_cast<RWMol &>(mol);
MolOps::setAromaticity(wmol, model);
}
void setConjugationMol(ROMol &mol) {
RWMol &wmol = static_cast<RWMol &>(mol);
MolOps::setConjugation(wmol);
}
void assignRadicalsMol(ROMol &mol) {
RWMol &wmol = static_cast<RWMol &>(mol);
MolOps::assignRadicals(wmol);
}
void setHybridizationMol(ROMol &mol) {
RWMol &wmol = static_cast<RWMol &>(mol);
MolOps::setHybridization(wmol);
}
VECT_INT_VECT getSymmSSSR(ROMol &mol) {
VECT_INT_VECT rings;
MolOps::symmetrizeSSSR(mol, rings);
return rings;
}
PyObject *getDistanceMatrix(ROMol &mol, bool useBO = false,
bool useAtomWts = false, bool force = false,
const char *prefix = 0) {
int nats = mol.getNumAtoms();
npy_intp dims[2];
dims[0] = nats;
dims[1] = nats;
double *distMat;
distMat = MolOps::getDistanceMat(mol, useBO, useAtomWts, force, prefix);
PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE);
memcpy(PyArray_DATA(res), static_cast<void *>(distMat),
nats * nats * sizeof(double));
return PyArray_Return(res);
}
PyObject *get3DDistanceMatrix(ROMol &mol, int confId = -1,
bool useAtomWts = false, bool force = false,
const char *prefix = 0) {
int nats = mol.getNumAtoms();
npy_intp dims[2];
dims[0] = nats;
dims[1] = nats;
double *distMat;
distMat = MolOps::get3DDistanceMat(mol, confId, useAtomWts, force, prefix);
PyArrayObject *res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE);
memcpy(PyArray_DATA(res), static_cast<void *>(distMat),
nats * nats * sizeof(double));
return PyArray_Return(res);
}
PyObject *getAdjacencyMatrix(ROMol &mol, bool useBO = false, int emptyVal = 0,
bool force = false, const char *prefix = 0) {
int nats = mol.getNumAtoms();
npy_intp dims[2];
dims[0] = nats;
dims[1] = nats;
double *tmpMat =
MolOps::getAdjacencyMatrix(mol, useBO, emptyVal, force, prefix);
PyArrayObject *res;
if (useBO) {
// if we're using valence, the results matrix is made up of doubles
res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_DOUBLE);
memcpy(PyArray_DATA(res), static_cast<void *>(tmpMat),
nats * nats * sizeof(double));
} else {
res = (PyArrayObject *)PyArray_SimpleNew(2, dims, NPY_INT);
int *data = static_cast<int *>(PyArray_DATA(res));
for (int i = 0; i < nats; i++) {
for (int j = 0; j < nats; j++) {
data[i * nats + j] = (int)round(tmpMat[i * nats + j]);
}
}
}
return PyArray_Return(res);
}
python::tuple GetMolFrags(const ROMol &mol, bool asMols, bool sanitizeFrags) {
python::list res;
if (!asMols) {
VECT_INT_VECT frags;
MolOps::getMolFrags(mol, frags);
for (unsigned int i = 0; i < frags.size(); ++i) {
python::list tpl;
for (unsigned int j = 0; j < frags[i].size(); ++j) {
tpl.append(frags[i][j]);
}
res.append(python::tuple(tpl));
}
} else {
std::vector<boost::shared_ptr<ROMol> > frags;
frags = MolOps::getMolFrags(mol, sanitizeFrags);
for (unsigned int i = 0; i < frags.size(); ++i) {
res.append(frags[i]);
}
}
return python::tuple(res);
}
ExplicitBitVect *wrapLayeredFingerprint(
const ROMol &mol, unsigned int layerFlags, unsigned int minPath,
unsigned int maxPath, unsigned int fpSize, python::list atomCounts,
ExplicitBitVect *includeOnlyBits, bool branchedPaths,
python::object fromAtoms) {
rdk_auto_ptr<std::vector<unsigned int> > lFromAtoms =
pythonObjectToVect(fromAtoms, mol.getNumAtoms());
std::vector<unsigned int> *atomCountsV = 0;
if (atomCounts) {
atomCountsV = new std::vector<unsigned int>;
unsigned int nAts =
python::extract<unsigned int>(atomCounts.attr("__len__")());
if (nAts < mol.getNumAtoms()) {
throw_value_error("atomCounts shorter than the number of atoms");
}
atomCountsV->resize(nAts);
for (unsigned int i = 0; i < nAts; ++i) {
(*atomCountsV)[i] = python::extract<unsigned int>(atomCounts[i]);
}
}
ExplicitBitVect *res;
res = RDKit::LayeredFingerprintMol(mol, layerFlags, minPath, maxPath, fpSize,
atomCountsV, includeOnlyBits,
branchedPaths, lFromAtoms.get());
if (atomCountsV) {
for (unsigned int i = 0; i < atomCountsV->size(); ++i) {
atomCounts[i] = (*atomCountsV)[i];
}
delete atomCountsV;
}
return res;
}
ExplicitBitVect *wrapPatternFingerprint(const ROMol &mol, unsigned int fpSize,
python::list atomCounts,
ExplicitBitVect *includeOnlyBits) {
std::vector<unsigned int> *atomCountsV = 0;
if (atomCounts) {
atomCountsV = new std::vector<unsigned int>;
unsigned int nAts =
python::extract<unsigned int>(atomCounts.attr("__len__")());
if (nAts < mol.getNumAtoms()) {
throw_value_error("atomCounts shorter than the number of atoms");
}
atomCountsV->resize(nAts);
for (unsigned int i = 0; i < nAts; ++i) {
(*atomCountsV)[i] = python::extract<unsigned int>(atomCounts[i]);
}
}
ExplicitBitVect *res;
res = RDKit::PatternFingerprintMol(mol, fpSize, atomCountsV, includeOnlyBits);
if (atomCountsV) {
for (unsigned int i = 0; i < atomCountsV->size(); ++i) {
atomCounts[i] = (*atomCountsV)[i];
}
delete atomCountsV;
}
return res;
}
ExplicitBitVect *wrapRDKFingerprintMol(
const ROMol &mol, unsigned int minPath, unsigned int maxPath,
unsigned int fpSize, unsigned int nBitsPerHash, bool useHs,
double tgtDensity, unsigned int minSize, bool branchedPaths,
bool useBondOrder, python::object atomInvariants, python::object fromAtoms,
python::object atomBits, python::object bitInfo) {
rdk_auto_ptr<std::vector<unsigned int> > lAtomInvariants =
pythonObjectToVect<unsigned int>(atomInvariants);
rdk_auto_ptr<std::vector<unsigned int> > lFromAtoms =
pythonObjectToVect(fromAtoms, mol.getNumAtoms());
std::vector<std::vector<boost::uint32_t> > *lAtomBits = 0;
std::map<boost::uint32_t, std::vector<std::vector<int> > > *lBitInfo = 0;
// if(!(atomBits.is_none())){
if (atomBits != python::object()) {
lAtomBits =
new std::vector<std::vector<boost::uint32_t> >(mol.getNumAtoms());
}
if (bitInfo != python::object()) {
lBitInfo = new std::map<boost::uint32_t, std::vector<std::vector<int> > >;
}
ExplicitBitVect *res;
res = RDKit::RDKFingerprintMol(mol, minPath, maxPath, fpSize, nBitsPerHash,
useHs, tgtDensity, minSize, branchedPaths,
useBondOrder, lAtomInvariants.get(),
lFromAtoms.get(), lAtomBits, lBitInfo);
if (lAtomBits) {
python::list &pyl = static_cast<python::list &>(atomBits);
for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) {
python::list tmp;
BOOST_FOREACH (boost::uint32_t v, (*lAtomBits)[i]) { tmp.append(v); }
pyl.append(tmp);
}
delete lAtomBits;
}
if (lBitInfo) {
python::dict &pyd = static_cast<python::dict &>(bitInfo);
typedef std::map<boost::uint32_t, std::vector<std::vector<int> > >::iterator
it_type;
for (it_type it = (*lBitInfo).begin(); it != (*lBitInfo).end(); ++it) {
python::list temp;
std::vector<std::vector<int> >::iterator itset;
for (itset = it->second.begin(); itset != it->second.end(); ++itset) {
python::list temp2;
for (unsigned int i = 0; i < itset->size(); ++i) {
temp2.append(itset->at(i));
}
temp.append(temp2);
}
if (!pyd.has_key(it->first)) {
pyd[it->first] = temp;
}
}
delete lBitInfo;
}
return res;
}
SparseIntVect<boost::uint64_t> *wrapUnfoldedRDKFingerprintMol(
const ROMol &mol, unsigned int minPath, unsigned int maxPath, bool useHs,
bool branchedPaths, bool useBondOrder, python::object atomInvariants,
python::object fromAtoms, python::object atomBits, python::object bitInfo) {
rdk_auto_ptr<std::vector<unsigned int> > lAtomInvariants =
pythonObjectToVect<unsigned int>(atomInvariants);
rdk_auto_ptr<std::vector<unsigned int> > lFromAtoms =
pythonObjectToVect(fromAtoms, mol.getNumAtoms());
std::vector<std::vector<boost::uint64_t> > *lAtomBits = 0;
std::map<boost::uint64_t, std::vector<std::vector<int> > > *lBitInfo = 0;
// if(!(atomBits.is_none())){
if (atomBits != python::object()) {
lAtomBits =
new std::vector<std::vector<boost::uint64_t> >(mol.getNumAtoms());
}
if (bitInfo != python::object()) {
lBitInfo = new std::map<boost::uint64_t, std::vector<std::vector<int> > >;
}
SparseIntVect<boost::uint64_t> *res;
res = getUnfoldedRDKFingerprintMol(
mol, minPath, maxPath, useHs, branchedPaths, useBondOrder,
lAtomInvariants.get(), lFromAtoms.get(), lAtomBits, lBitInfo);
if (lAtomBits) {
python::list &pyl = static_cast<python::list &>(atomBits);
for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) {
python::list tmp;
BOOST_FOREACH (boost::uint64_t v, (*lAtomBits)[i]) { tmp.append(v); }
pyl.append(tmp);
}
delete lAtomBits;
}
if (lBitInfo) {
python::dict &pyd = static_cast<python::dict &>(bitInfo);
typedef std::map<boost::uint64_t, std::vector<std::vector<int> > >::iterator
it_type;
for (it_type it = (*lBitInfo).begin(); it != (*lBitInfo).end(); ++it) {
python::list temp;
std::vector<std::vector<int> >::iterator itset;
for (itset = it->second.begin(); itset != it->second.end(); ++itset) {
python::list temp2;
for (unsigned int i = 0; i < itset->size(); ++i) {
temp2.append(itset->at(i));
}
temp.append(temp2);
}
if (!pyd.has_key(it->first)) {
pyd[it->first] = temp;
}
}
delete lBitInfo;
}
return res;
}
python::object findAllSubgraphsOfLengthsMtoNHelper(const ROMol &mol,
unsigned int lowerLen,
unsigned int upperLen,
bool useHs = false,
int rootedAtAtom = -1) {
if (lowerLen > upperLen) {
throw_value_error("lowerLen > upperLen");
}
INT_PATH_LIST_MAP oMap = findAllSubgraphsOfLengthsMtoN(
mol, lowerLen, upperLen, useHs, rootedAtAtom);
python::list res;
for (unsigned int i = lowerLen; i <= upperLen; ++i) {
python::list tmp;
const PATH_LIST &pth = oMap[i];
for (PATH_LIST_CI pthit = pth.begin(); pthit != pth.end(); ++pthit) {
tmp.append(python::tuple(*pthit));
}
res.append(tmp);
}
return python::tuple(res);
};
ROMol *pathToSubmolHelper(const ROMol &mol, python::object &path, bool useQuery,
python::object atomMap) {
ROMol *result;
PATH_TYPE pth;
for (unsigned int i = 0;
i < python::extract<unsigned int>(path.attr("__len__")()); ++i) {
pth.push_back(python::extract<unsigned int>(path[i]));
}
std::map<int, int> mapping;
result = Subgraphs::pathToSubmol(mol, pth, useQuery, mapping);
if (atomMap != python::object()) {
// make sure the optional argument actually was a dictionary
python::dict typecheck = python::extract<python::dict>(atomMap);
atomMap.attr("clear")();
for (std::map<int, int>::const_iterator mIt = mapping.begin();
mIt != mapping.end(); ++mIt) {
atomMap[mIt->first] = mIt->second;
}
}
return result;
}
ROMol *adjustQueryPropertiesHelper(const ROMol &mol, python::object pyparams) {
MolOps::AdjustQueryParameters params;
if (pyparams != python::object()) {
params = python::extract<MolOps::AdjustQueryParameters>(pyparams);
}
return MolOps::adjustQueryProperties(mol, ¶ms);
}
ROMol *replaceCoreHelper(const ROMol &mol,
const ROMol &core,
python::object match,
bool replaceDummies,
bool labelByIndex,
bool requireDummyMatch=false) {
// convert input to MatchVect
MatchVectType matchVect;
unsigned int length = python::extract<unsigned int>(match.attr("__len__")());
for (unsigned int i = 0; i < length; ++i) {
int sz = 1;
if(PyObject_HasAttrString(static_cast<python::object>(match[i]).ptr(), "__len__")) {
sz = python::extract<unsigned int>(match[i].attr("__len__")());
}
int v1,v2;
if (sz != 1 && sz != 2)
throw ValueErrorException("Input not a vector of (core_atom_idx,molecule_atom_idx) or (molecule_atom_idx,...) entries" );
if (sz == 1) {
if(length != core.getNumAtoms()) {
std::string entries = core.getNumAtoms() == 1 ? " entry" : " entries";
std::stringstream ss;
ss << std::string("When using input vector of type (molecule_atom_idx,...) supplied core requires ")
<< core.getNumAtoms() << entries;
throw ValueErrorException(ss.str());
}
v1 = (int)i;
v2 = python::extract<int>(match[i]);
} else if (sz == 2) {
v1 = python::extract<int>(match[i][0]);
v2 = python::extract<int>(match[i][1]);
}
matchVect.push_back(std::make_pair(v1,v2));
}
return replaceCore(mol, core, matchVect, replaceDummies, labelByIndex, requireDummyMatch);
}
struct molops_wrapper {
static void wrap() {
std::string docString;
python::enum_<MolOps::SanitizeFlags>("SanitizeFlags")
.value("SANITIZE_NONE", MolOps::SANITIZE_NONE)
.value("SANITIZE_CLEANUP", MolOps::SANITIZE_CLEANUP)
.value("SANITIZE_PROPERTIES", MolOps::SANITIZE_PROPERTIES)
.value("SANITIZE_SYMMRINGS", MolOps::SANITIZE_SYMMRINGS)
.value("SANITIZE_KEKULIZE", MolOps::SANITIZE_KEKULIZE)
.value("SANITIZE_FINDRADICALS", MolOps::SANITIZE_FINDRADICALS)
.value("SANITIZE_SETAROMATICITY", MolOps::SANITIZE_SETAROMATICITY)
.value("SANITIZE_SETCONJUGATION", MolOps::SANITIZE_SETCONJUGATION)
.value("SANITIZE_SETHYBRIDIZATION", MolOps::SANITIZE_SETHYBRIDIZATION)
.value("SANITIZE_CLEANUPCHIRALITY", MolOps::SANITIZE_CLEANUPCHIRALITY)
.value("SANITIZE_ADJUSTHS", MolOps::SANITIZE_ADJUSTHS)
.value("SANITIZE_ALL", MolOps::SANITIZE_ALL)
.export_values();
;
// ------------------------------------------------------------------------
docString =
"Kekulize, check valencies, set aromaticity, conjugation and hybridization\n\
\n\
- The molecule is modified in place.\n\
\n\
- If sanitization fails, an exception will be thrown unless catchErrors is set\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to be modified\n\
- sanitizeOps: (optional) sanitization operations to be carried out\n\
these should be constructed by or'ing together the\n\
operations in rdkit.Chem.SanitizeFlags\n\
- catchErrors: (optional) if provided, instead of raising an exception\n\
when sanitization fails (the default behavior), the \n\
first operation that failed (as defined in rdkit.Chem.SanitizeFlags)\n\
is returned. Zero is returned on success.\n\
\n";
python::def(
"SanitizeMol", sanitizeMol,
(python::arg("mol"), python::arg("sanitizeOps") = MolOps::SANITIZE_ALL,
python::arg("catchErrors") = false),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Get the smallest set of simple rings for a molecule.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use.\n\
\n\
RETURNS: a sequence of sequences containing the rings found as atom ids\n\
The length of this will be equal to NumBonds-NumAtoms+1 for single-fragment molecules.\n\
\n";
python::def("GetSSSR", getSSSR, docString.c_str());
// ------------------------------------------------------------------------
docString =
"Get a symmetrized SSSR for a molecule.\n\
\n\
The symmetrized SSSR is at least as large as the SSSR for a molecule.\n\
In certain highly-symmetric cases (e.g. cubane), the symmetrized SSSR can be\n\
a bit larger (i.e. the number of symmetrized rings is >= NumBonds-NumAtoms+1).\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use.\n\
\n\
RETURNS: a sequence of sequences containing the rings found as atom ids\n\
\n";
python::def("GetSymmSSSR", getSymmSSSR, docString.c_str());
// ------------------------------------------------------------------------
docString =
"Does a non-SSSR ring finding for a molecule.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use.\n\
\n\
RETURNS: Nothing\n\
\n";
python::def("FastFindRings", MolOps::fastFindRings, docString.c_str());
// ------------------------------------------------------------------------
docString =
"Adds hydrogens to the graph of a molecule.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to be modified\n\
\n\
- explicitOnly: (optional) if this toggle is set, only explicit Hs will\n\
be added to the molecule. Default value is 0 (add implicit and explicit Hs).\n\
\n\
- addCoords: (optional) if this toggle is set, The Hs will have 3D coordinates\n\
set. Default value is 0 (no 3D coords).\n\
\n\
- onlyOnHs: (optional) if this sequence is provided, only these atoms will be\n\
considered to have Hs added to them\n\
\n\
RETURNS: a new molecule with added Hs\n\
\n\
NOTES:\n\
\n\
- The original molecule is *not* modified.\n\
\n\
- Much of the code assumes that Hs are not included in the molecular\n\
topology, so be *very* careful with the molecule that comes back from\n\
this function.\n\
\n";
python::def("AddHs", addHs,
(python::arg("mol"), python::arg("explicitOnly") = false,
python::arg("addCoords") = false,
python::arg("onlyOnAtoms") = python::object()),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
// ------------------------------------------------------------------------
docString =
"Removes any hydrogens from the graph of a molecule.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to be modified\n\
\n\
- implicitOnly: (optional) if this toggle is set, only implicit Hs will\n\
be removed from the graph. Default value is 0 (remove implicit and explicit Hs).\n\
\n\
- updateExplicitCount: (optional) if this toggle is set, the explicit H count on atoms with \n\
Hs will be updated. Default value is 0 (do not update explicit H count).\n\
\n\
- sanitize: (optional) if this toggle is set, the molecule will be sanitized after the Hs\n\
are removed. Default value is 1 (do sanitize).\n\
\n\
RETURNS: a new molecule with the Hs removed\n\
\n\
NOTES:\n\
\n\
- The original molecule is *not* modified.\n\
\n";
python::def("RemoveHs",
(ROMol * (*)(const ROMol &, bool, bool, bool))MolOps::removeHs,
(python::arg("mol"), python::arg("implicitOnly") = false,
python::arg("updateExplicitCount") = false,
python::arg("sanitize") = true),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
python::def("MergeQueryHs",
(ROMol * (*)(const ROMol &, bool)) & MolOps::mergeQueryHs,
(python::arg("mol"), python::arg("mergeUnmappedOnly") = false),
"merges hydrogens into their neighboring atoms as queries",
python::return_value_policy<python::manage_new_object>());
// ------------------------------------------------------------------------
docString =
"Removes atoms matching a substructure query from a molecule\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to be modified\n\
\n\
- query: the molecule to be used as a substructure query\n\
\n\
- onlyFrags: (optional) if this toggle is set, atoms will only be removed if\n\
the entire fragment in which they are found is matched by the query.\n\
See below for examples.\n\
Default value is 0 (remove the atoms whether or not the entire fragment matches)\n\
\n\
- useChirality: (optional) match the substructure query using chirality\n\
\n\
RETURNS: a new molecule with the substructure removed\n\
\n\
NOTES:\n\
\n\
- The original molecule is *not* modified.\n\
\n\
EXAMPLES:\n\
\n\
The following examples substitute SMILES/SMARTS strings for molecules, you'd have\n\
to actually use molecules:\n\
\n\
- DeleteSubstructs('CCOC','OC') -> 'CC'\n\
\n\
- DeleteSubstructs('CCOC','OC',1) -> 'CCOC'\n\
\n\
- DeleteSubstructs('CCOCCl.Cl','Cl',1) -> 'CCOCCl'\n\
\n\
- DeleteSubstructs('CCOCCl.Cl','Cl') -> 'CCOC'\n\
\n";
python::def("DeleteSubstructs", deleteSubstructs,
(python::arg("mol"), python::arg("query"),
python::arg("onlyFrags") = false,
python::arg("useChirality") = false),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
docString = "Do a Murcko decomposition and return the scaffold";
python::def("MurckoDecompose", MurckoDecompose, (python::arg("mol")),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
docString = "Combine the atoms from two molecules to produce a third";
python::def("CombineMols", combineMols,
(python::arg("mol1"), python::arg("mol2"),
python::arg("offset") = RDGeom::Point3D(0, 0, 0)),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
// ------------------------------------------------------------------------
docString =
"Replaces atoms matching a substructure query in a molecule\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to be modified\n\
\n\
- query: the molecule to be used as a substructure query\n\
\n\
- replacement: the molecule to be used as the replacement\n\
\n\
- replaceAll: (optional) if this toggle is set, all substructures matching\n\
the query will be replaced in a single result, otherwise each result will\n\
contain a separate replacement.\n\
Default value is False (return multiple replacements)\n\
- replacementConnectionPoint: (optional) index of the atom in the replacement that\n\
the bond should be made to.\n\
- useChirality: (optional) match the substructure query using chirality\n\
\n\
RETURNS: a tuple of new molecules with the substructures replaced removed\n\
\n\
NOTES:\n\
\n\
- The original molecule is *not* modified.\n\
\n\
EXAMPLES:\n\
\n\
The following examples substitute SMILES/SMARTS strings for molecules, you'd have\n\
to actually use molecules:\n\
\n\
- ReplaceSubstructs('CCOC','OC','NC') -> ('CCNC',)\n\
\n\
- ReplaceSubstructs('COCCOC','OC','NC') -> ('COCCNC','CNCCOC')\n\
\n\
- ReplaceSubstructs('COCCOC','OC','NC',True) -> ('CNCCNC',)\n\
\n\
- ReplaceSubstructs('COCCOC','OC','CN',True,1) -> ('CNCCNC',)\n\
\n";
python::def("ReplaceSubstructs", replaceSubstructures,
(python::arg("mol"), python::arg("query"),
python::arg("replacement"), python::arg("replaceAll") = false,
python::arg("replacementConnectionPoint") = 0,
python::arg("useChirality") = false),
docString.c_str());
// ------------------------------------------------------------------------
docString = "Adds named recursive queries to atoms\n";
python::def(
"MolAddRecursiveQueries", addRecursiveQueriesHelper,
(python::arg("mol"), python::arg("queries"), python::arg("propName")),
docString.c_str());
docString = "reads query definitions from a simply formatted file\n";
python::def(
"ParseMolQueryDefFile", parseQueryDefFileHelper,
(python::arg("fileobj"), python::arg("standardize") = true,
python::arg("delimiter") = "\t", python::arg("comment") = "//",
python::arg("nameColumn") = 0, python::arg("smartsColumn") = 1),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Returns the molecule's topological distance matrix.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
- useBO: (optional) toggles use of bond orders in calculating the distance matrix.\n\
Default value is 0.\n\
\n\
- useAtomWts: (optional) toggles using atom weights for the diagonal elements of the\n\
matrix (to return a \"Balaban\" distance matrix).\n\
Default value is 0.\n\
\n\
- force: (optional) forces the calculation to proceed, even if there is a cached value.\n\
Default value is 0.\n\
\n\
- prefix: (optional, internal use) sets the prefix used in the property cache\n\
Default value is "
".\n\
\n\
RETURNS: a Numeric array of floats with the distance matrix\n\
\n";
python::def("GetDistanceMatrix", getDistanceMatrix,
(python::arg("mol"), python::arg("useBO") = false,
python::arg("useAtomWts") = false,
python::arg("force") = false, python::arg("prefix") = ""),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Returns the molecule's 3D distance matrix.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
- confId: (optional) chooses the conformer Id to use\n\
Default value is -1.\n\
\n\
- useAtomWts: (optional) toggles using atom weights for the diagonal elements of the\n\
matrix (to return a \"Balaban\" distance matrix).\n\
Default value is 0.\n\
\n\
- force: (optional) forces the calculation to proceed, even if there is a cached value.\n\
Default value is 0.\n\
\n\
- prefix: (optional, internal use) sets the prefix used in the property cache\n\
Default value is "
".\n\
\n\
RETURNS: a Numeric array of floats with the distance matrix\n\
\n";
python::def("Get3DDistanceMatrix", get3DDistanceMatrix,
(python::arg("mol"), python::arg("confId") = -1,
python::arg("useAtomWts") = false,
python::arg("force") = false, python::arg("prefix") = ""),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Returns the molecule's adjacency matrix.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
- useBO: (optional) toggles use of bond orders in calculating the matrix.\n\
Default value is 0.\n\
\n\
- emptyVal: (optional) sets the elements of the matrix between non-adjacent atoms\n\
Default value is 0.\n\
\n\
- force: (optional) forces the calculation to proceed, even if there is a cached value.\n\
Default value is 0.\n\
\n\
- prefix: (optional, internal use) sets the prefix used in the property cache\n\
Default value is "
".\n\
\n\
RETURNS: a Numeric array of floats containing the adjacency matrix\n\
\n";
python::def("GetAdjacencyMatrix", getAdjacencyMatrix,
(python::arg("mol"), python::arg("useBO") = false,
python::arg("emptyVal") = 0, python::arg("force") = false,
python::arg("prefix") = ""),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Kekulizes the molecule\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
- clearAromaticFlags: (optional) if this toggle is set, all atoms and bonds in the \n\
molecule will be marked non-aromatic following the kekulization.\n\
Default value is 0.\n\
\n\
NOTES:\n\
\n\
- The molecule is modified in place.\n\
\n";
python::def("Kekulize", kekulizeMol,
(python::arg("mol"), python::arg("clearAromaticFlags") = false),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"cleans up certain common bad functionalities in the molecule\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
NOTES:\n\
\n\
- The molecule is modified in place.\n\
\n";
python::def("Cleanup", cleanupMol, (python::arg("mol")), docString.c_str());
python::enum_<MolOps::AromaticityModel>("AromaticityModel")
.value("AROMATICITY_DEFAULT", MolOps::AROMATICITY_DEFAULT)
.value("AROMATICITY_RDKIT", MolOps::AROMATICITY_RDKIT)
.value("AROMATICITY_SIMPLE", MolOps::AROMATICITY_SIMPLE)
.value("AROMATICITY_CUSTOM", MolOps::AROMATICITY_CUSTOM)
.export_values();
// ------------------------------------------------------------------------
docString =
"does aromaticity perception\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
- model: the model to use\n\
\n\
NOTES:\n\
\n\
- The molecule is modified in place.\n\
\n";
python::def("SetAromaticity", setAromaticityMol,
(python::arg("mol"),
python::arg("model") = MolOps::AROMATICITY_DEFAULT),
docString.c_str());
docString =
"finds conjugated bonds\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
NOTES:\n\
\n\
- The molecule is modified in place.\n\
\n";
python::def("SetConjugation", setConjugationMol, (python::arg("mol")),
docString.c_str());
docString =
"Assigns hybridization states to atoms\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
NOTES:\n\
\n\
- The molecule is modified in place.\n\
\n";
python::def("SetHybridization", setHybridizationMol, (python::arg("mol")),
docString.c_str());
docString =
"Assigns radical counts to atoms\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
NOTES:\n\
\n\
- The molecule is modified in place.\n\
\n";
python::def("AssignRadicals", assignRadicalsMol, (python::arg("mol")),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Finds all subgraphs of a particular length in a molecule\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
- length: an integer with the target number of bonds for the subgraphs.\n\
\n\
- useHs: (optional) toggles whether or not bonds to Hs that are part of the graph\n\
should be included in the results.\n\
Defaults to 0.\n\
\n\
- rootedAtAtom: (optional) if nonzero, only subgraphs from the specified\n\
atom will be returned.\n\
\n\
RETURNS: a tuple of 2-tuples with bond IDs\n\
\n\
NOTES: \n\
\n\
- Difference between _subgraphs_ and _paths_ :: \n\
\n\
Subgraphs are potentially branched, whereas paths (in our \n\
terminology at least) cannot be. So, the following graph: \n\
\n\
C--0--C--1--C--3--C\n\
|\n\
2\n\
|\n\
C\n\
has 3 _subgraphs_ of length 3: (0,1,2),(0,1,3),(2,1,3)\n\
but only 2 _paths_ of length 3: (0,1,3),(2,1,3)\n\
\n";
python::def(
"FindAllSubgraphsOfLengthN", &findAllSubgraphsOfLengthN,
(python::arg("mol"), python::arg("length"),
python::arg("useHs") = false, python::arg("rootedAtAtom") = -1),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Finds all subgraphs of a particular length in a molecule\n\
See documentation for FindAllSubgraphsOfLengthN for definitions\n\
\n";
python::def(
"FindAllSubgraphsOfLengthMToN", &findAllSubgraphsOfLengthsMtoNHelper,
(python::arg("mol"), python::arg("min"), python::arg("max"),
python::arg("useHs") = false, python::arg("rootedAtAtom") = -1),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Finds unique subgraphs of a particular length in a molecule\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
- length: an integer with the target number of bonds for the subgraphs.\n\
\n\
- useHs: (optional) toggles whether or not bonds to Hs that are part of the graph\n\
should be included in the results.\n\
Defaults to 0.\n\
\n\
- useBO: (optional) Toggles use of bond orders in distinguishing one subgraph from\n\
another.\n\
Defaults to 1.\n\
\n\
- rootedAtAtom: (optional) if nonzero, only subgraphs from the specified\n\
atom will be returned.\n\
\n\
RETURNS: a tuple of tuples with bond IDs\n\
\n\
\n";
python::def("FindUniqueSubgraphsOfLengthN", &findUniqueSubgraphsOfLengthN,
(python::arg("mol"), python::arg("length"),
python::arg("useHs") = false, python::arg("useBO") = true,
python::arg("rootedAtAtom") = -1),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Finds all paths of a particular length in a molecule\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
- length: an integer with the target length for the paths.\n\
\n\
- useBonds: (optional) toggles the use of bond indices in the paths.\n\
Otherwise atom indices are used. *Note* this behavior is different\n\
from that for subgraphs.\n\
Defaults to 1.\n\
\n\
- rootedAtAtom: (optional) if nonzero, only paths from the specified\n\
atom will be returned.\n\
\n\
RETURNS: a tuple of tuples with IDs for the bonds.\n\
\n\
NOTES: \n\
\n\
- Difference between _subgraphs_ and _paths_ :: \n\
\n\
Subgraphs are potentially branched, whereas paths (in our \n\
terminology at least) cannot be. So, the following graph: \n\
\n\
C--0--C--1--C--3--C\n\
|\n\
2\n\
|\n\
C\n\
\n\
has 3 _subgraphs_ of length 3: (0,1,2),(0,1,3),(2,1,3)\n\
but only 2 _paths_ of length 3: (0,1,3),(2,1,3)\n\
\n";
python::def("FindAllPathsOfLengthN", &findAllPathsOfLengthN,
(python::arg("mol"), python::arg("length"),
python::arg("useBonds") = true, python::arg("useHs") = false,
python::arg("rootedAtAtom") = -1),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Finds the bonds within a certain radius of an atom in a molecule\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
- radius: an integer with the target radius for the environment.\n\
\n\
- rootedAtAtom: the atom to consider\n\
\n\
- useHs: (optional) toggles whether or not bonds to Hs that are part of the graph\n\
should be included in the results.\n\
Defaults to 0.\n\
\n\
RETURNS: a vector of bond IDs\n\
\n\
\n";
python::def("FindAtomEnvironmentOfRadiusN", &findAtomEnvironmentOfRadiusN,
(python::arg("mol"), python::arg("radius"),
python::arg("rootedAtAtom"), python::arg("useHs") = false),
docString.c_str());
python::def("PathToSubmol", pathToSubmolHelper,
(python::arg("mol"), python::arg("path"),
python::arg("useQuery") = false,
python::arg("atomMap") = python::object()),
"", python::return_value_policy<python::manage_new_object>());
// ------------------------------------------------------------------------
docString =
"Finds the disconnected fragments from a molecule.\n\
\n\
For example, for the molecule 'CC(=O)[O-].[NH3+]C' GetMolFrags() returns\n\
((0, 1, 2, 3), (4, 5))\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
- asMols: (optional) if this is provided and true, the fragments\n\
will be returned as molecules instead of atom ids.\n\
- sanitizeFrags: (optional) if this is provided and true, the fragments\n\
molecules will be sanitized before returning them.\n\
\n\
RETURNS: a tuple of tuples with IDs for the atoms in each fragment\n\
or a tuple of molecules.\n\
\n";
python::def("GetMolFrags", &GetMolFrags,
(python::arg("mol"), python::arg("asMols") = false,
python::arg("sanitizeFrags") = true),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Splits a molecule into pieces based on PDB residue information.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
- whiteList: only residues in this list will be returned\n\
- negateList: if set, negates the white list inclusion logic\n\
\n\
RETURNS: a dictionary keyed by residue name with molecules as the values\n\
\n";
python::def(
"SplitMolByPDBResidues", &splitMolByPDBResidues,
(python::arg("mol"), python::arg("whiteList") = python::object(),
python::arg("negateList") = false),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Splits a molecule into pieces based on PDB chain information.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
- whiteList: only residues in this list will be returned\n\
- negateList: if set, negates the white list inclusion logic\n\
\n\
RETURNS: a dictionary keyed by chain id with molecules as the values\n\
\n";
python::def(
"SplitMolByPDBChainId", &splitMolByPDBChainId,
(python::arg("mol"), python::arg("whiteList") = python::object(),
python::arg("negateList") = false),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Returns the formal charge for the molecule.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n";
python::def("GetFormalCharge", &MolOps::getFormalCharge, docString.c_str());
// ------------------------------------------------------------------------
docString =
"Find the shortest path between two atoms using the Bellman-Ford algorithm.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
- idx1: index of the first atom\n\
- idx2: index of the second atom\n\
\n";
python::def("GetShortestPath", getShortestPathHelper, docString.c_str());
// ------------------------------------------------------------------------
docString =
"Does the CIP stereochemistry assignment \n\
for the molecule's atoms (R/S) and double bond (Z/E).\n\
Chiral atoms will have a property '_CIPCode' indicating\n\
their chiral code.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
- cleanIt: (optional) if provided, atoms with a chiral specifier that aren't\n\
actually chiral (e.g. atoms with duplicate substituents or only 2 substituents,\n\
etc.) will have their chiral code set to CHI_UNSPECIFIED\n\
- force: (optional) causes the calculation to be repeated, even if it has already\n\
been done\n\
- flagPossibleStereoCenters (optional) set the _ChiralityPossible property on\n\
atoms that are possible stereocenters\n\
\n";
python::def("AssignStereochemistry", MolOps::assignStereochemistry,
(python::arg("mol"), python::arg("cleanIt") = false,
python::arg("force") = false,
python::arg("flagPossibleStereoCenters") = false),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Removes all stereochemistry info from the molecule.\n\
\n";
python::def("RemoveStereochemistry", MolOps::removeStereochemistry,
(python::arg("mol")), docString.c_str());
// ------------------------------------------------------------------------
docString =
"Sets the chiral tags on a molecule's atoms based on \n\
a 3D conformation.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
- confId: the conformer id to use, -1 for the default \n\
- replaceExistingTags: if True, existing stereochemistry information will be cleared \n\
before running the calculation. \n\
\n";
python::def("AssignAtomChiralTagsFromStructure",
MolOps::assignChiralTypesFrom3D,
(python::arg("mol"), python::arg("confId") = -1,
python::arg("replaceExistingTags") = true),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Returns an RDKit topological fingerprint for a molecule\n\
\n\
Explanation of the algorithm below.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
- minPath: (optional) minimum number of bonds to include in the subgraphs\n\
Defaults to 1.\n\
\n\
- maxPath: (optional) maximum number of bonds to include in the subgraphs\n\
Defaults to 7.\n\
\n\
- fpSize: (optional) number of bits in the fingerprint\n\
Defaults to 2048.\n\
\n\
- nBitsPerHash: (optional) number of bits to set per path\n\
Defaults to 2.\n\
\n\
- useHs: (optional) include paths involving Hs in the fingerprint if the molecule\n\
has explicit Hs.\n\
Defaults to True.\n\
\n\
- tgtDensity: (optional) fold the fingerprint until this minimum density has\n\
been reached\n\
Defaults to 0.\n\
\n\
- minSize: (optional) the minimum size the fingerprint will be folded to when\n\
trying to reach tgtDensity\n\
Defaults to 128.\n\
\n\
- branchedPaths: (optional) if set both branched and unbranched paths will be\n\
used in the fingerprint.\n\
Defaults to True.\n\
\n\
- useBondOrder: (optional) if set both bond orders will be used in the path hashes\n\
Defaults to True.\n\
\n\
- atomInvariants: (optional) a sequence of atom invariants to use in the path hashes\n\
Defaults to empty.\n\
\n\
- fromAtoms: (optional) a sequence of atom indices. If provided, only paths/subgraphs \n\
starting from these atoms will be used.\n\
Defaults to empty.\n\
\n\
- atomBits: (optional) an empty list. If provided, the result will contain a list \n\
containing the bits each atom sets.\n\
Defaults to empty.\n\
\n\
- bitInfo: (optional) an empty dict. If provided, the result will contain a dict \n\
with bits as keys and corresponding bond paths as values.\n\
Defaults to empty.\n\
\n\
RETURNS: a DataStructs.ExplicitBitVect with _fpSize_ bits\n\
\n\
ALGORITHM:\n\
\n\
This algorithm functions by find all subgraphs between minPath and maxPath in\n\
length. For each subgraph:\n\
\n\
1) A hash is calculated.\n\
\n\
2) The hash is used to seed a random-number generator\n\
\n\
3) _nBitsPerHash_ random numbers are generated and used to set the corresponding\n\
bits in the fingerprint\n\
\n\
\n";
python::def(
"RDKFingerprint", wrapRDKFingerprintMol,
(python::arg("mol"), python::arg("minPath") = 1,
python::arg("maxPath") = 7, python::arg("fpSize") = 2048,
python::arg("nBitsPerHash") = 2, python::arg("useHs") = true,
python::arg("tgtDensity") = 0.0, python::arg("minSize") = 128,
python::arg("branchedPaths") = true,
python::arg("useBondOrder") = true, python::arg("atomInvariants") = 0,
python::arg("fromAtoms") = 0,
python::arg("atomBits") = python::object(),
python::arg("bitInfo") = python::object()),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
python::scope().attr("_RDKFingerprint_version") =
RDKit::RDKFingerprintMolVersion;
docString =
"Returns an unfolded count-based version of the RDKit fingerprint for a molecule\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
- minPath: (optional) minimum number of bonds to include in the subgraphs\n\
Defaults to 1.\n\
\n\
- maxPath: (optional) maximum number of bonds to include in the subgraphs\n\
Defaults to 7.\n\
\n\
- useHs: (optional) include paths involving Hs in the fingerprint if the molecule\n\
has explicit Hs.\n\
Defaults to True.\n\
\n\
- branchedPaths: (optional) if set both branched and unbranched paths will be\n\
used in the fingerprint.\n\
Defaults to True.\n\
\n\
- useBondOrder: (optional) if set both bond orders will be used in the path hashes\n\
Defaults to True.\n\
\n\
- atomInvariants: (optional) a sequence of atom invariants to use in the path hashes\n\
Defaults to empty.\n\
\n\
- fromAtoms: (optional) a sequence of atom indices. If provided, only paths/subgraphs \n\
starting from these atoms will be used.\n\
Defaults to empty.\n\
\n\
- atomBits: (optional) an empty list. If provided, the result will contain a list \n\
containing the bits each atom sets.\n\
Defaults to empty.\n\
\n\
- bitInfo: (optional) an empty dict. If provided, the result will contain a dict \n\
with bits as keys and corresponding bond paths as values.\n\
Defaults to empty.\n\
\n\
\n";
python::def(
"UnfoldedRDKFingerprintCountBased", wrapUnfoldedRDKFingerprintMol,
(python::arg("mol"), python::arg("minPath") = 1,
python::arg("maxPath") = 7, python::arg("useHs") = true,
python::arg("branchedPaths") = true,
python::arg("useBondOrder") = true, python::arg("atomInvariants") = 0,
python::arg("fromAtoms") = 0,
python::arg("atomBits") = python::object(),
python::arg("bitInfo") = python::object()),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
// ------------------------------------------------------------------------
docString =
"Returns a layered fingerprint for a molecule\n\
\n\
NOTE: This function is experimental. The API or results may change from\n\
release to release.\n\
\n\
Explanation of the algorithm below.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to use\n\
\n\
- layerFlags: (optional) which layers to include in the fingerprint\n\
See below for definitions. Defaults to all.\n\
\n\
- minPath: (optional) minimum number of bonds to include in the subgraphs\n\
Defaults to 1.\n\
\n\
- maxPath: (optional) maximum number of bonds to include in the subgraphs\n\
Defaults to 7.\n\
\n\
- fpSize: (optional) number of bits in the fingerprint\n\
Defaults to 2048.\n\
\n\
- atomCounts: (optional) \n\
if provided, this should be a list at least as long as the number of atoms\n\
in the molecule. It will be used to provide the count of the number \n\
of paths that set bits each atom is involved in.\n\
NOTE: the list is not zeroed out here.\n\
\n\
- setOnlyBits: (optional) \n\
if provided, only bits that are set in this bit vector will be set\n\
in the result. This is essentially the same as doing:\n\
res &= setOnlyBits\n\
but also has an impact on the atomCounts (if being used)\n\
\n\
- branchedPaths: (optional) if set both branched and unbranched paths will be\n\
used in the fingerprint.\n\
Defaults to True.\n\
\n\
- fromAtoms: (optional) a sequence of atom indices. If provided, only paths/subgraphs \n\
starting from these atoms will be used.\n\
Defaults to empty.\n\
\n\
RETURNS: a DataStructs.ExplicitBitVect with _fpSize_ bits\n\
\n\
Layer definitions:\n\
- 0x01: pure topology\n\
- 0x02: bond order\n\
- 0x04: atom types\n\
- 0x08: presence of rings\n\
- 0x10: ring sizes\n\
- 0x20: aromaticity\n\
\n\
\n";
python::def(
"LayeredFingerprint", wrapLayeredFingerprint,
(python::arg("mol"), python::arg("layerFlags") = 0xFFFFFFFF,
python::arg("minPath") = 1, python::arg("maxPath") = 7,
python::arg("fpSize") = 2048,
python::arg("atomCounts") = python::list(),
python::arg("setOnlyBits") = (ExplicitBitVect *)0,
python::arg("branchedPaths") = true, python::arg("fromAtoms") = 0),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
python::scope().attr("_LayeredFingerprint_version") =
RDKit::LayeredFingerprintMolVersion;
python::scope().attr("LayeredFingerprint_substructLayers") =
RDKit::substructLayers;
// ------------------------------------------------------------------------
docString =
"A fingerprint using SMARTS patterns \n\
\n\
NOTE: This function is experimental. The API or results may change from\n\
release to release.\n";
python::def("PatternFingerprint", wrapPatternFingerprint,
(python::arg("mol"), python::arg("fpSize") = 2048,
python::arg("atomCounts") = python::list(),
python::arg("setOnlyBits") = (ExplicitBitVect *)0),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
docString =
"Set the wedging on single bonds in a molecule.\n\
The wedging scheme used is that from Mol files.\n\
\n\
ARGUMENTS:\n\
\n\
- molecule: the molecule to update\n\
\n\
\n";
python::def("WedgeMolBonds", WedgeMolBonds, docString.c_str());
// ------------------------------------------------------------------------
docString =
"Replaces sidechains in a molecule with dummy atoms for their attachment points.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to be modified\n\
\n\
- coreQuery: the molecule to be used as a substructure query for recognizing the core\n\
\n\
- useChirality: (optional) match the substructure query using chirality\n\
\n\
RETURNS: a new molecule with the sidechains removed\n\
\n\
NOTES:\n\
\n\
- The original molecule is *not* modified.\n\
\n\
EXAMPLES:\n\
\n\
The following examples substitute SMILES/SMARTS strings for molecules, you'd have\n\
to actually use molecules:\n\
\n\
- ReplaceSidechains('CCC1CCC1','C1CCC1') -> '[Xa]C1CCC1'\n\
\n\
- ReplaceSidechains('CCC1CC1','C1CCC1') -> ''\n\
\n\
- ReplaceSidechains('C1CC2C1CCC2','C1CCC1') -> '[Xa]C1CCC1[Xb]'\n\
\n";
python::def("ReplaceSidechains", replaceSidechains,
(python::arg("mol"), python::arg("coreQuery"),
python::arg("useChirality") = false),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
// ------------------------------------------------------------------------
docString =
"Removes the core of a molecule and labels the sidechains with dummy atoms based on\n\
The matches indices given in the matching vector matches.\n\
Calling:\n\
ReplaceCore(mol,core,mol.GetSubstructMatch(core))\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to be modified\n\
\n\
- coreQuery: the molecule to be used as a substructure query for recognizing the core\n\
\n\
- matches: a matching vector of the type returned by mol.GetSubstructMatch(...)\n\
\n\
- replaceDummies: toggles replacement of atoms that match dummies in the query\n\
\n\
- labelByIndex: toggles labeling the attachment point dummy atoms with \n\
the index of the core atom they're attached to.\n\
\n\
- requireDummyMatch: if the molecule has side chains that attach at points not\n\
flagged with a dummy, it will be rejected (None is returned)\n\
\n\
RETURNS: a new molecule with the core removed\n\
\n\
NOTES:\n\
\n\
- The original molecule is *not* modified.\n\
EXAMPLES:\n\
>>> from rdkit.Chem import MolToSmiles, MolFromSmiles, ReplaceCore\n\
>>> mol = MolFromSmiles('C1ONNCC1')\n\
>>> core = MolFromSmiles('NN')\n\
\n\
Note: Using isomericSmiles is necessary to see the labels.\n\
>>> MolToSmiles(ReplaceCore(mol, core, mol.GetSubstructMatch(core)), isomericSmiles=True)\n\
'[1*]OCCC[2*]'\n\
\n\
Since NN is symmetric, we should actually get two matches here if we don't\n\
uniquify the matches.\n\
>>> [MolToSmiles(ReplaceCore(mol, core, match), isomericSmiles=True)\n\
... for match in mol.GetSubstructMatches(core, uniquify=False)]\n\
['[1*]OCCC[2*]', '[1*]CCCO[2*]']\n\
\n\
";
python::def("ReplaceCore",
replaceCoreHelper,
(python::arg("mol"), python::arg("core"), python::arg("matches"),
python::arg("replaceDummies") = true,
python::arg("labelByIndex") = false,
python::arg("requireDummyMatch") = false),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
// ------------------------------------------------------------------------
docString =
"Removes the core of a molecule and labels the sidechains with dummy atoms.\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to be modified\n\
\n\
- coreQuery: the molecule to be used as a substructure query for recognizing the core\n\
\n\
- replaceDummies: toggles replacement of atoms that match dummies in the query\n\
\n\
- labelByIndex: toggles labeling the attachment point dummy atoms with \n\
the index of the core atom they're attached to.\n\
\n\
- requireDummyMatch: if the molecule has side chains that attach at points not\n\
flagged with a dummy, it will be rejected (None is returned)\n\
\n\
- useChirality: use chirality matching in the coreQuery\n\
\n\
RETURNS: a new molecule with the core removed\n\
\n\
NOTES:\n\
\n\
- The original molecule is *not* modified.\n\
\n\
EXAMPLES:\n\
\n\
>>> from rdkit.Chem import MolToSmiles, MolFromSmiles, MolFromSmarts, ReplaceCore\n\
\n\
Basic usage: remove a core as specified by SMILES (or another molecule).\n\
To get the atom labels which are stored as an isotope of the matched atom, \n\
the output must be written as isomeric smiles. \n\
A small confusion is that atom isotopes of 0 aren't shown in smiles strings.\n\
\n\
Here we remove a ring and leave the decoration (r-group) behind.\n\
\n\
>>> MolToSmiles(ReplaceCore(MolFromSmiles('CCCC1CCC1'),MolFromSmiles('C1CCC1')),\n\
... isomericSmiles=True)\n\
'[1*]CCC'\n\
\n\
The isotope label by default is matched by the first connection found. In order to\n\
indicate which atom the decoration is attached in the core query, use labelByIndex=True.\n\
Here the attachment is from the third atom in the smiles string, which is indexed by 3\n\
in the core, like all good computer scientists expect, atoms indices start at 0.\n\
>>> MolToSmiles(ReplaceCore(MolFromSmiles('CCN1CCC1'),MolFromSmiles('C1CCN1'),\n\
... labelByIndex=True),\n\
... isomericSmiles=True)\n\
'[3*]CC'\n\
\n\
Non-core matches just return None\n\
>>> ReplaceCore(MolFromSmiles('CCC1CC1'),MolFromSmiles('C1CCC1'))\n\
\n\
The bond between atoms are considered part of the core and are removed as well\n\
>>> MolToSmiles(ReplaceCore(MolFromSmiles('C1CC2C1CCC2'),MolFromSmiles('C1CCC1')),\n\
... isomericSmiles=True)\n\
'[1*]CCC[2*]'\n\
>>> MolToSmiles(ReplaceCore(MolFromSmiles('C1CNCC1'),MolFromSmiles('N')),\n\
... isomericSmiles=True)\n\
'[1*]CCCC[2*]'\n\
\n\
When using dummy atoms, cores should be read in as SMARTS. When read as SMILES\n\
dummy atoms only match other dummy atoms.\n\
The replaceDummies flag indicates whether matches to the dummy atoms should be considered as part\n\
of the core or as part of the decoration (r-group)\n\
>>> MolToSmiles(ReplaceCore(MolFromSmiles('C1CNCC1'),MolFromSmarts('[*]N[*]'),\n\
... replaceDummies=True),\n\
... isomericSmiles=True)\n\
'[1*]CC[2*]'\n\
>>> MolToSmiles(ReplaceCore(MolFromSmiles('C1CNCC1'),MolFromSmarts('[*]N[*]'),\n\
... replaceDummies=False),\n\
... isomericSmiles=True)\n\
'[1*]CCCC[2*]'\n\
\n\
\n\
>>> MolToSmiles(ReplaceCore(MolFromSmiles('C1CCC1CN'),MolFromSmarts('C1CCC1[*]'),\n\
... replaceDummies=False),\n\
... isomericSmiles=True)\n\
'[1*]CN'\n\
\n\
\n";
python::def("ReplaceCore",
(ROMol *(*)(const ROMol&, const ROMol&, bool,bool,bool,bool))replaceCore,
(python::arg("mol"), python::arg("coreQuery"),
python::arg("replaceDummies") = true,
python::arg("labelByIndex") = false,
python::arg("requireDummyMatch") = false,
python::arg("useChirality") = false),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
docString = "Return a new molecule with all BRICS bonds broken";
python::def("FragmentOnBRICSBonds", MolFragmenter::fragmentOnBRICSBonds,
(python::arg("mol")), docString.c_str(),
python::return_value_policy<python::manage_new_object>());
docString =
"Return a new molecule with all specified bonds broken\n\
\n\
ARGUMENTS:\n\
\n\
- mol - the molecule to be modified\n\
- bondIndices - indices of the bonds to be broken\n\
- addDummies - toggles addition of dummy atoms to indicate where \n\
bonds were broken\n\
- dummyLabels - used to provide the labels to be used for the dummies.\n\
the first element in each pair is the label for the dummy\n\
that replaces the bond's beginAtom, the second is for the \n\
dummy that replaces the bond's endAtom. If not provided, the\n\
dummies are labeled with atom indices.\n\
- bondTypes - used to provide the bond type to use between the\n\
fragments and the dummy atoms. If not provided, defaults to single. \n\
- cutsPerAtom - used to return the number of cuts made at each atom. \n\
\n\
RETURNS:\n\
a new Mol with the modifications\n\
";
python::def("FragmentOnBonds", fragmentOnBondsHelper,
(python::arg("mol"), python::arg("bondIndices"),
python::arg("addDummies") = true,
python::arg("dummyLabels") = python::object(),
python::arg("bondTypes") = python::object(),
python::arg("cutsPerAtom") = python::list()),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
docString = "fragment on some bonds";
python::def(
"FragmentOnSomeBonds", fragmentOnSomeBondsHelper,
(python::arg("mol"), python::arg("bondIndices"),
python::arg("numToBreak") = 1, python::arg("addDummies") = true,
python::arg("dummyLabels") = python::object(),
python::arg("bondTypes") = python::object(),
python::arg("returnCutsPerAtom") = false),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Adds a recursive query to an atom\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to be modified\n\
\n\
- query: the molecule to be used as the recursive query (this will be copied)\n\
\n\
- atomIdx: the atom to modify\n\
\n\
- preserveExistingQuery: (optional) if this is set, existing query information on the atom will be preserved\n\
\n\
RETURNS: None\n\
\n";
python::def(
"AddRecursiveQuery", addRecursiveQuery,
(python::arg("mol"), python::arg("query"), python::arg("atomIdx"),
python::arg("preserveExistingQuery") = true),
docString.c_str());
// ------------------------------------------------------------------------
docString =
"Returns a copy of a molecule with renumbered atoms\n\
\n\
ARGUMENTS:\n\
\n\
- mol: the molecule to be modified\n\
\n\
- newOrder: the new ordering the atoms (should be numAtoms long)\n\
for example: if newOrder is [3,2,0,1], then atom 3 in the original \n\
molecule will be atom 0 in the new one\n\
\n\
\n";
python::def("RenumberAtoms", renumberAtomsHelper,
(python::arg("mol"), python::arg("newOrder")),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
// ------------------------------------------------------------------------
docString = "Returns svg for a molecule";
python::def("MolToSVG", molToSVG,
(python::arg("mol"), python::arg("width") = 300,
python::arg("height") = 300,
python::arg("highlightAtoms") = python::object(),
python::arg("kekulize") = true,
python::arg("lineWidthMult") = 1, python::arg("fontSize") = 12,
python::arg("includeAtomCircles") = true),
docString.c_str());
python::enum_<MolOps::AdjustQueryWhichFlags>("AdjustQueryWhichFlags")
.value("ADJUST_IGNORENONE", MolOps::ADJUST_IGNORENONE)
.value("ADJUST_IGNORECHAINATOMS", MolOps::ADJUST_IGNORECHAINATOMS)
.value("ADJUST_IGNORERINGATOMS", MolOps::ADJUST_IGNORERINGATOMS)
.value("ADJUST_IGNOREDUMMIES", MolOps::ADJUST_IGNOREDUMMIES)
.value("ADJUST_IGNORENONDUMMIES", MolOps::ADJUST_IGNORENONDUMMIES)
.value("ADJUST_IGNOREALL", MolOps::ADJUST_IGNOREALL)
.export_values();
docString =
"Parameters controlling which components of the query atoms are adjusted.\n\
\n\
Attributes:\n\
- adjustDegree: \n\
modified atoms have an explicit-degree query added based on their degree in the query \n\
- adjustDegreeFlags: \n\
controls which atoms have a degree query added \n\
- adjustRingCount: \n\
modified atoms have a ring-count query added based on their ring count in the query \n\
- adjustRingCountFlags: \n\
controls which atoms have a ring-cout query added \n\
- makeDummiesQueries: \n\
dummy atoms that do not have a specified isotope are converted to any-atom queries \n\
- aromatizeIfPossible: \n\
attempts aromaticity perception on the molecule \n\
\n\
A note on the flags controlling which atoms are modified: \n\
These generally limit the set of atoms to be modified.\n\
For example if ADJUST_RINGSONLY is set, then only atoms in rings will be modified.\n\
ADJUST_IGNORENONE causes all atoms to be modified\n\
ADJUST_SETALL sets all of the ADJUST flags\n\
";
python::class_<MolOps::AdjustQueryParameters>("AdjustQueryParameters",
docString.c_str())
.def_readwrite("adjustDegree",
&MolOps::AdjustQueryParameters::adjustDegree)
.def_readwrite("adjustDegreeFlags",
&MolOps::AdjustQueryParameters::adjustDegreeFlags)
.def_readwrite("adjustRingCount",
&MolOps::AdjustQueryParameters::adjustRingCount)
.def_readwrite("adjustRingCountFlags",
&MolOps::AdjustQueryParameters::adjustRingCountFlags)
.def_readwrite("makeDummiesQueries",
&MolOps::AdjustQueryParameters::makeDummiesQueries)
.def_readwrite("aromatizeIfPossible",
&MolOps::AdjustQueryParameters::aromatizeIfPossible);
docString =
"Returns a new molecule where the query properties of atoms have been "
"modified.";
python::def("AdjustQueryProperties", adjustQueryPropertiesHelper,
(python::arg("mol"), python::arg("params") = python::object()),
docString.c_str(),
python::return_value_policy<python::manage_new_object>());
};
};
}
void wrap_molops() { RDKit::molops_wrapper::wrap(); }
|
jandom/rdkit
|
Code/GraphMol/Wrap/MolOps.cpp
|
C++
|
bsd-3-clause
| 79,121
|
/**
* The OWASP CSRFGuard Project, BSD License
* Eric Sheridan (eric.sheridan@owasp.org), Copyright (c) 2011
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of OWASP nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function() {
/** string utility functions * */
String.prototype.startsWith = function(prefix) {
return this.indexOf(prefix) === 0;
}
String.prototype.endsWith = function(suffix) {
return this.match(suffix+"$") == suffix;
};
/** hook using standards based prototype * */
function hijackStandard() {
XMLHttpRequest.prototype._open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
this.url = url;
this._open.apply(this, arguments);
}
XMLHttpRequest.prototype._send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(data) {
if(this.onsend != null) {
this.onsend.apply(this, arguments);
}
this._send.apply(this, arguments);
}
}
/** ie does not properly support prototype - wrap completely * */
function hijackExplorer() {
var _XMLHttpRequest = window.XMLHttpRequest;
function alloc_XMLHttpRequest() {
this.base = _XMLHttpRequest ? new _XMLHttpRequest : new window.ActiveXObject("Microsoft.XMLHTTP");
}
function init_XMLHttpRequest() {
return new alloc_XMLHttpRequest;
}
init_XMLHttpRequest.prototype = alloc_XMLHttpRequest.prototype;
/** constants * */
init_XMLHttpRequest.UNSENT = 0;
init_XMLHttpRequest.OPENED = 1;
init_XMLHttpRequest.HEADERS_RECEIVED = 2;
init_XMLHttpRequest.LOADING = 3;
init_XMLHttpRequest.DONE = 4;
/** properties * */
init_XMLHttpRequest.prototype.status = 0;
init_XMLHttpRequest.prototype.statusText = "";
init_XMLHttpRequest.prototype.readyState = init_XMLHttpRequest.UNSENT;
init_XMLHttpRequest.prototype.responseText = "";
init_XMLHttpRequest.prototype.responseXML = null;
init_XMLHttpRequest.prototype.onsend = null;
init_XMLHttpRequest.url = null;
init_XMLHttpRequest.onreadystatechange = null;
/** methods * */
init_XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
var self = this;
this.url = url;
this.base.open(method, url, async, user, pass);
this.base.onreadystatechange = function() {
try { self.status = self.base.status; } catch (e) { }
try { self.statusText = self.base.statusText; } catch (e) { }
try { self.readyState = self.base.readyState; } catch (e) { }
try { self.responseText = self.base.responseText; } catch(e) { }
try { self.responseXML = self.base.responseXML; } catch(e) { }
if(self.onreadystatechange != null) {
self.onreadystatechange.apply(this, arguments);
}
}
}
init_XMLHttpRequest.prototype.send = function(data) {
if(this.onsend != null) {
this.onsend.apply(this, arguments);
}
this.base.send(data);
}
init_XMLHttpRequest.prototype.abort = function() {
this.base.abort();
}
init_XMLHttpRequest.prototype.getAllResponseHeaders = function() {
return this.base.getAllResponseHeaders();
}
init_XMLHttpRequest.prototype.getResponseHeader = function(name) {
return this.base.getResponseHeader(name);
}
init_XMLHttpRequest.prototype.setRequestHeader = function(name, value) {
return this.base.setRequestHeader(name, value);
}
/** hook * */
window.XMLHttpRequest = init_XMLHttpRequest;
}
/** check if valid domain based on domainStrict * */
function isValidDomain(current, target) {
var result = false;
/** check exact or subdomain match * */
if(current == target) {
result = true;
} else if(%DOMAIN_STRICT% == false) {
if(target.charAt(0) == '.') {
result = current.endsWith(target);
} else {
result = current.endsWith('.' + target);
}
}
return result;
}
/** determine if uri/url points to valid domain * */
function isValidUrl(src) {
var result = false;
/** parse out domain to make sure it points to our own * */
if(src.substring(0, 7) == "http://" || src.substring(0, 8) == "https://") {
var token = "://";
var index = src.indexOf(token);
var part = src.substring(index + token.length);
var domain = "";
/** parse up to end, first slash, or anchor * */
for(i=0; i<part.length; i++) {
var character = part.charAt(i);
if(character == '/' || character == ':' || character == '#') {
break;
} else {
domain += character;
}
}
result = isValidDomain(document.domain, domain);
/** explicitly skip anchors * */
} else if(src.charAt(0) == '#') {
result = false;
/** ensure it is a local resource without a protocol * */
} else if(!src.startsWith("//") && (src.charAt(0) == '/' || src.indexOf(':') == -1)) {
result = true;
}
return result;
}
/** parse uri from url * */
function parseUri(url) {
var uri = "";
var token = "://";
var index = url.indexOf(token);
var part = "";
/**
* ensure to skip protocol and prepend context path for non-qualified
* resources (ex: "protect.html" vs
* "/Owasp.CsrfGuard.Test/protect.html").
*/
if(index > 0) {
part = url.substring(index + token.length);
} else if(url.charAt(0) != '/') {
part = "%CONTEXT_PATH%/" + url;
} else {
part = url;
}
/** parse up to end or query string * */
var uriContext = (index == -1);
for(var i=0; i<part.length; i++) {
var character = part.charAt(i);
if(character == '/') {
uriContext = true;
} else if(uriContext == true && (character == '?' || character == '#')) {
uriContext = false;
break;
}
if(uriContext == true) {
uri += character;
}
}
return uri;
}
/** inject tokens as hidden fields into forms * */
function injectTokenForm(form, tokenName, tokenValue, pageTokens) {
var action = form.getAttribute("action");
if(action != null && isValidUrl(action)) {
var uri = parseUri(action);
var hidden = document.createElement("input");
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", tokenName);
hidden.setAttribute("value", (pageTokens[uri] != null ? pageTokens[uri] : tokenValue));
form.appendChild(hidden);
}
}
/** inject tokens as query string parameters into url * */
function injectTokenAttribute(element, attr, tokenName, tokenValue, pageTokens) {
var location = element.getAttribute(attr);
if(location != null && isValidUrl(location)) {
var uri = parseUri(location);
var value = (pageTokens[uri] != null ? pageTokens[uri] : tokenValue);
// alert("injectTokenAttribute: location=" + location + " uri=" +
// uri + " value=" + value);
if(location.indexOf('?') != -1) {
location = location + '&' + tokenName + '=' + value;
} else {
location = location + '?' + tokenName + '=' + value;
}
try {
element.setAttribute(attr, location);
} catch (e) {
// attempted to set/update unsupported attribute
}
}
}
/** inject csrf prevention tokens throughout dom * */
function injectTokens(tokenName, tokenValue, pageTokens) {
/** iterate over all elements and injection token * */
var all = document.all ? document.all : document.getElementsByTagName('*');
var len = all.length;
for(var i=0; i<len; i++) {
var element = all[i];
/** inject into form * */
if(element.tagName.toLowerCase() == "form") {
if(%INJECT_FORMS% == true) {
injectTokenForm(element, tokenName, tokenValue, pageTokens);
}
/** inject into attribute * */
} else if(%INJECT_ATTRIBUTES% == true) {
injectTokenAttribute(element, "src", tokenName, tokenValue, pageTokens);
injectTokenAttribute(element, "href", tokenName, tokenValue, pageTokens);
}
}
}
/** obtain array of page specific tokens * */
function requestPageTokens() {
var xhr = new XMLHttpRequest();
var pageTokens = {};
xhr.open("POST", "%SERVLET_PATH%", false);
xhr.send(null);
var text = xhr.responseText;
// alert("master: %TOKEN_VALUE%");
// alert("requestPageTokens: " + text);
var name = "";
var value = "";
var nameContext = true;
for(var i=0; i<text.length; i++) {
var character = text.charAt(i);
if(character == ':') {
nameContext = false;
} else if(character != ',') {
if(nameContext == true) {
name += character;
} else {
value += character;
}
}
if(character == ',' || (i + 1) >= text.length) {
pageTokens[name] = value;
name = "";
value = "";
nameContext = true;
}
}
return pageTokens;
}
/** utility method to register window.onload * */
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != "function") {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
/**
* Only inject the tokens if the JavaScript was referenced from HTML that
* was served by us. Otherwise, the code was referenced from malicious HTML
* which may be trying to steal tokens using JavaScript hijacking
* techniques.
*/
if(isValidDomain(document.domain, "%DOMAIN_ORIGIN%")) {
/** optionally include Ajax support * */
if(%INJECT_XHR% == true) {
if(navigator.appName == "Microsoft Internet Explorer") {
hijackExplorer();
} else {
hijackStandard();
}
XMLHttpRequest.prototype.onsend = function(data) {
if(isValidUrl(this.url)) {
this.setRequestHeader("X-Requested-With", "%X_REQUESTED_WITH%")
this.setRequestHeader("%TOKEN_NAME%", "%TOKEN_VALUE%");
}
};
}
/** update nodes in DOM after load * */
addLoadEvent(function() {
injectTokens("%TOKEN_NAME%", "%TOKEN_VALUE%", requestPageTokens());
});
}
})();
|
NCIP/common-security-module
|
software/upt/webapp/public_html/WEB-INF/Owasp.CsrfGuard.js
|
JavaScript
|
bsd-3-clause
| 11,536
|
/*
* Copyright (c) 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* Portions copyright (c) 1999, 2000
* Intel Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
*
* This product includes software developed by the University of
* California, Berkeley, Intel Corporation, and its contributors.
*
* 4. Neither the name of University, Intel Corporation, or their respective
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS, INTEL CORPORATION AND
* CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS,
* INTEL CORPORATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/*++
Module Name:
wcscat.c
Abstract:
Wide char string concatenation
Revision History
--*/
#include <wchar.h>
wchar_t *
wcscat(s, append)
register wchar_t *s;
register const wchar_t *append;
{
wchar_t *save = s;
for (; *s; ++s);
while (*s++ = *append++);
return(save);
}
|
kontais/EFI-MIPS
|
ToolKit/lib/libc/wchar/wcscat.c
|
C
|
bsd-3-clause
| 2,321
|
#ifndef NT2_CORE_INCLUDE_FUNCTIONS_SCALAR_EXPAND_HPP_INCLUDED
#define NT2_CORE_INCLUDE_FUNCTIONS_SCALAR_EXPAND_HPP_INCLUDED
#include <nt2/core/functions/expand.hpp>
#include <nt2/core/functions/scalar/expand.hpp>
#endif
|
hainm/pythran
|
third_party/nt2/core/include/functions/scalar/expand.hpp
|
C++
|
bsd-3-clause
| 222
|
#include <csolve.h>
#include <stdlib.h>
struct s {
int x;
char * ARRAY y;
};
struct t {
char * ARRAY one;
char * ARRAY two;
short z;
};
void register_cb(void * VAR(K) s,
void * VAR(L) t,
void (* START VALIDPTR cb)(void * VAR(K), void * VAR(L)))
{
cb(s,t);
}
extern void process_s(struct s *s, struct t *t) OKEXTERN;
void main()
{
struct s s1;
struct t t1;
register_cb(&s1, &t1, process_s);
}
|
ucsd-progsys/csolve
|
tests/postests/polystore/poly_call3.c
|
C
|
bsd-3-clause
| 436
|
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\RuleActionSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="rule-action-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'action') ?>
<?= $form->field($model, 'value') ?>
<?= $form->field($model, 'rule_id') ?>
<?= $form->field($model, 'weight') ?>
<?php // echo $form->field($model, 'created_at') ?>
<?php // echo $form->field($model, 'updated_at') ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton(Yii::t('app', 'Reset'), ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
|
hvos234/raspberrypi.home.website
|
views/rule-action/_search.php
|
PHP
|
bsd-3-clause
| 906
|
/*
* Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef SVGFEMorphologyElement_h
#define SVGFEMorphologyElement_h
#include "core/platform/graphics/filters/FEMorphology.h"
#include "core/svg/SVGAnimatedEnumeration.h"
#include "core/svg/SVGAnimatedNumber.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
namespace WebCore {
template<>
struct SVGPropertyTraits<MorphologyOperatorType> {
static unsigned highestEnumValue() { return FEMORPHOLOGY_OPERATOR_DILATE; }
static String toString(MorphologyOperatorType type)
{
switch (type) {
case FEMORPHOLOGY_OPERATOR_UNKNOWN:
return emptyString();
case FEMORPHOLOGY_OPERATOR_ERODE:
return "erode";
case FEMORPHOLOGY_OPERATOR_DILATE:
return "dilate";
}
ASSERT_NOT_REACHED();
return emptyString();
}
static MorphologyOperatorType fromString(const String& value)
{
if (value == "erode")
return FEMORPHOLOGY_OPERATOR_ERODE;
if (value == "dilate")
return FEMORPHOLOGY_OPERATOR_DILATE;
return FEMORPHOLOGY_OPERATOR_UNKNOWN;
}
};
class SVGFEMorphologyElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
static PassRefPtr<SVGFEMorphologyElement> create(const QualifiedName&, Document*);
void setRadius(float radiusX, float radiusY);
private:
SVGFEMorphologyElement(const QualifiedName&, Document*);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&);
virtual void svgAttributeChanged(const QualifiedName&);
virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
static const AtomicString& radiusXIdentifier();
static const AtomicString& radiusYIdentifier();
BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFEMorphologyElement)
DECLARE_ANIMATED_STRING(In1, in1)
DECLARE_ANIMATED_ENUMERATION(_operator, _operator, MorphologyOperatorType)
DECLARE_ANIMATED_NUMBER(RadiusX, radiusX)
DECLARE_ANIMATED_NUMBER(RadiusY, radiusY)
END_DECLARE_ANIMATED_PROPERTIES
};
} // namespace WebCore
#endif
|
espadrine/opera
|
chromium/src/third_party/WebKit/Source/core/svg/SVGFEMorphologyElement.h
|
C
|
bsd-3-clause
| 3,054
|
# -*- coding: utf-8 -*-
import collections
import itertools
import json
import os
import posixpath
import re
import time
from operator import attrgetter
from datetime import datetime
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.files.storage import default_storage as storage
from django.db import models, transaction
from django.dispatch import receiver
from django.db.models import Max, Q, signals as dbsignals
from django.utils.translation import trans_real, ugettext_lazy as _
import caching.base as caching
import commonware.log
from django_extensions.db.fields.json import JSONField
from django_statsd.clients import statsd
from jinja2.filters import do_dictsort
from olympia import amo
from olympia.amo.models import (
SlugField, OnChangeMixin, ModelBase, ManagerBase, manual_order)
from olympia.access import acl
from olympia.addons.utils import (
get_creatured_ids, get_featured_ids, generate_addon_guid)
from olympia.amo import helpers
from olympia.amo.decorators import use_master, write
from olympia.amo.utils import (
attach_trans_dict, cache_ns_key, chunked,
no_translation, send_mail, slugify, sorted_groupby, timer, to_language,
urlparams, find_language, AMOJSONEncoder)
from olympia.amo.urlresolvers import get_outgoing_url, reverse
from olympia.constants.categories import CATEGORIES, CATEGORIES_BY_ID
from olympia.files.models import File
from olympia.files.utils import (
extract_translations, resolve_i18n_message, parse_addon)
from olympia.reviews.models import Review
from olympia.tags.models import Tag
from olympia.translations.fields import (
LinkifiedField, PurifiedField, save_signal, TranslatedField, Translation)
from olympia.users.models import UserForeignKey, UserProfile
from olympia.versions.compare import version_int
from olympia.versions.models import inherit_nomination, Version
from . import signals
log = commonware.log.getLogger('z.addons')
def clean_slug(instance, slug_field='slug'):
"""Cleans a model instance slug.
This strives to be as generic as possible as it's used by Addons
and Collections, and maybe more in the future.
"""
slug = getattr(instance, slug_field, None) or instance.name
if not slug:
# Initialize the slug with what we have available: a name translation,
# or the id of the instance, or in last resort the model name.
translations = Translation.objects.filter(id=instance.name_id)
if translations.exists():
slug = translations[0]
elif instance.id:
slug = str(instance.id)
else:
slug = instance.__class__.__name__
max_length = instance._meta.get_field_by_name(slug_field)[0].max_length
slug = slugify(slug)[:max_length]
if DeniedSlug.blocked(slug):
slug = slug[:max_length - 1] + '~'
# The following trick makes sure we are using a manager that returns
# all the objects, as otherwise we could have a slug clash on our hands.
# Eg with the "Addon.objects" manager, which doesn't list deleted addons,
# we could have a "clean" slug which is in fact already assigned to an
# already existing (deleted) addon. Also, make sure we use the base class.
manager = models.Manager()
manager.model = instance._meta.proxy_for_model or instance.__class__
qs = manager.values_list(slug_field, flat=True) # Get list of all slugs.
if instance.id:
qs = qs.exclude(pk=instance.id) # Can't clash with itself.
# We first need to make sure there's a clash, before trying to find a
# suffix that is available. Eg, if there's a "foo-bar" slug, "foo" is still
# available.
clash = qs.filter(**{slug_field: slug})
if clash.exists():
# Leave space for 99 clashes.
slug = slugify(slug)[:max_length - 2]
# There is a clash, so find a suffix that will make this slug unique.
lookup = {'%s__startswith' % slug_field: slug}
clashes = qs.filter(**lookup)
# Try numbers between 1 and the number of clashes + 1 (+ 1 because we
# start the range at 1, not 0):
# if we have two clashes "foo1" and "foo2", we need to try "foox"
# for x between 1 and 3 to be absolutely sure to find an available one.
for idx in range(1, len(clashes) + 2):
new = ('%s%s' % (slug, idx))[:max_length]
if new not in clashes:
slug = new
break
else:
# This could happen. The current implementation (using
# ``[:max_length -3]``) only works for the first 100 clashes in the
# worst case (if the slug is equal to or longuer than
# ``max_length - 3`` chars).
# After that, {verylongslug}-100 will be trimmed down to
# {verylongslug}-10, which is already assigned, but it's the last
# solution tested.
raise RuntimeError
setattr(instance, slug_field, slug)
return instance
class AddonQuerySet(caching.CachingQuerySet):
def id_or_slug(self, val):
"""Get add-ons by id or slug."""
if isinstance(val, basestring) and not val.isdigit():
return self.filter(slug=val)
return self.filter(id=val)
def enabled(self):
"""Get add-ons that haven't been disabled by their developer(s)."""
return self.filter(disabled_by_user=False)
def public(self):
"""Get public add-ons only"""
return self.filter(self.valid_q([amo.STATUS_PUBLIC]))
def valid(self):
"""Get valid, enabled add-ons only"""
return self.filter(self.valid_q(amo.VALID_ADDON_STATUSES))
def valid_and_disabled_and_pending(self):
"""
Get valid, pending, enabled and disabled add-ons.
Used to allow pending theme pages to still be viewed.
"""
statuses = (list(amo.VALID_ADDON_STATUSES) +
[amo.STATUS_DISABLED, amo.STATUS_PENDING])
return (self.filter(Q(status__in=statuses) | Q(disabled_by_user=True))
.exclude(type=amo.ADDON_EXTENSION,
_current_version__isnull=True))
def featured(self, app, lang=None, type=None):
"""
Filter for all featured add-ons for an application in all locales.
"""
ids = get_featured_ids(app, lang, type)
return manual_order(self.listed(app), ids, 'addons.id')
def listed(self, app, *status):
"""
Return add-ons that support a given ``app``, have a version with a file
matching ``status`` and are not disabled.
"""
if len(status) == 0:
status = [amo.STATUS_PUBLIC]
return self.filter(self.valid_q(status), appsupport__app=app.id)
def valid_q(self, status=None, prefix=''):
"""
Return a Q object that selects a valid Addon with the given statuses.
An add-on is valid if not disabled and has a current version.
``prefix`` can be used if you're not working with Addon directly and
need to hop across a join, e.g. ``prefix='addon__'`` in
CollectionAddon.
"""
if not status:
status = [amo.STATUS_PUBLIC]
def q(*args, **kw):
if prefix:
kw = dict((prefix + k, v) for k, v in kw.items())
return Q(*args, **kw)
return q(q(_current_version__isnull=False),
disabled_by_user=False, status__in=status)
class AddonManager(ManagerBase):
def __init__(self, include_deleted=False):
# DO NOT change the default value of include_deleted unless you've read
# through the comment just above the Addon managers
# declaration/instantiation and understand the consequences.
ManagerBase.__init__(self)
self.include_deleted = include_deleted
def get_queryset(self):
qs = super(AddonManager, self).get_queryset()
qs = qs._clone(klass=AddonQuerySet)
if not self.include_deleted:
qs = qs.exclude(status=amo.STATUS_DELETED)
return qs.transform(Addon.transformer)
def id_or_slug(self, val):
"""Get add-ons by id or slug."""
return self.get_queryset().id_or_slug(val)
def enabled(self):
"""Get add-ons that haven't been disabled by their developer(s)."""
return self.get_queryset().enabled()
def public(self):
"""Get public add-ons only"""
return self.get_queryset().public()
def valid(self):
"""Get valid, enabled add-ons only"""
return self.get_queryset().valid()
def valid_and_disabled_and_pending(self):
"""
Get valid, pending, enabled and disabled add-ons.
Used to allow pending theme pages to still be viewed.
"""
return self.get_queryset().valid_and_disabled_and_pending()
def featured(self, app, lang=None, type=None):
"""
Filter for all featured add-ons for an application in all locales.
"""
return self.get_queryset().featured(app, lang=lang, type=type)
def listed(self, app, *status):
"""
Return add-ons that support a given ``app``, have a version with a file
matching ``status`` and are not disabled.
"""
return self.get_queryset().listed(app, *status)
class Addon(OnChangeMixin, ModelBase):
STATUS_CHOICES = amo.STATUS_CHOICES_ADDON
guid = models.CharField(max_length=255, unique=True, null=True)
slug = models.CharField(max_length=30, unique=True, null=True)
name = TranslatedField(default=None)
default_locale = models.CharField(max_length=10,
default=settings.LANGUAGE_CODE,
db_column='defaultlocale')
type = models.PositiveIntegerField(
choices=amo.ADDON_TYPE.items(), db_column='addontype_id', default=0)
status = models.PositiveIntegerField(
choices=STATUS_CHOICES.items(), db_index=True, default=0)
icon_type = models.CharField(max_length=25, blank=True,
db_column='icontype')
homepage = TranslatedField()
support_email = TranslatedField(db_column='supportemail')
support_url = TranslatedField(db_column='supporturl')
description = PurifiedField(short=False)
summary = LinkifiedField()
developer_comments = PurifiedField(db_column='developercomments')
eula = PurifiedField()
privacy_policy = PurifiedField(db_column='privacypolicy')
the_reason = PurifiedField()
the_future = PurifiedField()
average_rating = models.FloatField(max_length=255, default=0, null=True,
db_column='averagerating')
bayesian_rating = models.FloatField(default=0, db_index=True,
db_column='bayesianrating')
total_reviews = models.PositiveIntegerField(default=0,
db_column='totalreviews')
weekly_downloads = models.PositiveIntegerField(
default=0, db_column='weeklydownloads', db_index=True)
total_downloads = models.PositiveIntegerField(
default=0, db_column='totaldownloads')
hotness = models.FloatField(default=0, db_index=True)
average_daily_downloads = models.PositiveIntegerField(default=0)
average_daily_users = models.PositiveIntegerField(default=0)
last_updated = models.DateTimeField(
db_index=True, null=True,
help_text='Last time this add-on had a file/version update')
disabled_by_user = models.BooleanField(default=False, db_index=True,
db_column='inactive')
view_source = models.BooleanField(default=True, db_column='viewsource')
public_stats = models.BooleanField(default=False, db_column='publicstats')
prerelease = models.BooleanField(default=False)
admin_review = models.BooleanField(default=False, db_column='adminreview')
external_software = models.BooleanField(default=False,
db_column='externalsoftware')
dev_agreement = models.BooleanField(
default=False, help_text="Has the dev agreement been signed?")
auto_repackage = models.BooleanField(
default=True, help_text='Automatically upgrade jetpack add-on to a '
'new sdk version?')
target_locale = models.CharField(
max_length=255, db_index=True, blank=True, null=True,
help_text="For dictionaries and language packs")
locale_disambiguation = models.CharField(
max_length=255, blank=True, null=True,
help_text="For dictionaries and language packs")
wants_contributions = models.BooleanField(default=False)
paypal_id = models.CharField(max_length=255, blank=True)
charity = models.ForeignKey('Charity', null=True)
suggested_amount = models.DecimalField(
max_digits=9, decimal_places=2, blank=True,
null=True, help_text=_(u'Users have the option of contributing more '
'or less than this amount.'))
total_contributions = models.DecimalField(max_digits=9, decimal_places=2,
blank=True, null=True)
annoying = models.PositiveIntegerField(
choices=amo.CONTRIB_CHOICES, default=0,
help_text=_(u'Users will always be asked in the Add-ons'
u' Manager (Firefox 4 and above).'
u' Only applies to desktop.'))
enable_thankyou = models.BooleanField(
default=False, help_text='Should the thank you note be sent to '
'contributors?')
thankyou_note = TranslatedField()
authors = models.ManyToManyField('users.UserProfile', through='AddonUser',
related_name='addons')
categories = models.ManyToManyField('Category', through='AddonCategory')
dependencies = models.ManyToManyField('self', symmetrical=False,
through='AddonDependency',
related_name='addons')
_current_version = models.ForeignKey(Version, db_column='current_version',
related_name='+', null=True,
on_delete=models.SET_NULL)
whiteboard = models.TextField(blank=True)
is_experimental = models.BooleanField(default=False,
db_column='experimental')
# The order of those managers is very important:
# The first one discovered, if it has "use_for_related_fields = True"
# (which it has if it's inheriting from caching.base.CachingManager), will
# be used for relations like `version.addon`. We thus want one that is NOT
# filtered in any case, we don't want a 500 if the addon is not found
# (because it has the status amo.STATUS_DELETED for example).
# The CLASS of the first one discovered will also be used for "many to many
# relations" like `collection.addons`. In that case, we do want the
# filtered version by default, to make sure we're not displaying stuff by
# mistake. You thus want the CLASS of the first one to be filtered by
# default.
# We don't control the instantiation, but AddonManager sets include_deleted
# to False by default, so filtering is enabled by default. This is also why
# it's not repeated for 'objects' below.
unfiltered = AddonManager(include_deleted=True)
objects = AddonManager()
class Meta:
db_table = 'addons'
@staticmethod
def __new__(cls, *args, **kw):
try:
type_idx = Addon._meta._type_idx
except AttributeError:
type_idx = (idx for idx, f in enumerate(Addon._meta.fields)
if f.attname == 'type').next()
Addon._meta._type_idx = type_idx
return object.__new__(cls)
def __unicode__(self):
return u'%s: %s' % (self.id, self.name)
def __init__(self, *args, **kw):
super(Addon, self).__init__(*args, **kw)
if self.type == amo.ADDON_PERSONA:
self.STATUS_CHOICES = Persona.STATUS_CHOICES
def save(self, **kw):
self.clean_slug()
super(Addon, self).save(**kw)
@classmethod
def search_public(cls):
"""Legacy search method for public add-ons.
Note that typically, code using this method do a search in ES but then
will fetch the relevant objects from the database using Addon.objects,
so deleted addons won't be returned no matter what ES returns. See
amo.search.ES and amo.search.ObjectSearchResults for more details.
In new code, use elasticsearch-dsl instead.
"""
return cls.search().filter(
is_disabled=False,
status__in=amo.REVIEWED_STATUSES,
current_version__exists=True)
@use_master
def clean_slug(self, slug_field='slug'):
if self.status == amo.STATUS_DELETED:
return
clean_slug(self, slug_field)
def is_soft_deleteable(self):
return self.status or Version.unfiltered.filter(addon=self).exists()
@transaction.atomic
def delete(self, msg='', reason=''):
# To avoid a circular import.
from . import tasks
# Check for soft deletion path. Happens only if the addon status isn't
# 0 (STATUS_INCOMPLETE) with no versions.
soft_deletion = self.is_soft_deleteable()
if soft_deletion and self.status == amo.STATUS_DELETED:
# We're already done.
return
id = self.id
# Fetch previews before deleting the addon instance, so that we can
# pass the list of files to delete to the delete_preview_files task
# after the addon is deleted.
previews = list(Preview.objects.filter(addon__id=id)
.values_list('id', flat=True))
if soft_deletion:
# /!\ If we ever stop using soft deletion, and remove this code, we
# need to make sure that the logs created below aren't cascade
# deleted!
log.debug('Deleting add-on: %s' % self.id)
to = [settings.FLIGTAR]
user = amo.get_user()
# Don't localize email to admins, use 'en-US' always.
with no_translation():
# The types are lazy translated in apps/constants/base.py.
atype = amo.ADDON_TYPE.get(self.type).upper()
context = {
'atype': atype,
'authors': [u.email for u in self.authors.all()],
'adu': self.average_daily_users,
'guid': self.guid,
'id': self.id,
'msg': msg,
'reason': reason,
'name': self.name,
'slug': self.slug,
'total_downloads': self.total_downloads,
'url': helpers.absolutify(self.get_url_path()),
'user_str': ("%s, %s (%s)" % (user.display_name or
user.username, user.email,
user.id) if user else "Unknown"),
}
email_msg = u"""
The following %(atype)s was deleted.
%(atype)s: %(name)s
URL: %(url)s
DELETED BY: %(user_str)s
ID: %(id)s
GUID: %(guid)s
AUTHORS: %(authors)s
TOTAL DOWNLOADS: %(total_downloads)s
AVERAGE DAILY USERS: %(adu)s
NOTES: %(msg)s
REASON GIVEN BY USER FOR DELETION: %(reason)s
""" % context
log.debug('Sending delete email for %(atype)s %(id)s' % context)
subject = 'Deleting %(atype)s %(slug)s (%(id)d)' % context
# Update or NULL out various fields.
models.signals.pre_delete.send(sender=Addon, instance=self)
self._reviews.all().delete()
# The last parameter is needed to automagically create an AddonLog.
amo.log(amo.LOG.DELETE_ADDON, self.pk, unicode(self.guid), self)
self.update(status=amo.STATUS_DELETED, slug=None,
_current_version=None, modified=datetime.now())
models.signals.post_delete.send(sender=Addon, instance=self)
send_mail(subject, email_msg, recipient_list=to)
else:
# Real deletion path.
super(Addon, self).delete()
for preview in previews:
tasks.delete_preview_files.delay(preview)
return True
@classmethod
def initialize_addon_from_upload(cls, data, upload, channel):
fields = cls._meta.get_all_field_names()
guid = data.get('guid')
old_guid_addon = None
if guid: # It's an extension.
# Reclaim GUID from deleted add-on.
try:
old_guid_addon = Addon.unfiltered.get(guid=guid)
old_guid_addon.update(guid=None)
except ObjectDoesNotExist:
pass
generate_guid = (
not data.get('guid', None) and
data.get('is_webextension', False)
)
if generate_guid:
data['guid'] = guid = generate_addon_guid()
data = cls.resolve_webext_translations(data, upload)
addon = Addon(**dict((k, v) for k, v in data.items() if k in fields))
addon.status = amo.STATUS_NULL
locale_is_set = (addon.default_locale and
addon.default_locale in (
settings.AMO_LANGUAGES +
settings.HIDDEN_LANGUAGES) and
data.get('default_locale') == addon.default_locale)
if not locale_is_set:
addon.default_locale = to_language(trans_real.get_language())
addon.save()
if old_guid_addon:
old_guid_addon.update(guid='guid-reused-by-pk-{}'.format(addon.pk))
old_guid_addon.save()
return addon
@classmethod
def create_addon_from_upload_data(cls, data, upload, channel, user=None,
**kwargs):
addon = cls.initialize_addon_from_upload(data, upload, channel,
**kwargs)
AddonUser(addon=addon, user=user).save()
return addon
@classmethod
def from_upload(cls, upload, platforms, source=None,
channel=amo.RELEASE_CHANNEL_LISTED, parsed_data=None):
if not parsed_data:
parsed_data = parse_addon(upload)
addon = cls.initialize_addon_from_upload(parsed_data, upload, channel)
if upload.validation_timeout:
addon.update(admin_review=True)
Version.from_upload(upload, addon, platforms, source=source,
channel=channel)
amo.log(amo.LOG.CREATE_ADDON, addon)
log.debug('New addon %r from %r' % (addon, upload))
return addon
@classmethod
def resolve_webext_translations(cls, data, upload):
"""Resolve all possible translations from an add-on.
This returns a modified `data` dictionary accordingly with proper
translations filled in.
"""
default_locale = find_language(data.get('default_locale'))
if not data.get('is_webextension') or not default_locale:
# Don't change anything if we don't meet the requirements
return data
fields = ('name', 'homepage', 'summary')
messages = extract_translations(upload)
for field in fields:
data[field] = {
locale: resolve_i18n_message(
data[field],
locale=locale,
default_locale=default_locale,
messages=messages)
for locale in messages
}
return data
def get_url_path(self, more=False, add_prefix=True):
if not self.current_version:
return ''
# If more=True you get the link to the ajax'd middle chunk of the
# detail page.
view = 'addons.detail_more' if more else 'addons.detail'
return reverse(view, args=[self.slug], add_prefix=add_prefix)
def get_dev_url(self, action='edit', args=None, prefix_only=False):
args = args or []
prefix = 'devhub'
type_ = 'themes' if self.type == amo.ADDON_PERSONA else 'addons'
if not prefix_only:
prefix += '.%s' % type_
view_name = '{prefix}.{action}'.format(prefix=prefix,
action=action)
return reverse(view_name, args=[self.slug] + args)
def get_detail_url(self, action='detail', args=None):
if args is None:
args = []
return reverse('addons.%s' % action, args=[self.slug] + args)
def meet_the_dev_url(self):
return reverse('addons.meet', args=[self.slug])
@property
def reviews_url(self):
return helpers.url('addons.reviews.list', self.slug)
def get_ratings_url(self, action='list', args=None, add_prefix=True):
return reverse('ratings.themes.%s' % action,
args=[self.slug] + (args or []),
add_prefix=add_prefix)
@classmethod
def get_type_url(cls, type):
try:
type = amo.ADDON_SLUGS[type]
except KeyError:
return None
return reverse('browse.%s' % type)
def type_url(self):
"""The url for this add-on's type."""
return Addon.get_type_url(self.type)
def share_url(self):
return reverse('addons.share', args=[self.slug])
@amo.cached_property(writable=True)
def listed_authors(self):
return UserProfile.objects.filter(
addons=self,
addonuser__listed=True).order_by('addonuser__position')
@classmethod
def get_fallback(cls):
return cls._meta.get_field('default_locale')
@property
def reviews(self):
return Review.objects.filter(addon=self, reply_to=None)
def get_category(self, app_id):
categories = self.app_categories.get(amo.APP_IDS.get(app_id))
return categories[0] if categories else None
def language_ascii(self):
lang = trans_real.to_language(self.default_locale)
return settings.LANGUAGES.get(lang)
@property
def valid_file_statuses(self):
if self.status == amo.STATUS_PUBLIC:
return [amo.STATUS_PUBLIC]
return amo.VALID_FILE_STATUSES
def find_latest_public_listed_version(self):
"""Retrieve the latest public listed version of an addon.
If the add-on is not public, it can return a listed version awaiting
review (since non-public add-ons should not have public versions)."""
if self.type == amo.ADDON_PERSONA:
return
try:
statuses = self.valid_file_statuses
status_list = ','.join(map(str, statuses))
fltr = {
'channel': amo.RELEASE_CHANNEL_LISTED,
'files__status__in': statuses
}
return self.versions.no_cache().filter(**fltr).extra(
where=["""
NOT EXISTS (
SELECT 1 FROM files AS f2
WHERE f2.version_id = versions.id AND
f2.status NOT IN (%s))
""" % status_list])[0]
except (IndexError, Version.DoesNotExist):
return None
def find_latest_version(self, channel, ignore=None):
"""Retrieve the latest non-disabled version of an add-on for the
specified channel. If channel is None either channel is returned.
Accepts an optional ignore argument to ignore a specific version."""
# If the add-on is deleted or hasn't been saved yet, it should not
# have a latest version.
if not self.id or self.status == amo.STATUS_DELETED:
return None
# We can't use .exclude(files__status=STATUS_DISABLED) because this
# excludes a version if any of the files are the disabled and there may
# be files we do want to include. Having a single beta file /does/
# mean we want the whole version disqualified though.
statuses_without_disabled = (
set(amo.STATUS_CHOICES_FILE.keys()) -
{amo.STATUS_DISABLED, amo.STATUS_BETA})
try:
latest_qs = (
Version.objects.filter(addon=self)
.exclude(files__status=amo.STATUS_BETA)
.filter(files__status__in=statuses_without_disabled))
if ignore is not None:
latest_qs = latest_qs.exclude(pk=ignore.pk)
if channel is not None:
latest_qs = latest_qs.filter(channel=channel)
latest = latest_qs.latest()
latest.addon = self
except Version.DoesNotExist:
latest = None
return latest
def find_latest_version_including_rejected(self, channel):
"""Similar to latest_version but includes rejected versions. Used so
we correctly attach review content to the last version reviewed. If
channel is None either channel is returned."""
try:
latest_qs = self.versions.exclude(files__status=amo.STATUS_BETA)
if channel is not None:
latest_qs = latest_qs.filter(channel=channel)
latest = latest_qs.latest()
except Version.DoesNotExist:
latest = None
return latest
@write
def update_version(self, ignore=None, _signal=True):
"""
Update the current_version field on this add-on if necessary.
Returns True if we updated the current_version field.
The optional ``ignore`` parameter, if present, is a a version
to not consider as part of the update, since it may be in the
process of being deleted.
Pass ``_signal=False`` if you want to no signals fired at all.
"""
if self.is_persona():
# Themes should only have a single version. So, if there is not
# current version set, we just need to copy over the latest version
# to current_version and we should never have to set it again.
if not self._current_version:
latest_version = self.find_latest_version(None)
if latest_version:
self.update(_current_version=latest_version, _signal=False)
return True
return False
new_current_version = self.find_latest_public_listed_version()
updated = {}
send_signal = False
if self._current_version != new_current_version:
updated['_current_version'] = new_current_version
send_signal = True
# update_version can be called by a post_delete signal (such
# as File's) when deleting a version. If so, we should avoid putting
# that version-being-deleted in any fields.
if ignore is not None:
updated = {k: v for k, v in updated.iteritems() if v != ignore}
if updated:
diff = [self._current_version, new_current_version]
# Pass along _signal to the .update() to prevent it from firing
# signals if we don't want them.
updated['_signal'] = _signal
try:
self.update(**updated)
if send_signal and _signal:
signals.version_changed.send(sender=self)
log.info(u'Version changed from current: %s to %s '
u'for addon %s'
% tuple(diff + [self]))
except Exception, e:
log.error(u'Could not save version changes current: %s to %s '
u'for addon %s (%s)' %
tuple(diff + [self, e]))
return bool(updated)
def increment_theme_version_number(self):
"""Increment theme version number by 1."""
latest_version = self.find_latest_version(None)
version = latest_version or self.current_version
version.version = str(float(version.version) + 1)
# Set the current version.
self.update(_current_version=version.save())
def invalidate_d2c_versions(self):
"""Invalidates the cache of compatible versions.
Call this when there is an event that may change what compatible
versions are returned so they are recalculated.
"""
key = cache_ns_key('d2c-versions:%s' % self.id, increment=True)
log.info('Incrementing d2c-versions namespace for add-on [%s]: %s' % (
self.id, key))
@property
def current_version(self):
"""Return the latest public listed version of an addon
If the add-on is not public, it can return a listed version awaiting
review (since non-public add-ons should not have public versions).
If the add-on has not been created yet or is deleted, it returns None.
"""
if not self.id or self.status == amo.STATUS_DELETED:
return None
try:
return self._current_version
except ObjectDoesNotExist:
pass
return None
@amo.cached_property(writable=True)
def latest_unlisted_version(self):
"""Shortcut property for Addon.find_latest_version(
channel=RELEASE_CHANNEL_UNLISTED)."""
return self.find_latest_version(channel=amo.RELEASE_CHANNEL_UNLISTED)
@amo.cached_property
def binary(self):
"""Returns if the current version has binary files."""
version = self.current_version
if version:
return version.files.filter(binary=True).exists()
return False
@amo.cached_property
def binary_components(self):
"""Returns if the current version has files with binary_components."""
version = self.current_version
if version:
return version.files.filter(binary_components=True).exists()
return False
def get_icon_dir(self):
return os.path.join(helpers.user_media_path('addon_icons'),
'%s' % (self.id / 1000))
def get_icon_url(self, size, use_default=True):
"""
Returns the addon's icon url according to icon_type.
If it's a persona, it will return the icon_url of the associated
Persona instance.
If it's a theme and there is no icon set, it will return the default
theme icon.
If it's something else, it will return the default add-on icon, unless
use_default is False, in which case it will return None.
"""
icon_type_split = []
if self.icon_type:
icon_type_split = self.icon_type.split('/')
# Get the closest allowed size without going over
if (size not in amo.ADDON_ICON_SIZES and
size >= amo.ADDON_ICON_SIZES[0]):
size = [s for s in amo.ADDON_ICON_SIZES if s < size][-1]
elif size < amo.ADDON_ICON_SIZES[0]:
size = amo.ADDON_ICON_SIZES[0]
# Figure out what to return for an image URL
if self.type == amo.ADDON_PERSONA:
return self.persona.icon_url
if not self.icon_type:
if self.type == amo.ADDON_THEME:
icon = amo.ADDON_ICONS[amo.ADDON_THEME]
return "%simg/icons/%s" % (settings.STATIC_URL, icon)
else:
if not use_default:
return None
return self.get_default_icon_url(size)
elif icon_type_split[0] == 'icon':
return '{0}img/addon-icons/{1}-{2}.png'.format(
settings.STATIC_URL,
icon_type_split[1],
size
)
else:
# [1] is the whole ID, [2] is the directory
split_id = re.match(r'((\d*?)\d{1,3})$', str(self.id))
modified = int(time.mktime(self.modified.timetuple()))
path = '/'.join([
split_id.group(2) or '0',
'{0}-{1}.png?modified={2}'.format(self.id, size, modified),
])
return helpers.user_media_url('addon_icons') + path
def get_default_icon_url(self, size):
return '{0}img/addon-icons/{1}-{2}.png'.format(
settings.STATIC_URL, 'default', size
)
@write
def update_status(self, ignore_version=None):
self.reload()
if (self.status in [amo.STATUS_NULL, amo.STATUS_DELETED] or
self.is_disabled or self.is_persona()):
self.update_version(ignore=ignore_version)
return
versions = self.versions.filter(channel=amo.RELEASE_CHANNEL_LISTED)
status = None
if not versions.exists():
status = amo.STATUS_NULL
reason = 'no listed versions'
elif not versions.filter(
files__status__in=amo.VALID_FILE_STATUSES).exists():
status = amo.STATUS_NULL
reason = 'no listed version with valid file'
elif (self.status == amo.STATUS_PUBLIC and
not versions.filter(files__status=amo.STATUS_PUBLIC).exists()):
if versions.filter(
files__status=amo.STATUS_AWAITING_REVIEW).exists():
status = amo.STATUS_NOMINATED
reason = 'only an unreviewed file'
else:
status = amo.STATUS_NULL
reason = 'no reviewed files'
elif self.status == amo.STATUS_PUBLIC:
latest_version = self.find_latest_version(
channel=amo.RELEASE_CHANNEL_LISTED)
if (latest_version and latest_version.has_files and
(latest_version.all_files[0].status ==
amo.STATUS_AWAITING_REVIEW)):
# Addon is public, but its latest file is not (it's the case on
# a new file upload). So, call update, to trigger watch_status,
# which takes care of setting nomination time when needed.
status = self.status
reason = 'triggering watch_status'
if status is not None:
log.info('Changing add-on status [%s]: %s => %s (%s).'
% (self.id, self.status, status, reason))
self.update(status=status)
amo.log(amo.LOG.CHANGE_STATUS, self.get_status_display(), self)
self.update_version(ignore=ignore_version)
@staticmethod
def attach_related_versions(addons, addon_dict=None):
if addon_dict is None:
addon_dict = dict((a.id, a) for a in addons)
all_ids = set(filter(None, (a._current_version_id for a in addons)))
versions = list(Version.objects.filter(id__in=all_ids).order_by())
for version in versions:
try:
addon = addon_dict[version.addon_id]
except KeyError:
log.debug('Version %s has an invalid add-on id.' % version.id)
continue
if addon._current_version_id == version.id:
addon._current_version = version
version.addon = addon
@staticmethod
def attach_listed_authors(addons, addon_dict=None):
if addon_dict is None:
addon_dict = dict((a.id, a) for a in addons)
qs = (UserProfile.objects.no_cache()
.filter(addons__in=addons, addonuser__listed=True)
.extra(select={'addon_id': 'addons_users.addon_id',
'position': 'addons_users.position'}))
qs = sorted(qs, key=lambda u: (u.addon_id, u.position))
for addon_id, users in itertools.groupby(qs, key=lambda u: u.addon_id):
addon_dict[addon_id].listed_authors = list(users)
# FIXME: set listed_authors to empty list on addons without listed
# authors.
@staticmethod
def attach_previews(addons, addon_dict=None, no_transforms=False):
if addon_dict is None:
addon_dict = dict((a.id, a) for a in addons)
qs = Preview.objects.filter(addon__in=addons,
position__gte=0).order_by()
if no_transforms:
qs = qs.no_transforms()
qs = sorted(qs, key=lambda x: (x.addon_id, x.position, x.created))
for addon, previews in itertools.groupby(qs, lambda x: x.addon_id):
addon_dict[addon].all_previews = list(previews)
# FIXME: set all_previews to empty list on addons without previews.
@staticmethod
def attach_static_categories(addons, addon_dict=None):
if addon_dict is None:
addon_dict = dict((a.id, a) for a in addons)
qs = AddonCategory.objects.values_list(
'addon', 'category').filter(addon__in=addon_dict)
qs = sorted(qs, key=lambda x: (x[0], x[1]))
for addon_id, cats_iter in itertools.groupby(qs, key=lambda x: x[0]):
# The second value of each tuple in cats_iter are the category ids
# we want.
addon_dict[addon_id].category_ids = [c[1] for c in cats_iter]
addon_dict[addon_id].all_categories = [
CATEGORIES_BY_ID[cat_id] for cat_id
in addon_dict[addon_id].category_ids
if cat_id in CATEGORIES_BY_ID]
@staticmethod
@timer
def transformer(addons):
if not addons:
return
addon_dict = {a.id: a for a in addons}
# Attach categories. This needs to be done before separating addons
# from personas, because Personas need categories for the theme_data
# JSON dump, rest of the add-ons need the first category to be
# displayed in detail page / API.
Addon.attach_static_categories(addons, addon_dict=addon_dict)
personas = [a for a in addons if a.type == amo.ADDON_PERSONA]
addons = [a for a in addons if a.type != amo.ADDON_PERSONA]
# Set _current_version.
Addon.attach_related_versions(addons, addon_dict=addon_dict)
# Attach listed authors.
Addon.attach_listed_authors(addons, addon_dict=addon_dict)
# Persona-specific stuff
for persona in Persona.objects.no_cache().filter(addon__in=personas):
addon = addon_dict[persona.addon_id]
addon.persona = persona
addon.weekly_downloads = persona.popularity
# Attach previews.
Addon.attach_previews(addons, addon_dict=addon_dict)
return addon_dict
@property
def show_beta(self):
return self.status == amo.STATUS_PUBLIC and self.current_beta_version
def show_adu(self):
return self.type != amo.ADDON_SEARCH
@amo.cached_property(writable=True)
def current_beta_version(self):
"""Retrieves the latest version of an addon, in the beta channel."""
versions = self.versions.filter(files__status=amo.STATUS_BETA)[:1]
if versions:
return versions[0]
@property
def icon_url(self):
return self.get_icon_url(32)
def authors_other_addons(self, app=None):
"""
Return other addons by the author(s) of this addon,
optionally takes an app.
"""
if app:
qs = Addon.objects.listed(app)
else:
qs = Addon.objects.valid()
return (qs.exclude(id=self.id)
.filter(addonuser__listed=True,
authors__in=self.listed_authors)
.distinct())
@property
def contribution_url(self, lang=settings.LANGUAGE_CODE,
app=settings.DEFAULT_APP):
return reverse('addons.contribute', args=[self.slug])
@property
def thumbnail_url(self):
"""
Returns the addon's thumbnail url or a default.
"""
try:
preview = self.all_previews[0]
return preview.thumbnail_url
except IndexError:
return settings.STATIC_URL + '/img/icons/no-preview.png'
def can_request_review(self):
"""Return whether an add-on can request a review or not."""
if (self.is_disabled or
self.status in (amo.STATUS_PUBLIC,
amo.STATUS_NOMINATED,
amo.STATUS_DELETED)):
return False
latest_version = self.find_latest_version_including_rejected(
channel=amo.RELEASE_CHANNEL_LISTED)
return latest_version is not None and latest_version.files.exists()
def is_persona(self):
return self.type == amo.ADDON_PERSONA
@property
def is_disabled(self):
"""True if this Addon is disabled.
It could be disabled by an admin or disabled by the developer
"""
return self.status == amo.STATUS_DISABLED or self.disabled_by_user
@property
def is_deleted(self):
return self.status == amo.STATUS_DELETED
def is_unreviewed(self):
return self.status in amo.UNREVIEWED_ADDON_STATUSES
def is_public(self):
return self.status == amo.STATUS_PUBLIC and not self.disabled_by_user
def has_complete_metadata(self, has_listed_versions=None):
"""See get_required_metadata for has_listed_versions details."""
return all(self.get_required_metadata(
has_listed_versions=has_listed_versions))
def get_required_metadata(self, has_listed_versions=None):
"""If has_listed_versions is not specified this method will return the
current (required) metadata (truthy values if present) for this Addon.
If has_listed_versions is specified then the method will act as if
Addon.has_listed_versions() returns that value. Used to predict if the
addon will require extra metadata before a version is created."""
if has_listed_versions is None:
has_listed_versions = self.has_listed_versions()
if not has_listed_versions:
# Add-ons with only unlisted versions have no required metadata.
return []
latest_version = self.find_latest_version_including_rejected(
channel=amo.RELEASE_CHANNEL_LISTED)
return [
self.all_categories,
self.summary,
(latest_version and latest_version.license),
]
def should_redirect_to_submit_flow(self):
return (
self.status == amo.STATUS_NULL and
not self.has_complete_metadata() and
self.find_latest_version(channel=amo.RELEASE_CHANNEL_LISTED))
def is_pending(self):
return self.status == amo.STATUS_PENDING
def is_rejected(self):
return self.status == amo.STATUS_REJECTED
def can_be_deleted(self):
return not self.is_deleted
def has_listed_versions(self):
return self.versions.filter(
channel=amo.RELEASE_CHANNEL_LISTED).exists()
def has_unlisted_versions(self):
return self.versions.filter(
channel=amo.RELEASE_CHANNEL_UNLISTED).exists()
@classmethod
def featured_random(cls, app, lang):
return get_featured_ids(app, lang)
@property
def requires_restart(self):
"""Whether the add-on current version requires a browser restart to
work."""
return self.current_version and self.current_version.requires_restart
def is_featured(self, app, lang=None):
"""Is add-on globally featured for this app and language?"""
if app:
return self.id in get_featured_ids(app, lang)
def has_full_profile(self):
"""Is developer profile public (completed)?"""
return self.the_reason and self.the_future
def has_profile(self):
"""Is developer profile (partially or entirely) completed?"""
return self.the_reason or self.the_future
@amo.cached_property
def tags_partitioned_by_developer(self):
"""Returns a tuple of developer tags and user tags for this addon."""
tags = self.tags.not_denied()
if self.is_persona:
return [], tags
user_tags = tags.exclude(addon_tags__user__in=self.listed_authors)
dev_tags = tags.exclude(id__in=[t.id for t in user_tags])
return dev_tags, user_tags
@amo.cached_property(writable=True)
def compatible_apps(self):
"""Shortcut to get compatible apps for the current version."""
# Search providers and personas don't list their supported apps.
if self.type in amo.NO_COMPAT:
return dict((app, None) for app in
amo.APP_TYPE_SUPPORT[self.type])
if self.current_version:
return self.current_version.compatible_apps
else:
return {}
def accepts_compatible_apps(self):
"""True if this add-on lists compatible apps."""
return self.type not in amo.NO_COMPAT
def incompatible_latest_apps(self):
"""Returns a list of applications with which this add-on is
incompatible (based on the latest version of each app).
"""
return [app for app, ver in self.compatible_apps.items() if ver and
version_int(ver.max.version) < version_int(app.latest_version)]
def has_author(self, user, roles=None):
"""True if ``user`` is an author with any of the specified ``roles``.
``roles`` should be a list of valid roles (see amo.AUTHOR_ROLE_*). If
not specified, has_author will return true if the user has any role.
"""
if user is None or user.is_anonymous():
return False
if roles is None:
roles = dict(amo.AUTHOR_CHOICES).keys()
return AddonUser.objects.filter(addon=self, user=user,
role__in=roles).exists()
@property
def takes_contributions(self):
return (self.status == amo.STATUS_PUBLIC and
self.wants_contributions and
(self.paypal_id or self.charity_id))
@classmethod
def _last_updated_queries(cls):
"""
Get the queries used to calculate addon.last_updated.
"""
status_change = Max('versions__files__datestatuschanged')
public = (
Addon.objects.no_cache().filter(
status=amo.STATUS_PUBLIC,
versions__files__status=amo.STATUS_PUBLIC)
.exclude(type=amo.ADDON_PERSONA)
.values('id').annotate(last_updated=status_change))
stati = amo.VALID_ADDON_STATUSES
exp = (Addon.objects.no_cache().exclude(status__in=stati)
.filter(versions__files__status__in=amo.VALID_FILE_STATUSES)
.values('id')
.annotate(last_updated=Max('versions__files__created')))
personas = (Addon.objects.no_cache().filter(type=amo.ADDON_PERSONA)
.extra(select={'last_updated': 'created'}))
return dict(public=public, exp=exp, personas=personas)
@amo.cached_property(writable=True)
def all_categories(self):
return filter(
None, [cat.to_static_category() for cat in self.categories.all()])
@amo.cached_property(writable=True)
def all_previews(self):
return list(self.get_previews())
def get_previews(self):
"""Exclude promo graphics."""
return self.previews.exclude(position=-1)
@property
def app_categories(self):
app_cats = {}
categories = sorted_groupby(
sorted(self.all_categories, key=attrgetter('weight', 'name')),
key=lambda x: amo.APP_IDS.get(x.application))
for app, cats in categories:
app_cats[app] = list(cats)
return app_cats
def remove_locale(self, locale):
"""NULLify strings in this locale for the add-on and versions."""
for o in itertools.chain([self], self.versions.all()):
Translation.objects.remove_for(o, locale)
def get_localepicker(self):
"""For language packs, gets the contents of localepicker."""
if (self.type == amo.ADDON_LPAPP and
self.status == amo.STATUS_PUBLIC and
self.current_version):
files = (self.current_version.files
.filter(platform=amo.PLATFORM_ANDROID.id))
try:
return unicode(files[0].get_localepicker(), 'utf-8')
except IndexError:
pass
return ''
def can_review(self, user):
return not(user and self.has_author(user))
@property
def all_dependencies(self):
"""Return all the (valid) add-ons this add-on depends on."""
return list(self.dependencies.valid().all()[:3])
def has_installed(self, user):
if not user or not isinstance(user, UserProfile):
return False
return self.installed.filter(user=user).exists()
def get_latest_file(self):
"""Get the latest file from the current version."""
cur = self.current_version
if cur:
res = cur.files.order_by('-created')
if res:
return res[0]
def in_escalation_queue(self):
return self.escalationqueue_set.exists()
def check_ownership(self, request, require_owner, require_author,
ignore_disabled, admin):
"""
Used by acl.check_ownership to see if request.user has permissions for
the addon.
"""
if require_author:
require_owner = False
ignore_disabled = True
admin = False
return acl.check_addon_ownership(request, self, admin=admin,
viewer=(not require_owner),
ignore_disabled=ignore_disabled)
@property
def feature_compatibility(self):
try:
feature_compatibility = self.addonfeaturecompatibility
except AddonFeatureCompatibility.DoesNotExist:
# If it does not exist, return a blank one, no need to create. It's
# the caller responsibility to create when needed to avoid
# unexpected database writes.
feature_compatibility = AddonFeatureCompatibility()
return feature_compatibility
dbsignals.pre_save.connect(save_signal, sender=Addon,
dispatch_uid='addon_translations')
@receiver(signals.version_changed, dispatch_uid='version_changed')
def version_changed(sender, **kw):
from . import tasks
tasks.version_changed.delay(sender.id)
@receiver(dbsignals.post_save, sender=Addon,
dispatch_uid='addons.search.index')
def update_search_index(sender, instance, **kw):
from . import tasks
if not kw.get('raw'):
tasks.index_addons.delay([instance.id])
@Addon.on_change
def watch_status(old_attr=None, new_attr=None, instance=None,
sender=None, **kwargs):
"""
Set nomination date if the addon is new in queue or updating.
The nomination date cannot be reset, say, when a developer cancels
their request for review and re-requests review.
If a version is rejected after nomination, the developer has
to upload a new version.
"""
if old_attr is None:
old_attr = {}
if new_attr is None:
new_attr = {}
new_status = new_attr.get('status')
old_status = old_attr.get('status')
latest_version = instance.find_latest_version(
channel=amo.RELEASE_CHANNEL_LISTED)
if (new_status not in amo.VALID_ADDON_STATUSES or
not new_status or not latest_version):
return
if old_status not in amo.UNREVIEWED_ADDON_STATUSES:
# New: will (re)set nomination only if it's None.
latest_version.reset_nomination_time()
elif latest_version.has_files:
# Updating: inherit nomination from last nominated version.
# Calls `inherit_nomination` manually given that signals are
# deactivated to avoid circular calls.
inherit_nomination(None, latest_version)
@Addon.on_change
def watch_disabled(old_attr=None, new_attr=None, instance=None, sender=None,
**kwargs):
if old_attr is None:
old_attr = {}
if new_attr is None:
new_attr = {}
attrs = dict((k, v) for k, v in old_attr.items()
if k in ('disabled_by_user', 'status'))
if Addon(**attrs).is_disabled and not instance.is_disabled:
for f in File.objects.filter(version__addon=instance.id):
f.unhide_disabled_file()
if instance.is_disabled and not Addon(**attrs).is_disabled:
for f in File.objects.filter(version__addon=instance.id):
f.hide_disabled_file()
@Addon.on_change
def watch_developer_notes(old_attr=None, new_attr=None, instance=None,
sender=None, **kwargs):
if old_attr is None:
old_attr = {}
if new_attr is None:
new_attr = {}
whiteboard_changed = (
new_attr.get('whiteboard') and
old_attr.get('whiteboard') != new_attr.get('whiteboard'))
developer_comments_changed = (new_attr.get('_developer_comments_cache') and
old_attr.get('_developer_comments_cache') !=
new_attr.get('_developer_comments_cache'))
if whiteboard_changed or developer_comments_changed:
instance.versions.update(has_info_request=False)
def attach_translations(addons):
"""Put all translations into a translations dict."""
attach_trans_dict(Addon, addons)
def attach_tags(addons):
addon_dict = dict((a.id, a) for a in addons)
qs = (Tag.objects.not_denied().filter(addons__in=addon_dict)
.values_list('addons__id', 'tag_text'))
for addon, tags in sorted_groupby(qs, lambda x: x[0]):
addon_dict[addon].tag_list = [t[1] for t in tags]
class Persona(caching.CachingMixin, models.Model):
"""Personas-specific additions to the add-on model."""
STATUS_CHOICES = amo.STATUS_CHOICES_PERSONA
addon = models.OneToOneField(Addon, null=True)
persona_id = models.PositiveIntegerField(db_index=True)
# name: deprecated in favor of Addon model's name field
# description: deprecated, ditto
header = models.CharField(max_length=64, null=True)
footer = models.CharField(max_length=64, null=True)
accentcolor = models.CharField(max_length=10, null=True)
textcolor = models.CharField(max_length=10, null=True)
author = models.CharField(max_length=255, null=True)
display_username = models.CharField(max_length=255, null=True)
submit = models.DateTimeField(null=True)
approve = models.DateTimeField(null=True)
movers = models.FloatField(null=True, db_index=True)
popularity = models.IntegerField(null=False, default=0, db_index=True)
license = models.PositiveIntegerField(
choices=amo.PERSONA_LICENSES_CHOICES, null=True, blank=True)
# To spot duplicate submissions.
checksum = models.CharField(max_length=64, blank=True, default='')
dupe_persona = models.ForeignKey('self', null=True)
objects = caching.CachingManager()
class Meta:
db_table = 'personas'
def __unicode__(self):
return unicode(self.addon.name)
def is_new(self):
return self.persona_id == 0
def _image_url(self, filename):
host = helpers.user_media_url('addons')
image_url = posixpath.join(host, str(self.addon.id), filename or '')
# TODO: Bust the cache on the hash of the image contents or something.
if self.addon.modified is not None:
modified = int(time.mktime(self.addon.modified.timetuple()))
else:
modified = 0
return '%s?%s' % (image_url, modified)
def _image_path(self, filename):
return os.path.join(helpers.user_media_path('addons'),
str(self.addon.id), filename)
@amo.cached_property
def thumb_url(self):
"""
Handles deprecated GetPersonas URL.
In days of yore, preview.jpg used to be a separate image.
In modern days, we use the same image for big preview + thumb.
"""
if self.is_new():
return self._image_url('preview.png')
else:
return self._image_url('preview.jpg')
@amo.cached_property
def thumb_path(self):
"""
Handles deprecated GetPersonas path.
In days of yore, preview.jpg used to be a separate image.
In modern days, we use the same image for big preview + thumb.
"""
if self.is_new():
return self._image_path('preview.png')
else:
return self._image_path('preview.jpg')
@amo.cached_property
def icon_url(self):
"""URL to personas square preview."""
if self.is_new():
return self._image_url('icon.png')
else:
return self._image_url('preview_small.jpg')
@amo.cached_property
def icon_path(self):
"""Path to personas square preview."""
if self.is_new():
return self._image_path('icon.png')
else:
return self._image_path('preview_small.jpg')
@amo.cached_property
def preview_url(self):
"""URL to Persona's big, 680px, preview."""
if self.is_new():
return self._image_url('preview.png')
else:
return self._image_url('preview_large.jpg')
@amo.cached_property
def preview_path(self):
"""Path to Persona's big, 680px, preview."""
if self.is_new():
return self._image_path('preview.png')
else:
return self._image_path('preview_large.jpg')
@amo.cached_property
def header_url(self):
return self._image_url(self.header)
@amo.cached_property
def footer_url(self):
return self.footer and self._image_url(self.footer) or ''
@amo.cached_property
def header_path(self):
return self._image_path(self.header)
@amo.cached_property
def footer_path(self):
return self.footer and self._image_path(self.footer) or ''
@amo.cached_property
def update_url(self):
locale = settings.LANGUAGE_URL_MAP.get(trans_real.get_language())
return settings.NEW_PERSONAS_UPDATE_URL % {
'locale': locale or settings.LANGUAGE_CODE,
'id': self.addon.id
}
@amo.cached_property
def theme_data(self):
"""Theme JSON Data for Browser/extension preview."""
def hexcolor(color):
return '#%s' % color
addon = self.addon
return {
'id': unicode(self.addon.id), # Personas dislikes ints
'name': unicode(addon.name),
'accentcolor': hexcolor(self.accentcolor),
'textcolor': hexcolor(self.textcolor),
'category': (unicode(addon.all_categories[0].name) if
addon.all_categories else ''),
# TODO: Change this to be `addons_users.user.display_name`.
'author': self.display_username,
'description': unicode(addon.description),
'header': self.header_url,
'footer': self.footer_url or '',
'headerURL': self.header_url,
'footerURL': self.footer_url or '',
'previewURL': self.preview_url,
'iconURL': self.icon_url,
'updateURL': self.update_url,
'detailURL': helpers.absolutify(self.addon.get_url_path()),
'version': '1.0'
}
@property
def json_data(self):
"""Persona JSON Data for Browser/extension preview."""
return json.dumps(self.theme_data,
separators=(',', ':'), cls=AMOJSONEncoder)
def authors_other_addons(self, app=None):
"""
Return other addons by the author(s) of this addon,
optionally takes an app.
"""
qs = (Addon.objects.valid()
.exclude(id=self.addon.id)
.filter(type=amo.ADDON_PERSONA))
return (qs.filter(addonuser__listed=True,
authors__in=self.addon.listed_authors)
.distinct())
@amo.cached_property(writable=True)
def listed_authors(self):
return self.addon.listed_authors
class AddonCategory(caching.CachingMixin, models.Model):
addon = models.ForeignKey(Addon, on_delete=models.CASCADE)
category = models.ForeignKey('Category')
feature = models.BooleanField(default=False)
feature_locales = models.CharField(max_length=255, default='', null=True)
objects = caching.CachingManager()
class Meta:
db_table = 'addons_categories'
unique_together = ('addon', 'category')
@classmethod
def creatured_random(cls, category, lang):
return get_creatured_ids(category, lang)
class AddonUser(caching.CachingMixin, models.Model):
addon = models.ForeignKey(Addon, on_delete=models.CASCADE)
user = UserForeignKey()
role = models.SmallIntegerField(default=amo.AUTHOR_ROLE_OWNER,
choices=amo.AUTHOR_CHOICES)
listed = models.BooleanField(_(u'Listed'), default=True)
position = models.IntegerField(default=0)
objects = caching.CachingManager()
def __init__(self, *args, **kwargs):
super(AddonUser, self).__init__(*args, **kwargs)
self._original_role = self.role
self._original_user_id = self.user_id
class Meta:
db_table = 'addons_users'
class AddonDependency(models.Model):
addon = models.ForeignKey(Addon, related_name='addons_dependencies')
dependent_addon = models.ForeignKey(Addon, related_name='dependent_on')
class Meta:
db_table = 'addons_dependencies'
unique_together = ('addon', 'dependent_addon')
class AddonFeatureCompatibility(ModelBase):
addon = models.OneToOneField(
Addon, primary_key=True, on_delete=models.CASCADE)
e10s = models.PositiveSmallIntegerField(
choices=amo.E10S_COMPATIBILITY_CHOICES, default=amo.E10S_UNKNOWN)
def __unicode__(self):
return unicode(self.addon) if self.pk else u""
def get_e10s_classname(self):
return amo.E10S_COMPATIBILITY_CHOICES_API[self.e10s]
class DeniedGuid(ModelBase):
guid = models.CharField(max_length=255, unique=True)
comments = models.TextField(default='', blank=True)
class Meta:
db_table = 'denied_guids'
def __unicode__(self):
return self.guid
class Category(OnChangeMixin, ModelBase):
# Old name translations, we now have constants translated via gettext, but
# this is for backwards-compatibility, for categories which have a weird
# type/application/slug combo that is not in the constants.
db_name = TranslatedField(db_column='name')
slug = SlugField(max_length=50,
help_text='Used in Category URLs.')
type = models.PositiveIntegerField(db_column='addontype_id',
choices=do_dictsort(amo.ADDON_TYPE))
application = models.PositiveIntegerField(choices=amo.APPS_CHOICES,
null=True, blank=True,
db_column='application_id')
count = models.IntegerField('Addon count', default=0)
weight = models.IntegerField(
default=0, help_text='Category weight used in sort ordering')
misc = models.BooleanField(default=False)
addons = models.ManyToManyField(Addon, through='AddonCategory')
class Meta:
db_table = 'categories'
verbose_name_plural = 'Categories'
@property
def name(self):
try:
value = CATEGORIES[self.application][self.type][self.slug].name
except KeyError:
# If we can't find the category in the constants dict, fall back
# to the db field.
value = self.db_name
return unicode(value)
def __unicode__(self):
return unicode(self.name)
def get_url_path(self):
try:
type = amo.ADDON_SLUGS[self.type]
except KeyError:
type = amo.ADDON_SLUGS[amo.ADDON_EXTENSION]
return reverse('browse.%s' % type, args=[self.slug])
def to_static_category(self):
"""Return the corresponding StaticCategory instance from a Category."""
try:
staticcategory = CATEGORIES[self.application][self.type][self.slug]
except KeyError:
staticcategory = None
return staticcategory
@classmethod
def from_static_category(cls, static_category):
"""Return a Category instance created from a StaticCategory.
Does not save it into the database. Useful in tests."""
return cls(**static_category.__dict__)
dbsignals.pre_save.connect(save_signal, sender=Category,
dispatch_uid='category_translations')
class Preview(ModelBase):
addon = models.ForeignKey(Addon, related_name='previews')
caption = TranslatedField()
position = models.IntegerField(default=0)
sizes = JSONField(max_length=25, default={})
class Meta:
db_table = 'previews'
ordering = ('position', 'created')
def _image_url(self, url_template):
if self.modified is not None:
modified = int(time.mktime(self.modified.timetuple()))
else:
modified = 0
args = [self.id / 1000, self.id, modified]
return url_template % tuple(args)
def _image_path(self, url_template):
args = [self.id / 1000, self.id]
return url_template % tuple(args)
def as_dict(self, src=None):
d = {'full': urlparams(self.image_url, src=src),
'thumbnail': urlparams(self.thumbnail_url, src=src),
'caption': unicode(self.caption)}
return d
@property
def is_landscape(self):
size = self.image_size
if not size:
return False
return size[0] > size[1]
@property
def thumbnail_url(self):
template = (
helpers.user_media_url('previews') +
'thumbs/%s/%d.png?modified=%s')
return self._image_url(template)
@property
def image_url(self):
template = (
helpers.user_media_url('previews') +
'full/%s/%d.png?modified=%s')
return self._image_url(template)
@property
def thumbnail_path(self):
template = os.path.join(
helpers.user_media_path('previews'),
'thumbs',
'%s',
'%d.png'
)
return self._image_path(template)
@property
def image_path(self):
template = os.path.join(
helpers.user_media_path('previews'),
'full',
'%s',
'%d.png'
)
return self._image_path(template)
@property
def thumbnail_size(self):
return self.sizes.get('thumbnail', []) if self.sizes else []
@property
def image_size(self):
return self.sizes.get('image', []) if self.sizes else []
dbsignals.pre_save.connect(save_signal, sender=Preview,
dispatch_uid='preview_translations')
def delete_preview_files(sender, instance, **kw):
"""On delete of the Preview object from the database, unlink the image
and thumb on the file system """
for filename in [instance.image_path, instance.thumbnail_path]:
if storage.exists(filename):
log.info('Removing filename: %s for preview: %s'
% (filename, instance.pk))
storage.delete(filename)
models.signals.post_delete.connect(delete_preview_files,
sender=Preview,
dispatch_uid='delete_preview_files')
class AppSupport(ModelBase):
"""Cache to tell us if an add-on's current version supports an app."""
addon = models.ForeignKey(Addon, on_delete=models.CASCADE)
app = models.PositiveIntegerField(choices=amo.APPS_CHOICES,
db_column='app_id')
min = models.BigIntegerField("Minimum app version", null=True)
max = models.BigIntegerField("Maximum app version", null=True)
class Meta:
db_table = 'appsupport'
unique_together = ('addon', 'app')
class Charity(ModelBase):
name = models.CharField(max_length=255)
url = models.URLField()
paypal = models.CharField(max_length=255)
class Meta:
db_table = 'charities'
@property
def outgoing_url(self):
if self.pk == amo.FOUNDATION_ORG:
return self.url
return get_outgoing_url(unicode(self.url))
class DeniedSlug(ModelBase):
name = models.CharField(max_length=255, unique=True, default='')
class Meta:
db_table = 'addons_denied_slug'
def __unicode__(self):
return self.name
@classmethod
def blocked(cls, slug):
return slug.isdigit() or cls.objects.filter(name=slug).exists()
class FrozenAddon(models.Model):
"""Add-ons in this table never get a hotness score."""
addon = models.ForeignKey(Addon)
class Meta:
db_table = 'frozen_addons'
def __unicode__(self):
return 'Frozen: %s' % self.addon_id
@receiver(dbsignals.post_save, sender=FrozenAddon)
def freezer(sender, instance, **kw):
# Adjust the hotness of the FrozenAddon.
if instance.addon_id:
Addon.objects.get(id=instance.addon_id).update(hotness=0)
class CompatOverride(ModelBase):
"""Helps manage compat info for add-ons not hosted on AMO."""
name = models.CharField(max_length=255, blank=True, null=True)
guid = models.CharField(max_length=255, unique=True)
addon = models.ForeignKey(Addon, blank=True, null=True,
help_text='Fill this out to link an override '
'to a hosted add-on')
class Meta:
db_table = 'compat_override'
unique_together = ('addon', 'guid')
def save(self, *args, **kw):
if not self.addon:
qs = Addon.objects.filter(guid=self.guid)
if qs:
self.addon = qs[0]
return super(CompatOverride, self).save(*args, **kw)
def __unicode__(self):
if self.addon:
return unicode(self.addon)
elif self.name:
return '%s (%s)' % (self.name, self.guid)
else:
return self.guid
def is_hosted(self):
"""Am I talking about an add-on on AMO?"""
return bool(self.addon_id)
@staticmethod
def transformer(overrides):
if not overrides:
return
id_map = dict((o.id, o) for o in overrides)
qs = CompatOverrideRange.objects.filter(compat__in=id_map)
for compat_id, ranges in sorted_groupby(qs, 'compat_id'):
id_map[compat_id].compat_ranges = list(ranges)
# May be filled in by a transformer for performance.
@amo.cached_property(writable=True)
def compat_ranges(self):
return list(self._compat_ranges.all())
def collapsed_ranges(self):
"""Collapse identical version ranges into one entity."""
Range = collections.namedtuple('Range', 'type min max apps')
AppRange = collections.namedtuple('AppRange', 'app min max')
rv = []
def sort_key(x):
return (x.min_version, x.max_version, x.type)
for key, compats in sorted_groupby(self.compat_ranges, key=sort_key):
compats = list(compats)
first = compats[0]
item = Range(first.override_type(), first.min_version,
first.max_version, [])
for compat in compats:
app = AppRange(amo.APPS_ALL[compat.app],
compat.min_app_version, compat.max_app_version)
item.apps.append(app)
rv.append(item)
return rv
OVERRIDE_TYPES = (
(0, 'Compatible (not supported)'),
(1, 'Incompatible'),
)
class CompatOverrideRange(ModelBase):
"""App compatibility for a certain version range of a RemoteAddon."""
compat = models.ForeignKey(CompatOverride, related_name='_compat_ranges')
type = models.SmallIntegerField(choices=OVERRIDE_TYPES, default=1)
min_version = models.CharField(
max_length=255, default='0',
help_text=u'If not "0", version is required to exist for the override'
u' to take effect.')
max_version = models.CharField(
max_length=255, default='*',
help_text=u'If not "*", version is required to exist for the override'
u' to take effect.')
app = models.PositiveIntegerField(choices=amo.APPS_CHOICES,
db_column='app_id')
min_app_version = models.CharField(max_length=255, default='0')
max_app_version = models.CharField(max_length=255, default='*')
class Meta:
db_table = 'compat_override_range'
def override_type(self):
"""This is what Firefox wants to see in the XML output."""
return {0: 'compatible', 1: 'incompatible'}[self.type]
class IncompatibleVersions(ModelBase):
"""
Denormalized table to join against for fast compat override filtering.
This was created to be able to join against a specific version record since
the CompatOverrideRange can be wildcarded (e.g. 0 to *, or 1.0 to 1.*), and
addon versioning isn't as consistent as Firefox versioning to trust
`version_int` in all cases. So extra logic needed to be provided for when
a particular version falls within the range of a compatibility override.
"""
version = models.ForeignKey(Version, related_name='+')
app = models.PositiveIntegerField(choices=amo.APPS_CHOICES,
db_column='app_id')
min_app_version = models.CharField(max_length=255, blank=True, default='0')
max_app_version = models.CharField(max_length=255, blank=True, default='*')
min_app_version_int = models.BigIntegerField(blank=True, null=True,
editable=False, db_index=True)
max_app_version_int = models.BigIntegerField(blank=True, null=True,
editable=False, db_index=True)
class Meta:
db_table = 'incompatible_versions'
def __unicode__(self):
return u'<IncompatibleVersion V:%s A:%s %s-%s>' % (
self.version.id, self.app.id, self.min_app_version,
self.max_app_version)
def save(self, *args, **kw):
self.min_app_version_int = version_int(self.min_app_version)
self.max_app_version_int = version_int(self.max_app_version)
return super(IncompatibleVersions, self).save(*args, **kw)
def update_incompatible_versions(sender, instance, **kw):
if not instance.compat.addon_id:
return
if not instance.compat.addon.type == amo.ADDON_EXTENSION:
return
from . import tasks
versions = instance.compat.addon.versions.values_list('id', flat=True)
for chunk in chunked(versions, 50):
tasks.update_incompatible_appversions.delay(chunk)
models.signals.post_save.connect(update_incompatible_versions,
sender=CompatOverrideRange,
dispatch_uid='cor_update_incompatible')
models.signals.post_delete.connect(update_incompatible_versions,
sender=CompatOverrideRange,
dispatch_uid='cor_update_incompatible')
def track_new_status(sender, instance, *args, **kw):
if kw.get('raw'):
# The addon is being loaded from a fixure.
return
if kw.get('created'):
track_addon_status_change(instance)
models.signals.post_save.connect(track_new_status,
sender=Addon,
dispatch_uid='track_new_addon_status')
@Addon.on_change
def track_status_change(old_attr=None, new_attr=None, **kw):
if old_attr is None:
old_attr = {}
if new_attr is None:
new_attr = {}
new_status = new_attr.get('status')
old_status = old_attr.get('status')
if new_status != old_status:
track_addon_status_change(kw['instance'])
def track_addon_status_change(addon):
statsd.incr('addon_status_change.all.status_{}'
.format(addon.status))
|
mstriemer/addons-server
|
src/olympia/addons/models.py
|
Python
|
bsd-3-clause
| 80,686
|
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/enterprise/connectors/device_trust/signals/decorators/common/common_signals_decorator.h"
#include "base/bind.h"
#include "base/callback.h"
#include "chrome/browser/enterprise/signals/signals_utils.h"
#include "components/policy/core/common/cloud/cloud_policy_util.h"
#include "components/version_info/version_info.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
namespace enterprise_connectors {
CommonSignalsDecorator::CommonSignalsDecorator(PrefService* local_state,
PrefService* profile_prefs)
: local_state_(local_state), profile_prefs_(profile_prefs) {
DCHECK(profile_prefs_);
DCHECK(local_state_);
}
CommonSignalsDecorator::~CommonSignalsDecorator() = default;
void CommonSignalsDecorator::Decorate(SignalsType& signals,
base::OnceClosure done_closure) {
signals.set_os(policy::GetOSPlatform());
signals.set_os_version(policy::GetOSVersion());
signals.set_display_name(policy::GetDeviceName());
signals.set_browser_version(version_info::GetVersionNumber());
// Get signals from policy values.
signals.set_built_in_dns_client_enabled(
enterprise_signals::utils::GetBuiltInDnsClientEnabled(local_state_));
signals.set_safe_browsing_protection_level(static_cast<int32_t>(
enterprise_signals::utils::GetSafeBrowsingProtectionLevel(
profile_prefs_)));
absl::optional<bool> third_party_blocking_enabled =
enterprise_signals::utils::GetThirdPartyBlockingEnabled(local_state_);
if (third_party_blocking_enabled.has_value()) {
signals.set_third_party_blocking_enabled(
third_party_blocking_enabled.value());
}
absl::optional<bool> chrome_cleanup_enabled =
enterprise_signals::utils::GetChromeCleanupEnabled(local_state_);
if (chrome_cleanup_enabled.has_value()) {
signals.set_chrome_cleanup_enabled(chrome_cleanup_enabled.value());
}
absl::optional<safe_browsing::PasswordProtectionTrigger>
password_protection_warning_trigger =
enterprise_signals::utils::GetPasswordProtectionWarningTrigger(
profile_prefs_);
if (password_protection_warning_trigger.has_value()) {
signals.set_password_protection_warning_trigger(
static_cast<int32_t>(password_protection_warning_trigger.value()));
}
auto callback =
base::BindOnce(&CommonSignalsDecorator::OnHardwareInfoRetrieved,
weak_ptr_factory_.GetWeakPtr(), std::ref(signals),
std::move(done_closure));
base::SysInfo::GetHardwareInfo(std::move(callback));
}
void CommonSignalsDecorator::OnHardwareInfoRetrieved(
SignalsType& signals,
base::OnceClosure done_closure,
base::SysInfo::HardwareInfo hardware_info) {
// TODO(b/178421844): Look into adding caching support for these signals, as
// they will never change throughout the browser's lifetime.
signals.set_device_model(hardware_info.model);
signals.set_device_manufacturer(hardware_info.manufacturer);
std::move(done_closure).Run();
}
} // namespace enterprise_connectors
|
scheib/chromium
|
chrome/browser/enterprise/connectors/device_trust/signals/decorators/common/common_signals_decorator.cc
|
C++
|
bsd-3-clause
| 3,271
|
<html lang="en">
<head>
<title>Sbttl - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Pseudo-Ops.html#Pseudo-Ops" title="Pseudo Ops">
<link rel="prev" href="Rept.html#Rept" title="Rept">
<link rel="next" href="Scl.html#Scl" title="Scl">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This file documents the GNU Assembler "as".
Copyright (C) 1991-2014 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled ``GNU Free Documentation License''.
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<a name="Sbttl"></a>
<p>
Next: <a rel="next" accesskey="n" href="Scl.html#Scl">Scl</a>,
Previous: <a rel="previous" accesskey="p" href="Rept.html#Rept">Rept</a>,
Up: <a rel="up" accesskey="u" href="Pseudo-Ops.html#Pseudo-Ops">Pseudo Ops</a>
<hr>
</div>
<h3 class="section">7.97 <code>.sbttl "</code><var>subheading</var><code>"</code></h3>
<p><a name="index-g_t_0040code_007bsbttl_007d-directive-443"></a><a name="index-subtitles-for-listings-444"></a><a name="index-listing-control_003a-subtitle-445"></a>Use <var>subheading</var> as the title (third line, immediately after the
title line) when generating assembly listings.
<p>This directive affects subsequent pages, as well as the current page if
it appears within ten lines of the top of a page.
</body></html>
|
ExploreEmbedded/Tit-Windows
|
tools/doc/binutils/as.html/Sbttl.html
|
HTML
|
bsd-3-clause
| 2,387
|
\begin{VerbatimInput}[frame=single, fontsize=\tiny, numbers=left, label={[11420]\url{http://article.gmane.org/gmane.comp.sysutils.backup.bacula.devel/11420}}]
{../../data/11420.txt}
\end{VerbatimInput}
|
joaohf/rxpslca
|
src/artigo/bacula-devel/11420.tex
|
TeX
|
bsd-3-clause
| 202
|
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------------------------
from os.path import basename, exists
from json import loads, dumps
from tempfile import NamedTemporaryFile
from tornado.web import authenticated, HTTPError
from qiita_core.qiita_settings import r_client
from qiita_pet.handlers.base_handlers import BaseHandler
from qiita_db.util import get_files_from_uploads_folders
from qiita_db.study import Study
from qiita_db.metadata_template.sample_template import SampleTemplate
from qiita_db.metadata_template.util import looks_like_qiime_mapping_file
from qiita_db.software import Software, Parameters
from qiita_db.processing_job import ProcessingJob
from qiita_db.exceptions import QiitaDBUnknownIDError
from qiita_pet.handlers.api_proxy import (
data_types_get_req, sample_template_samples_get_req,
prep_template_samples_get_req, study_prep_get_req,
sample_template_meta_cats_get_req, sample_template_category_get_req,
get_sample_template_processing_status,
check_fp)
SAMPLE_TEMPLATE_KEY_FORMAT = 'sample_template_%s'
def sample_template_checks(study_id, user, check_exists=False):
"""Performs different checks and raises errors if any of the checks fail
Parameters
----------
study_id : int
The study id
user : qiita_db.user.User
The user trying to access the study
check_exists : bool, optional
If true, check if the sample template exists
Raises
------
HTTPError
404 if the study does not exist
403 if the user does not have access to the study
404 if check_exists == True and the sample template doesn't exist
"""
try:
study = Study(int(study_id))
except QiitaDBUnknownIDError:
raise HTTPError(404, reason='Study does not exist')
if not study.has_access(user):
raise HTTPError(403, reason='User does not have access to study')
# Check if the sample template exists
if check_exists and not SampleTemplate.exists(study_id):
raise HTTPError(404, reason="Study %s doesn't have sample information"
% study_id)
def sample_template_handler_post_request(study_id, user, filepath,
data_type=None, direct_upload=False):
"""Creates a new sample template
Parameters
----------
study_id: int
The study to add the sample information
user: qiita_db.user import User
The user performing the request
filepath: str
The path to the sample template file
data_type: str, optional
If filepath is a QIIME mapping file, the data type of the prep
information file
direct_upload: boolean, optional
If filepath is a direct upload; if False we need to process the
filepath as part of the study upload folder
Returns
-------
dict of {'job': str}
job: the id of the job adding the sample information to the study
Raises
------
HTTPError
404 if the filepath doesn't exist
"""
# Check if the current user has access to the study
sample_template_checks(study_id, user)
# Check if the file exists
if not direct_upload:
fp_rsp = check_fp(study_id, filepath)
if fp_rsp['status'] != 'success':
raise HTTPError(404, reason='Filepath not found')
filepath = fp_rsp['file']
is_mapping_file = looks_like_qiime_mapping_file(filepath)
if is_mapping_file and not data_type:
raise HTTPError(400, reason='Please, choose a data type if uploading '
'a QIIME mapping file')
qiita_plugin = Software.from_name_and_version('Qiita', 'alpha')
cmd = qiita_plugin.get_command('create_sample_template')
params = Parameters.load(
cmd, values_dict={'fp': filepath, 'study_id': study_id,
'is_mapping_file': is_mapping_file,
'data_type': data_type})
job = ProcessingJob.create(user, params, True)
r_client.set(SAMPLE_TEMPLATE_KEY_FORMAT % study_id,
dumps({'job_id': job.id}))
job.submit()
return {'job': job.id}
def sample_template_handler_patch_request(user, req_op, req_path,
req_value=None, req_from=None,
direct_upload=False):
"""Patches the sample template
Parameters
----------
user: qiita_db.user.User
The user performing the request
req_op : str
The operation to perform on the sample template
req_path : str
The path to the attribute to patch
req_value : str, optional
The new value
req_from : str, optional
The original path of the element
direct_upload : boolean, optional
If the file being uploaded comes from a direct upload (True)
Returns
-------
Raises
------
HTTPError
400 If the path parameter doens't follow the expected format
400 If the given operation is not supported
"""
req_path = [v for v in req_path.split('/') if v]
# At this point we know the path should be at least length 2
if len(req_path) < 2:
raise HTTPError(400, reason='Incorrect path parameter')
study_id = int(req_path[0])
# Check if the current user has access to the study and if the sample
# template exists
sample_template_checks(study_id, user, check_exists=True)
if req_op == 'remove':
# Path format
# column: study_id/columns/column_name
# sample: study_id/samples/sample_id
if len(req_path) != 3:
raise HTTPError(400, reason='Incorrect path parameter')
attribute = req_path[1]
attr_id = req_path[2]
qiita_plugin = Software.from_name_and_version('Qiita', 'alpha')
cmd = qiita_plugin.get_command('delete_sample_or_column')
params = Parameters.load(
cmd, values_dict={'obj_class': 'SampleTemplate',
'obj_id': study_id,
'sample_or_col': attribute,
'name': attr_id})
job = ProcessingJob.create(user, params, True)
# Store the job id attaching it to the sample template id
r_client.set(SAMPLE_TEMPLATE_KEY_FORMAT % study_id,
dumps({'job_id': job.id}))
job.submit()
return {'job': job.id}
elif req_op == 'replace':
# WARNING: Although the patch operation is a replace, is not a full
# true replace. A replace is in theory equivalent to a remove + add.
# In this case, the replace operation doesn't necessarily removes
# anything (e.g. when only new columns/samples are being added to the)
# sample information.
# Path format: study_id/data
# Forcing to specify data for extensibility. In the future we may want
# to use this function to replace other elements of the sample
# information
if len(req_path) != 2:
raise HTTPError(400, reason='Incorrect path parameter')
attribute = req_path[1]
if attribute == 'data':
# Update the sample information
if req_value is None:
raise HTTPError(400, reason="Value is required when updating "
"sample information")
if direct_upload:
# We can assume that the file exist as it was generated by
# the system
filepath = req_value
if not exists(filepath):
reason = ('Upload file not found (%s), please report to '
'qiita.help@gmail.com' % filepath)
raise HTTPError(404, reason=reason)
else:
# Check if the file exists
fp_rsp = check_fp(study_id, req_value)
if fp_rsp['status'] != 'success':
raise HTTPError(404, reason='Filepath not found')
filepath = fp_rsp['file']
qiita_plugin = Software.from_name_and_version('Qiita', 'alpha')
cmd = qiita_plugin.get_command('update_sample_template')
params = Parameters.load(
cmd, values_dict={'study': study_id,
'template_fp': filepath})
job = ProcessingJob.create(user, params, True)
# Store the job id attaching it to the sample template id
r_client.set(SAMPLE_TEMPLATE_KEY_FORMAT % study_id,
dumps({'job_id': job.id}))
job.submit()
return {'job': job.id}
else:
raise HTTPError(404, reason='Attribute %s not found' % attribute)
else:
raise HTTPError(400, reason='Operation %s not supported. Current '
'supported operations: remove, replace' % req_op)
def sample_template_handler_delete_request(study_id, user):
"""Deletes the sample template
Parameters
----------
study_id: int
The study to delete the sample information
user: qiita_db.user
The user performing the request
Returns
-------
dict of {'job': str}
job: the id of the job deleting the sample information to the study
Raises
------
HTTPError
404 If the sample template doesn't exist
"""
# Check if the current user has access to the study and if the sample
# template exists
sample_template_checks(study_id, user, check_exists=True)
qiita_plugin = Software.from_name_and_version('Qiita', 'alpha')
cmd = qiita_plugin.get_command('delete_sample_template')
params = Parameters.load(cmd, values_dict={'study': int(study_id)})
job = ProcessingJob.create(user, params, True)
# Store the job if deleteing the sample template
r_client.set(SAMPLE_TEMPLATE_KEY_FORMAT % study_id,
dumps({'job_id': job.id}))
job.submit()
return {'job': job.id}
class SampleTemplateHandler(BaseHandler):
@authenticated
def get(self):
study_id = self.get_argument('study_id')
# Check if the current user has access to the study
sample_template_checks(study_id, self.current_user)
self.render('study_ajax/sample_summary.html', study_id=study_id)
@authenticated
def post(self):
study_id = int(self.get_argument('study_id'))
filepath = self.get_argument('filepath')
data_type = self.get_argument('data_type')
direct_upload = self.get_argument('direct_upload', False)
if direct_upload and direct_upload == 'true':
direct_upload = True
with NamedTemporaryFile(suffix='.txt', delete=False) as fp:
fp.write(self.request.files['theFile'][0]['body'])
filepath = fp.name
self.write(sample_template_handler_post_request(
study_id, self.current_user, filepath, data_type=data_type,
direct_upload=direct_upload))
@authenticated
def patch(self):
req_op = self.get_argument('op')
req_path = self.get_argument('path')
req_value = self.get_argument('value', None)
req_from = self.get_argument('from', None)
direct_upload = self.get_argument('direct_upload', False)
if direct_upload and direct_upload == 'true':
direct_upload = True
with NamedTemporaryFile(suffix='.txt', delete=False) as fp:
fp.write(self.request.files['value'][0]['body'])
req_value = fp.name
self.write(sample_template_handler_patch_request(
self.current_user, req_op, req_path, req_value, req_from,
direct_upload))
@authenticated
def delete(self):
study_id = int(self.get_argument('study_id'))
self.write(sample_template_handler_delete_request(
study_id, self.current_user))
def sample_template_overview_handler_get_request(study_id, user):
# Check if the current user has access to the sample template
sample_template_checks(study_id, user)
# Check if the sample template exists
exists = SampleTemplate.exists(study_id)
# The following information should always be provided:
# The files that have been uploaded to the system and can be a
# sample template file
files = [f for _, f, _ in get_files_from_uploads_folders(study_id)
if f.endswith(('txt', 'tsv', 'xlsx'))]
# If there is a job associated with the sample information, the job id
job = None
job_info = r_client.get(SAMPLE_TEMPLATE_KEY_FORMAT % study_id)
if job_info:
job = loads(job_info)['job_id']
# Specific information if it exists or not:
data_types = []
st_fp_id = None
old_files = []
num_samples = 0
num_cols = 0
columns = []
specimen_id_column = None
sample_restrictions = ''
if exists:
# If it exists we need to provide:
# The id of the sample template file so the user can download it and
# the list of old filepaths
st = SampleTemplate(study_id)
all_st_files = st.get_filepaths()
# The current sample template file is the first one in the list
# (pop(0)) and we are interested only in the id ([0])
st_fp_id = all_st_files.pop(0)[0]
# For the old filepaths we are only interested in their basename
old_files = [basename(fp) for _, fp in all_st_files]
# The number of samples - this is a space efficient way of counting
# the number of samples. Doing len(list(st.keys())) creates a list
# that we are not using
num_samples = sum(1 for _ in st.keys())
columns = st.categories()
# The number of columns
num_cols = len(columns)
specimen_id_column = Study(study_id).specimen_id_column
_, sample_restrictions = st.validate_restrictions()
else:
# It doesn't exist, we also need to provide the data_types in case
# the user uploads a QIIME mapping file
data_types = sorted(data_types_get_req()['data_types'])
return {'exists': exists,
'uploaded_files': files,
'data_types': data_types,
'user_can_edit': Study(study_id).can_edit(user),
'job': job,
'download_id': st_fp_id,
'old_files': old_files,
'num_samples': num_samples,
'num_columns': num_cols,
'columns': columns,
'sample_restrictions': sample_restrictions,
'specimen_id_column': specimen_id_column}
class SampleTemplateOverviewHandler(BaseHandler):
@authenticated
def get(self):
study_id = int(self.get_argument('study_id'))
self.write(
sample_template_overview_handler_get_request(
study_id, self.current_user))
def sample_template_columns_get_req(study_id, column, user):
"""Returns the columns of the sample template
Parameters
----------
study_id: int
The study to retrieve the sample information summary
column: str
The column of interest, if None send all columns
user: qiita_db.user
The user performing the request
Returns
-------
list of str
The result of the search
Raises
------
HTTPError
404 If the sample template doesn't exist
"""
# Check if the current user has access to the study and if the sample
# template exists
sample_template_checks(study_id, user, check_exists=True)
if column is None:
reply = SampleTemplate(study_id).categories()
else:
reply = list(SampleTemplate(study_id).get_category(column).values())
return reply
class SampleTemplateColumnsHandler(BaseHandler):
@authenticated
def get(self):
"""Send formatted summary page of sample template"""
sid = int(self.get_argument('study_id'))
column = self.get_argument('column', None)
reply = sample_template_columns_get_req(sid, column, self.current_user)
# we reply with {'values': reply} because tornado expectes a dict
self.write({'values': reply})
def _build_sample_summary(study_id, user_id):
"""Builds the row object for SlickGrid
Parameters
----------
study_id : int
Study to get samples from
user_id : str
User requesting the information
Returns
-------
columns : dicts
keys represent fields and values names for the columns in SlickGrid
rows : list of dicts
[ {field_1: 'value', ...}, ...]
"""
# Load all samples available into dictionary and set
rows = {s: {'sample': s} for s in sample_template_samples_get_req(
study_id, user_id)['samples']}
samples = rows.keys()
# Add one column per prep template highlighting what samples exist
preps = study_prep_get_req(study_id, user_id)["info"]
columns = {}
for preptype in preps:
for prep in preps[preptype]:
field = "prep%d" % prep["id"]
name = "%s (%d)" % (prep["name"], prep["id"])
columns[field] = name
prep_samples = prep_template_samples_get_req(
prep['id'], user_id)['samples']
for s in samples:
rows[s][field] = 'X' if s in prep_samples else ''
return columns, rows
class SampleAJAX(BaseHandler):
@authenticated
def get(self):
"""Show the sample summary page"""
study_id = int(self.get_argument('study_id'))
email = self.current_user.id
res = sample_template_meta_cats_get_req(study_id, email)
if res['status'] == 'error':
if 'does not exist' in res['message']:
raise HTTPError(404, reason=res['message'])
elif 'User does not have access to study' in res['message']:
raise HTTPError(403, reason=res['message'])
else:
raise HTTPError(500, reason=res['message'])
categories = res['categories']
columns, rows = _build_sample_summary(study_id, email)
_, alert_type, alert_msg = get_sample_template_processing_status(
study_id)
self.render('study_ajax/sample_prep_summary.html',
rows=rows, columns=columns, categories=categories,
study_id=study_id, alert_type=alert_type,
alert_message=alert_msg,
user_can_edit=Study(study_id).can_edit(self.current_user))
@authenticated
def post(self):
study_id = int(self.get_argument('study_id'))
meta_col = self.get_argument('meta_col')
values = sample_template_category_get_req(meta_col, study_id,
self.current_user.id)
if values['status'] != 'success':
self.write(values)
else:
self.write({'status': 'success',
'message': '',
'values': values['values']
})
|
biocore/qiita
|
qiita_pet/handlers/study_handlers/sample_template.py
|
Python
|
bsd-3-clause
| 19,340
|
/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the 2-clause BSD license.
* See license.txt in the OpenLayers distribution or repository for the
* full text of the license. */
/**
* @requires OpenLayers/Tile.js
* @requires OpenLayers/Animation.js
* @requires OpenLayers/Util.js
*/
/**
* Class: OpenLayers.Tile.Image
* Instances of OpenLayers.Tile.Image are used to manage the image tiles
* used by various layers. Create a new image tile with the
* <OpenLayers.Tile.Image> constructor.
*
* Inherits from:
* - <OpenLayers.Tile>
*/
OpenLayers.Tile.Image = OpenLayers.Class(OpenLayers.Tile, {
/**
* APIProperty: events
* {<OpenLayers.Events>} An events object that handles all
* events on the tile.
*
* Register a listener for a particular event with the following syntax:
* (code)
* tile.events.register(type, obj, listener);
* (end)
*
* Supported event types (in addition to the <OpenLayers.Tile> events):
* beforeload - Triggered before an image is prepared for loading, when the
* url for the image is known already. Listeners may call <setImage> on
* the tile instance. If they do so, that image will be used and no new
* one will be created.
*/
/**
* APIProperty: url
* {String} The URL of the image being requested. No default. Filled in by
* layer.getURL() function. May be modified by loadstart listeners.
*/
url: null,
/**
* Property: imgDiv
* {HTMLImageElement} The image for this tile.
*/
imgDiv: null,
/**
* Property: frame
* {DOMElement} The image element is appended to the frame. Any gutter on
* the image will be hidden behind the frame. If no gutter is set,
* this will be null.
*/
frame: null,
/**
* Property: imageReloadAttempts
* {Integer} Attempts to load the image.
*/
imageReloadAttempts: null,
/**
* Property: layerAlphaHack
* {Boolean} True if the png alpha hack needs to be applied on the layer's div.
*/
layerAlphaHack: null,
/**
* Property: asyncRequestId
* {Integer} ID of an request to see if request is still valid. This is a
* number which increments by 1 for each asynchronous request.
*/
asyncRequestId: null,
/**
* APIProperty: maxGetUrlLength
* {Number} If set, requests that would result in GET urls with more
* characters than the number provided will be made using form-encoded
* HTTP POST. It is good practice to avoid urls that are longer than 2048
* characters.
*
* Caution:
* Older versions of Gecko based browsers (e.g. Firefox < 3.5) and most
* Opera versions do not fully support this option. On all browsers,
* transition effects are not supported if POST requests are used.
*/
maxGetUrlLength: null,
/**
* Property: canvasContext
* {CanvasRenderingContext2D} A canvas context associated with
* the tile image.
*/
canvasContext: null,
/**
* APIProperty: crossOriginKeyword
* The value of the crossorigin keyword to use when loading images. This is
* only relevant when using <getCanvasContext> for tiles from remote
* origins and should be set to either 'anonymous' or 'use-credentials'
* for servers that send Access-Control-Allow-Origin headers with their
* tiles.
*/
crossOriginKeyword: null,
/** TBD 3.0 - reorder the parameters to the init function to remove
* URL. the getUrl() function on the layer gets called on
* each draw(), so no need to specify it here.
*/
/**
* Constructor: OpenLayers.Tile.Image
* Constructor for a new <OpenLayers.Tile.Image> instance.
*
* Parameters:
* layer - {<OpenLayers.Layer>} layer that the tile will go in.
* position - {<OpenLayers.Pixel>}
* bounds - {<OpenLayers.Bounds>}
* url - {<String>} Deprecated. Remove me in 3.0.
* size - {<OpenLayers.Size>}
* options - {Object}
*/
initialize: function (layer, position, bounds, url, size, options) {
OpenLayers.Tile.prototype.initialize.apply(this, arguments);
this.url = url; //deprecated remove me
this.layerAlphaHack = this.layer.alpha && OpenLayers.Util.alphaHack();
if (this.maxGetUrlLength != null || this.layer.gutter || this.layerAlphaHack) {
// only create frame if it's needed
this.frame = document.createElement("div");
this.frame.style.position = "absolute";
this.frame.style.overflow = "hidden";
}
if (this.maxGetUrlLength != null) {
OpenLayers.Util.extend(this, OpenLayers.Tile.Image.IFrame);
}
},
/**
* APIMethod: destroy
* nullify references to prevent circular references and memory leaks
*/
destroy: function () {
if (this.imgDiv) {
this.clear();
this.imgDiv = null;
this.frame = null;
}
// don't handle async requests any more
this.asyncRequestId = null;
OpenLayers.Tile.prototype.destroy.apply(this, arguments);
},
/**
* Method: draw
* Check that a tile should be drawn, and draw it.
*
* Returns:
* {Boolean} Was a tile drawn? Or null if a beforedraw listener returned
* false.
*/
draw: function () {
var shouldDraw = OpenLayers.Tile.prototype.draw.apply(this, arguments);
if (shouldDraw) {
// The layer's reproject option is deprecated.
if (this.layer != this.layer.map.baseLayer && this.layer.reproject) {
// getBoundsFromBaseLayer is defined in deprecated.js.
this.bounds = this.getBoundsFromBaseLayer(this.position);
}
if (this.isLoading) {
//if we're already loading, send 'reload' instead of 'loadstart'.
this._loadEvent = "reload";
} else {
this.isLoading = true;
this._loadEvent = "loadstart";
}
this.renderTile();
this.positionTile();
} else if (shouldDraw === false) {
this.unload();
}
return shouldDraw;
},
/**
* Method: renderTile
* Internal function to actually initialize the image tile,
* position it correctly, and set its url.
*/
renderTile: function () {
if (this.layer.async) {
// Asynchronous image requests call the asynchronous getURL method
// on the layer to fetch an image that covers 'this.bounds'.
var id = this.asyncRequestId = (this.asyncRequestId || 0) + 1;
this.layer.getURLasync(this.bounds, function (url) {
if (id == this.asyncRequestId) {
this.url = url;
this.initImage();
}
}, this);
} else {
// synchronous image requests get the url immediately.
this.url = this.layer.getURL(this.bounds);
this.initImage();
}
},
/**
* Method: positionTile
* Using the properties currenty set on the layer, position the tile correctly.
* This method is used both by the async and non-async versions of the Tile.Image
* code.
*/
positionTile: function () {
var style = this.getTile().style,
size = this.frame ? this.size :
this.layer.getImageSize(this.bounds),
ratio = 1;
if (this.layer instanceof OpenLayers.Layer.Grid) {
ratio = this.layer.getServerResolution() / this.layer.map.getResolution();
}
style.left = this.position.x + "px";
style.top = this.position.y + "px";
style.width = Math.round(ratio * size.w) + "px";
style.height = Math.round(ratio * size.h) + "px";
},
/**
* Method: clear
* Remove the tile from the DOM, clear it of any image related data so that
* it can be reused in a new location.
*/
clear: function () {
OpenLayers.Tile.prototype.clear.apply(this, arguments);
var img = this.imgDiv;
if (img) {
var tile = this.getTile();
if (tile.parentNode === this.layer.div) {
this.layer.div.removeChild(tile);
}
this.setImgSrc();
if (this.layerAlphaHack === true) {
img.style.filter = "";
}
OpenLayers.Element.removeClass(img, "olImageLoadError");
}
this.canvasContext = null;
},
/**
* Method: getImage
* Returns or creates and returns the tile image.
*/
getImage: function () {
if (!this.imgDiv) {
this.imgDiv = OpenLayers.Tile.Image.IMAGE.cloneNode(false);
var style = this.imgDiv.style;
if (this.frame) {
var left = 0, top = 0;
if (this.layer.gutter) {
left = this.layer.gutter / this.layer.tileSize.w * 100;
top = this.layer.gutter / this.layer.tileSize.h * 100;
}
style.left = -left + "%";
style.top = -top + "%";
style.width = (2 * left + 100) + "%";
style.height = (2 * top + 100) + "%";
}
style.visibility = "hidden";
style.opacity = 0;
if (this.layer.opacity < 1) {
style.filter = 'alpha(opacity=' +
(this.layer.opacity * 100) +
')';
}
style.position = "absolute";
if (this.layerAlphaHack) {
// move the image out of sight
style.paddingTop = style.height;
style.height = "0";
style.width = "100%";
}
if (this.frame) {
this.frame.appendChild(this.imgDiv);
}
}
return this.imgDiv;
},
/**
* APIMethod: setImage
* Sets the image element for this tile. This method should only be called
* from beforeload listeners.
*
* Parameters
* img - {HTMLImageElement} The image to use for this tile.
*/
setImage: function (img) {
this.imgDiv = img;
},
/**
* Method: initImage
* Creates the content for the frame on the tile.
*/
initImage: function () {
if (!this.url && !this.imgDiv) {
// fast path out - if there is no tile url and no previous image
this.isLoading = false;
return;
}
this.events.triggerEvent('beforeload');
this.layer.div.appendChild(this.getTile());
this.events.triggerEvent(this._loadEvent);
var img = this.getImage();
var src = img.getAttribute('src') || '';
if (this.url && OpenLayers.Util.isEquivalentUrl(src, this.url)) {
this._loadTimeout = window.setTimeout(
OpenLayers.Function.bind(this.onImageLoad, this), 0
);
} else {
this.stopLoading();
if (this.crossOriginKeyword) {
img.removeAttribute("crossorigin");
}
OpenLayers.Event.observe(img, "load",
OpenLayers.Function.bind(this.onImageLoad, this)
);
OpenLayers.Event.observe(img, "error",
OpenLayers.Function.bind(this.onImageError, this)
);
this.imageReloadAttempts = 0;
this.setImgSrc(this.url);
}
},
/**
* Method: setImgSrc
* Sets the source for the tile image
*
* Parameters:
* url - {String} or undefined to hide the image
*/
setImgSrc: function (url) {
var img = this.imgDiv;
if (url) {
img.style.visibility = 'hidden';
img.style.opacity = 0;
// don't set crossOrigin if the url is a data URL
if (this.crossOriginKeyword) {
if (url.substr(0, 5) !== 'data:') {
img.setAttribute("crossorigin", this.crossOriginKeyword);
} else {
img.removeAttribute("crossorigin");
}
}
img.src = url;
} else {
// Remove reference to the image, and leave it to the browser's
// caching and garbage collection.
this.stopLoading();
this.imgDiv = null;
if (img.parentNode) {
img.parentNode.removeChild(img);
}
}
},
/**
* Method: getTile
* Get the tile's markup.
*
* Returns:
* {DOMElement} The tile's markup
*/
getTile: function () {
return this.frame ? this.frame : this.getImage();
},
/**
* Method: createBackBuffer
* Create a backbuffer for this tile. A backbuffer isn't exactly a clone
* of the tile's markup, because we want to avoid the reloading of the
* image. So we clone the frame, and steal the image from the tile.
*
* Returns:
* {DOMElement} The markup, or undefined if the tile has no image
* or if it's currently loading.
*/
createBackBuffer: function () {
if (!this.imgDiv || this.isLoading) {
return;
}
var backBuffer;
if (this.frame) {
backBuffer = this.frame.cloneNode(false);
backBuffer.appendChild(this.imgDiv);
} else {
backBuffer = this.imgDiv;
}
this.imgDiv = null;
return backBuffer;
},
/**
* Method: onImageLoad
* Handler for the image onload event
*/
onImageLoad: function () {
var img = this.imgDiv;
this.stopLoading();
img.style.visibility = 'inherit';
img.style.opacity = this.layer.opacity;
this.isLoading = false;
this.canvasContext = null;
this.events.triggerEvent("loadend");
if (this.layerAlphaHack === true) {
img.style.filter =
"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" +
img.src + "', sizingMethod='scale')";
}
},
/**
* Method: onImageError
* Handler for the image onerror event
*/
onImageError: function () {
var img = this.imgDiv;
if (img.src != null) {
this.imageReloadAttempts++;
if (this.imageReloadAttempts <= OpenLayers.IMAGE_RELOAD_ATTEMPTS) {
this.setImgSrc(this.layer.getURL(this.bounds));
} else {
OpenLayers.Element.addClass(img, "olImageLoadError");
this.events.triggerEvent("loaderror");
this.onImageLoad();
}
}
},
/**
* Method: stopLoading
* Stops a loading sequence so <onImageLoad> won't be executed.
*/
stopLoading: function () {
OpenLayers.Event.stopObservingElement(this.imgDiv);
window.clearTimeout(this._loadTimeout);
delete this._loadTimeout;
},
/**
* APIMethod: getCanvasContext
* Returns a canvas context associated with the tile image (with
* the image drawn on it).
* Returns undefined if the browser does not support canvas, if
* the tile has no image or if it's currently loading.
*
* The function returns a canvas context instance but the
* underlying canvas is still available in the 'canvas' property:
* (code)
* var context = tile.getCanvasContext();
* if (context) {
* var data = context.canvas.toDataURL('image/jpeg');
* }
* (end)
*
* Returns:
* {Boolean}
*/
getCanvasContext: function () {
if (OpenLayers.CANVAS_SUPPORTED && this.imgDiv && !this.isLoading) {
if (!this.canvasContext) {
var canvas = document.createElement("canvas");
canvas.width = this.size.w;
canvas.height = this.size.h;
this.canvasContext = canvas.getContext("2d");
this.canvasContext.drawImage(this.imgDiv, 0, 0);
}
return this.canvasContext;
}
},
CLASS_NAME: "OpenLayers.Tile.Image"
});
/**
* Constant: OpenLayers.Tile.Image.IMAGE
* {HTMLImageElement} The image for a tile.
*/
OpenLayers.Tile.Image.IMAGE = (function () {
var img = new Image();
img.className = "olTileImage";
// avoid image gallery menu in IE6
img.galleryImg = "no";
return img;
}());
|
girc/dmis
|
common/asset-files/openlayers/ol2/lib/OpenLayers/Tile/Image.js
|
JavaScript
|
bsd-3-clause
| 16,702
|
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
namespace CefSharp
{
/// <summary>
/// Event arguments to the NavStateChanged event handler set up in IWebBrowser.
/// </summary>
public class NavStateChangedEventArgs : EventArgs
{
public bool CanGoForward { get; private set; }
public bool CanGoBack { get; private set; }
public bool CanReload { get; private set; }
public NavStateChangedEventArgs(bool canGoBack, bool canGoForward, bool canReload)
{
CanGoBack = canGoBack;
CanGoForward = canGoForward;
CanReload = canReload;
}
}
}
|
dreamsxin/CefSharp-37.0.0
|
CefSharp/NavStateChangedEventArgs.cs
|
C#
|
bsd-3-clause
| 784
|
# SHBiasKMask
Calculate the multitaper (cross-)power spectrum expectation of a function localized by arbitrary windows derived from a mask.
# Usage
`outcspectra` = SHBiasK (`tapers`, `incspectra`, [`lwin`, `k`, `ldata`, `taper_wt`, `save_cg`])
# Returns
`outcspectra` : float, dimension (`ldata`+`lwin`+1)
: The expectation of the multitaper localized power spectrum.
# Parameters
`tapers` : float, dimension ((`lwinin`+1)**2, `kin`)
: The spherical harmonic coefficients of the localization windows generated by a call to `SHReturnTapersMap`. The coefficients in each column are ordered according to the convention in `SHCilmToVector`.
`incspectra` : float, dimension (`ldatain`+1)
: The global unwindowed power spectrum.
`lwin` : optional, integer, default = `lwinin`
: The spherical harmonic bandwidth of the localizing windows.
`k` : optional, integer, default = `kin`
: The number of localization windows to use. Only the first `k` columns of `tapers` will be employed, which corresponds to the best-concentrated windows.
`ldata` : optional, integer, default = `ldatain`
: The maximum degree of the global unwindowed power spectrum.
`taper_wt` : optional, float, dimension (`kin`), default = -1
: The weights to apply to each individual windowed specral estimate. The weights must sum to unity, and the default specifies that taper weights are not used.
`save_cg` : optional, integer, default = 0
: If set equal to 1, the Clebsch-Gordon coefficients will be precomputed and saved for future use (if `lwin` or `ldata` change, these will be recomputed). To deallocate the saved memory, set this parameter equal to 1. If set equal to 0 (default), the Clebsch-Gordon coefficients will be recomputed for each call.
# Description
`SHBiasKMask` will calculate the multitaper (cross-)power spectrum expectation of a function multiplied by the `k` best-concentrated localization windows derived from an arbitrary mask. This is given by equation 36 of Wieczorek and Simons (2005) (see also eq. 2.11 of Wieczorek and Simons 2007). In contrast to `SHBias`, which takes as input the power spectrum of a single localizing window, this routine expects as input a matrix containing the spherical harmonic coefficients of the localizing windows. These can be generated by a call to `SHReturnTapersMap` and the coefficients in each column are ordered according to the convention in `SHCilmToVector`.
It is assumed implicitly that the power spectrum of `inspectrum` is zero beyond degree `ldata`. If this is not the case, the ouput power spectrum should be considered valid only for the degrees up to and including `ldata` - `lwin`.
The default is to apply equal weights to each individual windowed estimate of the spectrum, but this can be modified by specifying the weights in the optional argument `taper_wt`. The weights must sum to unity. If this routine is to be called several times using the same values of `lwin` and `ldata`, then the Clebsch-Gordon coefficients can be precomputed and saved by setting the optional parameter `save_cg` equal to 1.
# References
Wieczorek, M. A. and F. J. Simons, Minimum-variance multitaper spectral estimation on the sphere, J. Fourier Anal. Appl., 13, 665-692, doi:10.1007/s00041-006-6904-1, 2007.
Simons, F. J., F. A. Dahlen and M. A. Wieczorek, Spatiospectral concentration on a sphere, SIAM Review, 48, 504-536, doi:10.1137/S0036144504445765, 2006.
Wieczorek, M. A. and F. J. Simons, Localized spectral analysis on the sphere,
Geophys. J. Int., 162, 655-675, doi:10.1111/j.1365-246X.2005.02687.x, 2005.
# See also
[shbias](pyshbias.html), [shreturntapersmap](pyshreturntapersmap.html), [shmtcouplingmatrix](pyshmtcouplingmatrix.html)
|
MMesch/SHTOOLS
|
src/pydoc/pyshbiaskmask.md
|
Markdown
|
bsd-3-clause
| 3,708
|
/*
* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef VBOOT_REFERENCE_FUTILITY_H_
#define VBOOT_REFERENCE_FUTILITY_H_
#include <stdint.h>
#include "vboot_common.h"
#include "gbb_header.h"
#include "host_key.h"
/* This program */
#define MYNAME "futility"
/* Version string (autogenerated) */
extern const char futility_version[];
/* Bitfields indicating the struct/format versions supported by a command */
enum vboot_version {
/*
* v1.0 is the original structs used since the dawn of time.
* v2.0 can verify the firmware in smaller chunks, but there's
* no difference in the on-device structs, so it's only
* meaningful for the firmware API. Futility doesn't care.
*/
VBOOT_VERSION_1_0 = 0x00000001,
/*
* v2.1 uses new and different structs, and is what v2.0 would have
* been if someone hadn't started using it before it was ready.
*/
VBOOT_VERSION_2_1 = 0x00000002,
/*
* Everything we know about to date.
*/
VBOOT_VERSION_ALL = 0x00000003,
};
/* What's our preferred API & data format? */
enum vboot_version vboot_version;
/* Here's a structure to define the commands that futility implements. */
struct futil_cmd_t {
const char *const name;
int (*const handler) (int argc, char **argv);
enum vboot_version version;
const char *const shorthelp;
void (*longhelp) (const char *cmd);
};
/* Macro to define a command */
#define DECLARE_FUTIL_COMMAND(NAME, HANDLER, VERSION, SHORTHELP, LONGHELP) \
const struct futil_cmd_t __cmd_##NAME = { \
.name = #NAME, \
.handler = HANDLER, \
.version = VERSION, \
.shorthelp = SHORTHELP, \
.longhelp = LONGHELP, \
}
/* This is the list of pointers to all commands. */
extern const struct futil_cmd_t *const futil_cmds[];
/* Size of an array */
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(array) (sizeof(array)/sizeof(array[0]))
#endif
/* Test an important condition at compile time, not run time */
#ifndef BUILD_ASSERT
#define _BA1_(cond, line) \
extern int __build_assertion_ ## line[1 - 2*!(cond)] \
__attribute__ ((unused))
#define _BA0_(c, x) _BA1_(c, x)
#define BUILD_ASSERT(cond) _BA0_(cond, __LINE__)
#endif
/* Fatal internal stupidness */
#ifndef DIE
#define DIE do { \
fprintf(stderr, MYNAME ": internal error at %s:%d\n", \
__FILE__, __LINE__); \
exit(1); \
} while (0)
#endif
/* Debug output (off by default) */
extern int debugging_enabled;
void Debug(const char *format, ...);
/* Returns true if this looks enough like a GBB header to proceed. */
int futil_looks_like_gbb(GoogleBinaryBlockHeader *gbb, uint32_t len);
/*
* Returns true if the gbb header is valid (and optionally updates *maxlen).
* This doesn't verify the contents, though.
*/
int futil_valid_gbb_header(GoogleBinaryBlockHeader *gbb, uint32_t len,
uint32_t *maxlen);
/* For GBB v1.2 and later, update the hwid_digest */
void update_hwid_digest(GoogleBinaryBlockHeader *gbb);
/* For GBB v1.2 and later, print the stored digest of the HWID (and whether
* it's correct). Return true if it is correct. */
int print_hwid_digest(GoogleBinaryBlockHeader *gbb,
const char *banner, const char *footer);
/* Copies a file or dies with an error message */
void futil_copy_file_or_die(const char *infile, const char *outfile);
/* Possible file operation errors */
enum futil_file_err {
FILE_ERR_NONE,
FILE_ERR_STAT,
FILE_ERR_SIZE,
FILE_ERR_MMAP,
FILE_ERR_MSYNC,
FILE_ERR_MUNMAP,
FILE_ERR_OPEN,
FILE_ERR_CLOSE,
FILE_ERR_DIR,
FILE_ERR_CHR,
FILE_ERR_FIFO,
FILE_ERR_SOCK,
};
/* Wrapper for mmap/munmap. Skips stupidly large files. */
#define MAP_RO 0
#define MAP_RW 1
enum futil_file_err futil_map_file(int fd, int writeable,
uint8_t **buf, uint32_t *len);
enum futil_file_err futil_unmap_file(int fd, int writeable,
uint8_t *buf, uint32_t len);
/* The CPU architecture is occasionally important */
enum arch_t {
ARCH_UNSPECIFIED,
ARCH_X86,
ARCH_ARM,
ARCH_MIPS
};
#endif /* VBOOT_REFERENCE_FUTILITY_H_ */
|
geekboxzone/mmallow_external_vboot_reference
|
futility/futility.h
|
C
|
bsd-3-clause
| 4,097
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE690_NULL_Deref_From_Return__long_malloc_54c.c
Label Definition File: CWE690_NULL_Deref_From_Return.free.label.xml
Template File: source-sinks-54c.tmpl.c
*/
/*
* @description
* CWE: 690 Unchecked Return Value To NULL Pointer
* BadSource: malloc Allocate data using malloc()
* Sinks:
* GoodSink: Check to see if the data allocation failed and if not, use data
* BadSink : Don't check for NULL and use data
* Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifndef OMITBAD
/* bad function declaration */
void CWE690_NULL_Deref_From_Return__long_malloc_54d_badSink(long * data);
void CWE690_NULL_Deref_From_Return__long_malloc_54c_badSink(long * data)
{
CWE690_NULL_Deref_From_Return__long_malloc_54d_badSink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G uses the BadSource with the GoodSink */
void CWE690_NULL_Deref_From_Return__long_malloc_54d_goodB2GSink(long * data);
void CWE690_NULL_Deref_From_Return__long_malloc_54c_goodB2GSink(long * data)
{
CWE690_NULL_Deref_From_Return__long_malloc_54d_goodB2GSink(data);
}
#endif /* OMITGOOD */
|
JianpingZeng/xcc
|
xcc/test/juliet/testcases/CWE690_NULL_Deref_From_Return/s01/CWE690_NULL_Deref_From_Return__long_malloc_54c.c
|
C
|
bsd-3-clause
| 1,334
|
''' Provide special versions of list and dict, that can automatically notify
about changes when used for property values.
Mutations to these values are detected, and the properties owning the
collection is notified of the changes. Consider the following model
definition:
.. code-block:: python
class SomeModel(Model):
options = List(String)
If we have an instance of this model, ``m`` then we can set the entire
value of the ``options`` property at once:
.. code-block:: python
m.options = ["foo", "bar"]
When we do this in the context of a Bokeh server application that is being
viewed in a browser, this change is automatically noticed, and the
corresponding BokehJS property in the browser is synchronized, possibly
causing some change in the visual state of the application in the browser.
But it is also desirable that changes *inside* the ``options`` list also
be detected. That is, the following kinds of operations should also be
automatically synchronized between BokehJS and a Bokeh server:
.. code-block:: python
m.options.append("baz")
m.options[2] = "quux"
m.options.insert(0, "bar")
The classes in this module provide this functionality.
.. note::
These classes form part of the very low-level machinery that implements
the Bokeh model and property system. It is unlikely that any of these
classes or their methods will be applicable to any standard usage or to
anyone who is not directly developing on Bokeh's own infrastructure.
'''
from __future__ import absolute_import, print_function
from ...util.dependencies import import_optional
pd = import_optional('pandas')
def notify_owner(func):
''' A decorator for mutating methods of property container classes
that notifies owners of the property container about mutating changes.
Args:
func (callable) : the container method to wrap in a notification
Returns:
wrapped method
Examples:
A ``__setitem__`` could be wrapped like this:
.. code-block:: python
# x[i] = y
@notify_owner
def __setitem__(self, i, y):
return super(PropertyValueDict, self).__setitem__(i, y)
The returned wrapped method will have a docstring indicating what
original method it is wrapping.
'''
def wrapper(self, *args, **kwargs):
old = self._saved_copy()
result = func(self, *args, **kwargs)
self._notify_owners(old)
return result
wrapper.__doc__ = "Container method ``%s`` instrumented to notify property owners" % func.__name__
return wrapper
class PropertyValueContainer(object):
''' A base class for property container classes that support change
notifications on mutating operations.
This class maintains an internal list of property owners, and also
provides a private mechanism for methods wrapped with
:func:`~bokeh.core.property_containers.notify_owners` to update
those owners when mutating changes occur.
'''
def __init__(self, *args, **kwargs):
self._owners = set()
super(PropertyValueContainer, self).__init__(*args, **kwargs)
def _register_owner(self, owner, descriptor):
self._owners.add((owner, descriptor))
def _unregister_owner(self, owner, descriptor):
self._owners.discard((owner, descriptor))
def _notify_owners(self, old, hint=None):
for (owner, descriptor) in self._owners:
descriptor._notify_mutated(owner, old, hint=hint)
def _saved_copy(self):
raise RuntimeError("Subtypes must implement this to make a backup copy")
class PropertyValueList(PropertyValueContainer, list):
''' A list property value container that supports change notifications on
mutating operations.
When a Bokeh model has a ``List`` property, the ``PropertyValueLists`` are
transparently created to wrap those values. These ``PropertyValueList``
values are subject to normal property validation. If the property type
``foo = List(Str)`` then attempting to set ``x.foo[0] = 10`` will raise
an error.
Instances of ``PropertyValueList`` can be explicitly created by passing
any object that the standard list initializer accepts, for example:
.. code-block:: python
>>> PropertyValueList([10, 20])
[10, 20]
>>> PropertyValueList((10, 20))
[10, 20]
The following mutating operations on lists automatically trigger
notifications:
.. code-block:: python
del x[y]
del x[i:j]
x += y
x *= y
x[i] = y
x[i:j] = y
x.append
x.extend
x.insert
x.pop
x.remove
x.reverse
x.sort
'''
def __init__(self, *args, **kwargs):
return super(PropertyValueList, self).__init__(*args, **kwargs)
def _saved_copy(self):
return list(self)
# delete x[y]
@notify_owner
def __delitem__(self, y):
return super(PropertyValueList, self).__delitem__(y)
# delete x[i:j]
@notify_owner
def __delslice__(self, i, j):
# Note: this is different py2 vs py3, py3 calls __delitem__ with a
# slice index, and does not have this method at all
return super(PropertyValueList, self).__delslice__(i, j)
# x += y
@notify_owner
def __iadd__(self, y):
return super(PropertyValueList, self).__iadd__(y)
# x *= y
@notify_owner
def __imul__(self, y):
return super(PropertyValueList, self).__imul__(y)
# x[i] = y
@notify_owner
def __setitem__(self, i, y):
return super(PropertyValueList, self).__setitem__(i, y)
# x[i:j] = y
@notify_owner
def __setslice__(self, i, j, y):
# Note: this is different py2 vs py3, py3 calls __setitem__ with a
# slice index, and does not have this method at all
return super(PropertyValueList, self).__setslice__(i, j, y)
@notify_owner
def append(self, obj):
return super(PropertyValueList, self).append(obj)
@notify_owner
def extend(self, iterable):
return super(PropertyValueList, self).extend(iterable)
@notify_owner
def insert(self, index, obj):
return super(PropertyValueList, self).insert(index, obj)
@notify_owner
def pop(self, index=-1):
return super(PropertyValueList, self).pop(index)
@notify_owner
def remove(self, obj):
return super(PropertyValueList, self).remove(obj)
@notify_owner
def reverse(self):
return super(PropertyValueList, self).reverse()
@notify_owner
def sort(self, **kwargs):
return super(PropertyValueList, self).sort(**kwargs)
class PropertyValueDict(PropertyValueContainer, dict):
''' A dict property value container that supports change notifications on
mutating operations.
When a Bokeh model has a ``List`` property, the ``PropertyValueLists`` are
transparently created to wrap those values. These ``PropertyValueList``
values are subject to normal property validation. If the property type
``foo = Dict(Str, Str)`` then attempting to set ``x.foo['bar'] = 10`` will
raise an error.
Instances of ``PropertyValueDict`` can be eplicitly created by passing
any object that the standard dict initializer accepts, for example:
.. code-block:: python
>>> PropertyValueDict(dict(a=10, b=20))
{'a': 10, 'b': 20}
>>> PropertyValueDict(a=10, b=20)
{'a': 10, 'b': 20}
>>> PropertyValueDict([('a', 10), ['b', 20]])
{'a': 10, 'b': 20}
The following mutating operations on dicts automatically trigger
notifications:
.. code-block:: python
del x[y]
x[i] = y
x.clear
x.pop
x.popitem
x.setdefault
x.update
'''
def __init__(self, *args, **kwargs):
return super(PropertyValueDict, self).__init__(*args, **kwargs)
def _saved_copy(self):
return dict(self)
# delete x[y]
@notify_owner
def __delitem__(self, y):
return super(PropertyValueDict, self).__delitem__(y)
# x[i] = y
@notify_owner
def __setitem__(self, i, y):
return super(PropertyValueDict, self).__setitem__(i, y)
@notify_owner
def clear(self):
return super(PropertyValueDict, self).clear()
@notify_owner
def pop(self, *args):
return super(PropertyValueDict, self).pop(*args)
@notify_owner
def popitem(self):
return super(PropertyValueDict, self).popitem()
@notify_owner
def setdefault(self, *args):
return super(PropertyValueDict, self).setdefault(*args)
@notify_owner
def update(self, *args, **kwargs):
return super(PropertyValueDict, self).update(*args, **kwargs)
class PropertyValueColumnData(PropertyValueDict):
''' A property value container for ColumnData that supports change
notifications on mutating operations.
This property value container affords specialized code paths for
updating the .data dictionary for ColumnDataSource. When possible,
more efficient ColumnDataChangedEvent hints are generated to perform
the updates:
.. code-block:: python
x[i] = y
x.update
'''
# x[i] = y
# don't wrap with notify_owner --- notifies owners explicitly
def __setitem__(self, i, y):
return self.update([(i, y)])
# don't wrap with notify_owner --- notifies owners explicitly
def update(self, *args, **kwargs):
old = self._saved_copy()
result = super(PropertyValueDict, self).update(*args, **kwargs)
from ...document.events import ColumnDataChangedEvent
# Grab keys to update according to Python docstring for update([E, ]**F)
#
# If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
# If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
# In either case, this is followed by: for k in F: D[k] = F[k]
cols = set(kwargs.keys())
if len(args) == 1:
E = args[0]
if hasattr(E, 'keys'):
cols |= set(E.keys())
else:
cols |= { x[0] for x in E }
# we must loop ourselves here instead of calling _notify_owners
# because the hint is customized for each owner separately
for (owner, descriptor) in self._owners:
hint = ColumnDataChangedEvent(owner.document, owner, cols=list(cols))
descriptor._notify_mutated(owner, old, hint=hint)
return result
# don't wrap with notify_owner --- notifies owners explicitly
def _stream(self, doc, source, new_data, rollover=None, setter=None):
''' Internal implementation to handle special-casing stream events
on ``ColumnDataSource`` columns.
Normally any changes to the ``.data`` dict attribute on a
``ColumnDataSource`` triggers a notification, causing all of the data
to be synchronized between server and clients.
The ``.stream`` method on column data sources exists to provide a
more efficient way to perform streaming (i.e. append-only) updates
to a data source, without having to perform a full synchronization,
which would needlessly re-send all the data.
To accomplish this, this function bypasses the wrapped methods on
``PropertyValueDict`` and uses the unwrapped versions on the dict
superclass directly. It then explicitly makes a notification, adding
a special ``ColumnsStreamedEvent`` hint to the message containing
only the small streamed data that BokehJS needs in order to
efficiently synchronize.
.. warning::
This function assumes the integrity of ``new_data`` has already
been verified.
'''
old = self._saved_copy()
import numpy as np
# TODO (bev) Currently this reports old differently for array vs list
# For arrays is reports the actual old value. For lists, the old value
# is actually the already updated value. This is because the method
# self._saved_copy() makes a shallow copy.
for k, v in new_data.items():
if isinstance(self[k], np.ndarray) or isinstance(new_data[k], np.ndarray):
data = np.append(self[k], new_data[k])
if rollover and len(data) > rollover:
data = data[-rollover:]
super(PropertyValueDict, self).__setitem__(k, data)
else:
L = self[k]
L.extend(new_data[k])
if rollover is not None:
del L[:-rollover]
from ...document.events import ColumnsStreamedEvent
self._notify_owners(old,
hint=ColumnsStreamedEvent(doc, source, new_data, rollover, setter))
# don't wrap with notify_owner --- notifies owners explicitly
def _patch(self, doc, source, patches, setter=None):
''' Internal implementation to handle special-casing patch events
on ``ColumnDataSource`` columns.
Normally any changes to the ``.data`` dict attribute on a
``ColumnDataSource`` triggers a notification, causing all of the data
to be synchronized between server and clients.
The ``.patch`` method on column data sources exists to provide a
more efficient way to perform patching (i.e. random access) updates
to a data source, without having to perform a full synchronization,
which would needlessly re-send all the data.
To accomplish this, this function bypasses the wrapped methods on
``PropertyValueDict`` and uses the unwrapped versions on the dict
superclass directly. It then explicitly makes a notification, adding
a special ``ColumnsPatchedEvent`` hint to the message containing
only the small patched data that BokehJS needs in order to efficiently
synchronize.
.. warning::
This function assumes the integrity of ``patches`` has already
been verified.
'''
import numpy as np
old = self._saved_copy()
for name, patch in patches.items():
for ind, value in patch:
if isinstance(ind, (int, slice)):
self[name][ind] = value
else:
shape = self[name][ind[0]][ind[1:]].shape
self[name][ind[0]][ind[1:]] = np.array(value, copy=False).reshape(shape)
from ...document.events import ColumnsPatchedEvent
self._notify_owners(old,
hint=ColumnsPatchedEvent(doc, source, patches, setter))
|
Karel-van-de-Plassche/bokeh
|
bokeh/core/property/containers.py
|
Python
|
bsd-3-clause
| 14,792
|
# Copyright (c) 2009-2010 Six Apart Ltd.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of Six Apart Ltd. nor the names of its contributors may
# be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
`DataObject` is a class of object that provides coding between object
attributes and dictionaries, suitable for
In `DataObject` is the mechanism for converting between dictionaries and
objects. These conversions are performed with aid of `Field` instances
declared on `DataObject` subclasses. `Field` classes reside in the
`remoteobjects.field` module.
"""
from copy import deepcopy
import logging
import remoteobjects.fields
classes_by_name = {}
classes_by_constant_field = {}
def find_by_name(name):
"""Finds and returns the DataObject subclass with the given name.
Parameter `name` should be a bare class name with no module. If there is
no class by that name, raises `KeyError`.
"""
return classes_by_name[name]
class DataObjectMetaclass(type):
"""Metaclass for `DataObject` classes.
This metaclass installs all `remoteobjects.fields.Property` instances
declared as attributes of the new class, including all `Field` and `Link`
instances.
This metaclass also makes the new class findable through the
`dataobject.find_by_name()` function.
"""
def __new__(cls, name, bases, attrs):
"""Creates and returns a new `DataObject` class with its declared
fields and name."""
fields = {}
new_fields = {}
new_properties = {}
# Inherit all the parent DataObject classes' fields.
for base in bases:
if isinstance(base, DataObjectMetaclass):
fields.update(base.fields)
# Move all the class's attributes that are Fields to the fields set.
for attrname, field in attrs.items():
if isinstance(field, remoteobjects.fields.Property):
new_properties[attrname] = field
if isinstance(field, remoteobjects.fields.Field):
new_fields[attrname] = field
elif attrname in fields:
# Throw out any parent fields that the subclass defined as
# something other than a Field.
del fields[attrname]
fields.update(new_fields)
attrs['fields'] = fields
obj_cls = super(DataObjectMetaclass, cls).__new__(cls, name, bases, attrs)
for field, value in new_properties.items():
obj_cls.add_to_class(field, value)
# Register the new class so Object fields can have forward-referenced it.
classes_by_name[name] = obj_cls
# Tell this class's fields what this class is, so they can find their
# forward references later.
for field in new_properties.values():
field.of_cls = obj_cls
return obj_cls
def add_to_class(cls, name, value):
try:
value.install(name, cls)
except (NotImplementedError, AttributeError):
setattr(cls, name, value)
class DataObject(object):
"""An object that can be decoded from or encoded as a dictionary.
DataObject subclasses should be declared with their different data
attributes defined as instances of fields from the `remoteobjects.fields`
module. For example:
>>> from remoteobjects import dataobject, fields
>>> class Asset(dataobject.DataObject):
... name = fields.Field()
... updated = fields.Datetime()
... author = fields.Object('Author')
...
A DataObject's fields then provide the coding between live DataObject
instances and dictionaries.
"""
__metaclass__ = DataObjectMetaclass
def __init__(self, **kwargs):
"""Initializes a new `DataObject` with the given field values."""
self.api_data = {}
self.__dict__.update(kwargs)
def __eq__(self, other):
"""Returns whether two `DataObject` instances are equivalent.
If the `DataObject` instances are of the same type and contain the
same data in all their fields, the objects are equivalent.
"""
if type(self) != type(other):
return False
for k, v in self.fields.iteritems():
if isinstance(v, remoteobjects.fields.Field):
if getattr(self, k) != getattr(other, k):
return False
return True
def __ne__(self, other):
"""Returns whether two `DataObject` instances are different.
`DataObject` instances are different if they are not equivalent as
determined through `__eq__()`.
"""
return not self == other
@classmethod
def statefields(cls):
return cls.fields.keys() + ['api_data']
def __getstate__(self):
return dict((k, self.__dict__[k]) for k in self.statefields()
if k in self.__dict__)
def get(self, attr, *args):
return getattr(self, attr, *args)
def __iter__(self):
for key in self.fields.keys():
yield key
def to_dict(self):
"""Encodes the DataObject to a dictionary."""
# Start with the last set of data we got from the API
data = deepcopy(self.api_data)
# Now replace the data with what's actually in our object
for field_name, field in self.fields.iteritems():
value = getattr(self, field.attrname, None)
if value is not None:
data[field.api_name] = field.encode(value)
else:
data[field.api_name] = None
# Now delete any fields that ended up being None
# since we should exclude them in the resulting dict.
for k in data.keys():
if data[k] is None:
del data[k]
return data
@classmethod
def from_dict(cls, data):
"""Decodes a dictionary into a new `DataObject` instance."""
self = cls()
self.update_from_dict(data)
return self
def update_from_dict(self, data):
"""Adds the content of a dictionary to this DataObject.
Parameter `data` is the dictionary from which to update the object.
Use this only when receiving newly updated or partial content for a
DataObject; that is, when the data is from the outside data source and
needs decoded through the object's fields. Data from "inside" your
application should be added to an object manually by setting the
object's attributes. Data that constitutes a new object should be
turned into another object with `from_dict()`.
"""
if not isinstance(data, dict):
raise TypeError
# Clear any local instance field data
for k in self.fields.iterkeys():
if k in self.__dict__:
del self.__dict__[k]
self.api_data = data
@classmethod
def subclass_with_constant_field(cls, fieldname, value):
"""Returns the closest subclass of this class that has a `Constant`
field with the given value.
Use this method in combination with the `fields.Constant` field class
to find the most appropriate subclass of `cls` based on a content
field. For example, if you have an ``Asset`` class, but want to
declare subclasses with special behavior based on the ``kind`` field
of the ``Asset`` instances, declare ``kind`` as a `Constant` field on
each subclass. Then when you want to create a new ``Asset`` instance
(as in ``Asset.from_dict()``), you can use this method to select a
more appropriate class to instantiate.
Parameters `fieldname` and `value` are the name and value of the
`Constant` field for which to search respectively.
If a subclass of `cls` has been declared with a `Constant` field of
the given name and value, it will be returned. If multiple subclasses
of `cls` declare a matching `Constant` field, one of the matching
subclasses will be returned, but which subclass is not defined.
"""
try:
clsname = classes_by_constant_field[fieldname][tuple(value)]
except KeyError:
# No matching classes, then.
pass
else:
return find_by_name(clsname)
raise ValueError('No such subclass of %s with field %r equivalent to %r'
% (cls.__name__, fieldname, value))
|
mozilla/remoteobjects
|
remoteobjects/dataobject.py
|
Python
|
bsd-3-clause
| 9,792
|
<?php
namespace User\Model;
/**
*
* @author nmt
*
*/
class AclWhiteList {
public $id;
public $resource_id;
public $status;
public $created_on;
public function exchangeArray($data) {
$this->id = (! empty ( $data ['id'] )) ? $data ['id'] : null;
$this->resource_id = (! empty ( $data ['resource_id'] )) ? $data ['resource_id'] : null;
$this->status = (! empty ( $data ['resource'] )) ? $data ['type'] : null;
$this->created_on = (! empty ( $data ['created_on'] )) ? $data ['created_on'] : null;
}
}
|
ngmautri/nmt
|
module/User/src/Model/AclWhiteList.php
|
PHP
|
bsd-3-clause
| 551
|
package nginx.clojure.jersey;
import static nginx.clojure.MiniConstants.BODY;
import static nginx.clojure.MiniConstants.HEADERS;
import static nginx.clojure.MiniConstants.NGX_HTTP_INTERNAL_SERVER_ERROR;
import static nginx.clojure.MiniConstants.REQUEST_METHOD;
import static nginx.clojure.MiniConstants.SCHEME;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.SecurityContext;
import nginx.clojure.NginxClojureRT;
import nginx.clojure.NginxHttpServerChannel;
import nginx.clojure.bridge.NginxBridge;
import nginx.clojure.java.NginxJavaRequest;
import org.glassfish.jersey.internal.MapPropertiesDelegate;
import org.glassfish.jersey.server.ApplicationHandler;
import org.glassfish.jersey.server.ContainerException;
import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.ContainerResponse;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.spi.ContainerResponseWriter;
public class NginxJerseyContainer implements NginxBridge {
protected ApplicationHandler appHandler;
protected String appPath;
protected Class[] appResources;
protected ClassLoader bootLoader;
protected ResourceConfig configure() {
return new ResourceConfig(appResources);
}
@Override
public void boot(Map<String, String> properties, ClassLoader loader) {
appPath = properties.get("jersey.app.path");
bootLoader = loader;
if (appPath == null) {
appPath = "";
}
String res = properties.get("jersey.app.resources");
List<Class> clzList = new ArrayList<Class>();
if (res != null) {
for (String clz : res.split(",") ) {
try {
clzList.add(loader.loadClass(clz.trim()));
} catch (Throwable e) {
NginxClojureRT.log.warn("can not load resource %s, skiping", clz, e);
}
}
appResources = clzList.toArray(new Class[clzList.size()]);
}
if (appResources == null || appResources.length == 0){
NginxClojureRT.log.warn("no resource defined, property %s is null", "jersey.app.resources");
}
appHandler = new ApplicationHandler(configure());
}
@Override
public ClassLoader getClassLoader() {
return bootLoader;
}
protected SecurityContext getSecurityContext(final Principal principal, final boolean isSecure) {
return new SecurityContext() {
@Override
public boolean isUserInRole(final String role) {
return false;
}
@Override
public boolean isSecure() {
return isSecure;
}
@Override
public Principal getUserPrincipal() {
return principal;
}
@Override
public String getAuthenticationScheme() {
return null;
}
};
}
public static class NginxReponseWriter implements ContainerResponseWriter {
protected boolean suspend = false;
protected NginxHttpServerChannel sc;
public NginxReponseWriter() {
}
public NginxReponseWriter(NginxHttpServerChannel sc) {
this.sc = sc;
}
@Override
public void commit() {
try {
sc.close();
} catch (IOException e) {
NginxClojureRT.log.error("commit failure!", e);
}
}
@Override
public boolean enableResponseBuffering() {
return true;
}
@Override
public void failure(Throwable e) {
NginxClojureRT.log.error("failure from jersey", e);
try {
sc.sendResponse(NGX_HTTP_INTERNAL_SERVER_ERROR);
} catch (IOException e1) {
NginxClojureRT.log.error("send error response failed!", e);
}
}
@Override
public void setSuspendTimeout(long timeOut, TimeUnit timeUnit)
throws IllegalStateException {
}
@Override
public boolean suspend(long timeOut, TimeUnit timeUnit, TimeoutHandler timeoutHandler) {
return suspend = true;
}
@Override
public OutputStream writeResponseStatusAndHeaders(long contentLength,
ContainerResponse context) throws ContainerException {
try {
sc.sendHeader(context.getStatus(), context.getStringHeaders().entrySet(), true, false);
} catch (IOException e) {
throw new ContainerException("send header error!", e);
}
return new OutputStream() {
@Override
public void write(int b) throws IOException {
write(new byte[]{(byte)b}, 0, 1);
}
@Override
public void write(byte[] b, int off, int len)
throws IOException {
if (b == null) {
throw new NullPointerException("byte[] can not be null");
}
if (off + len > b.length) {
throw new IndexOutOfBoundsException("buffer space is too small, off + len > b.length");
}
sc.send(b, off, len, false, false);
}
@Override
public void flush() throws IOException {
sc.flush();
}
@Override
public void close() throws IOException {
sc.close();
}
};
}
}
@Override
public Object[] handle(NginxJavaRequest req) throws IOException {
final NginxHttpServerChannel sc = req.hijack(false);
Map<String, Object> headers = (Map<String, Object>) req.get(HEADERS);
URI baseUri;
try {
baseUri = new URI(new StringBuilder((String) req.get(SCHEME))
.append("://").append(headers.get("host")).append(appPath)
.append(appPath.endsWith("/") ? "" : "/").toString());
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
URI requestUri = baseUri.resolve(req.getVariable("request_uri"));
ContainerRequest cr = new ContainerRequest(baseUri, requestUri,
((String)req.get(REQUEST_METHOD)).toUpperCase(), getSecurityContext(null, false),
new MapPropertiesDelegate());
cr.setEntityStream((InputStream)req.get(BODY));
MultivaluedMap<String, String> crHeaders = cr.getHeaders();
for (Entry<String, Object> en : headers.entrySet()) {
Object v = en.getValue();
if (v == null) {
continue;
}
if (v.getClass().isArray()) {
crHeaders.put(en.getKey(), Arrays.asList((String[])v));
}else {
crHeaders.putSingle(en.getKey(), (String)v);
}
}
NginxReponseWriter writer = new NginxReponseWriter(sc);
cr.setWriter(writer);
appHandler.handle(cr);
if (!writer.suspend) {
sc.close();
}
return null;
}
}
|
duqiao/nginx-clojure
|
nginx-jersey/src/java/nginx/clojure/jersey/NginxJerseyContainer.java
|
Java
|
bsd-3-clause
| 6,615
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Code Coverage for /Users/eduardojunior/projetos/ieducar2/www/module/Portal/src/Portal/Entity</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="../../../css/bootstrap.min.css" rel="stylesheet">
<link href="../../../css/style.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="../../../js/html5shiv.min.js"></script>
<script src="../../../js/respond.min.js"></script>
<![endif]-->
</head>
<body>
<header>
<div class="container">
<div class="row">
<div class="col-md-12">
<ol class="breadcrumb">
<li><a href="../../../index.html">/Users/eduardojunior/projetos/ieducar2/www/module/Portal</a></li>
<li><a href="../../index.html">src</a></li>
<li><a href="../index.html">Portal</a></li>
<li class="active">Entity</li>
<li>(<a href="dashboard.html">Dashboard</a>)</li>
</ol>
</div>
</div>
</div>
</header>
<div class="container">
<table class="table table-bordered">
<thead>
<tr>
<td> </td>
<td colspan="9"><div align="center"><strong>Code Coverage</strong></div></td>
</tr>
<tr>
<td> </td>
<td colspan="3"><div align="center"><strong>Lines</strong></div></td>
<td colspan="3"><div align="center"><strong>Functions and Methods</strong></div></td>
<td colspan="3"><div align="center"><strong>Classes and Traits</strong></div></td>
</tr>
</thead>
<tbody>
<tr>
<td class="success">Total</td>
<td class="success big"> <div class="progress">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="81.79" aria-valuemin="0" aria-valuemax="100" style="width: 81.79%">
<span class="sr-only">81.79% covered (success)</span>
</div>
</div>
</td>
<td class="success small"><div align="right">81.79%</div></td>
<td class="success small"><div align="right">247 / 302</div></td>
<td class="warning big"> <div class="progress">
<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="69.23" aria-valuemin="0" aria-valuemax="100" style="width: 69.23%">
<span class="sr-only">69.23% covered (warning)</span>
</div>
</div>
</td>
<td class="warning small"><div align="right">69.23%</div></td>
<td class="warning small"><div align="right">36 / 52</div></td>
<td class="danger big"> <div class="progress">
<div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
<span class="sr-only">0.00% covered (danger)</span>
</div>
</div>
</td>
<td class="danger small"><div align="right">0.00%</div></td>
<td class="danger small"><div align="right">0 / 1</div></td>
</tr>
<tr>
<td class="success"><span class="glyphicon glyphicon-file"></span> <a href="Funcionario.php.html">Funcionario.php</a></td>
<td class="success big"> <div class="progress">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="81.79" aria-valuemin="0" aria-valuemax="100" style="width: 81.79%">
<span class="sr-only">81.79% covered (success)</span>
</div>
</div>
</td>
<td class="success small"><div align="right">81.79%</div></td>
<td class="success small"><div align="right">247 / 302</div></td>
<td class="warning big"> <div class="progress">
<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="69.23" aria-valuemin="0" aria-valuemax="100" style="width: 69.23%">
<span class="sr-only">69.23% covered (warning)</span>
</div>
</div>
</td>
<td class="warning small"><div align="right">69.23%</div></td>
<td class="warning small"><div align="right">36 / 52</div></td>
<td class="danger big"> <div class="progress">
<div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="0.00" aria-valuemin="0" aria-valuemax="100" style="width: 0.00%">
<span class="sr-only">0.00% covered (danger)</span>
</div>
</div>
</td>
<td class="danger small"><div align="right">0.00%</div></td>
<td class="danger small"><div align="right">0 / 1</div></td>
</tr>
</tbody>
</table>
<footer>
<hr/>
<h4>Legend</h4>
<p>
<span class="danger"><strong>Low</strong>: 0% to 35%</span>
<span class="warning"><strong>Medium</strong>: 35% to 70%</span>
<span class="success"><strong>High</strong>: 70% to 100%</span>
</p>
<p>
<small>Generated by <a href="http://github.com/sebastianbergmann/php-code-coverage" target="_top">PHP_CodeCoverage 2.0.10</a> using <a href="http://php.net/" target="_top">PHP 5.4.24</a> and <a href="http://phpunit.de/">PHPUnit 4.2.2</a> at Tue Sep 16 13:34:21 BRT 2014.</small>
</p>
</footer>
</div>
<script src="../../../js/jquery.min.js" type="text/javascript"></script>
<script src="../../../js/bootstrap.min.js" type="text/javascript"></script>
<script src="../../../js/holder.js" type="text/javascript"></script>
</body>
</html>
|
goldblade/ieducar2
|
module/Portal/tests/_reports/coverage/src/Portal/Entity/index.html
|
HTML
|
bsd-3-clause
| 5,398
|
#ifndef NT2_PREDICATES_INCLUDE_FUNCTIONS_SIMD_ISEMPTY_HPP_INCLUDED
#define NT2_PREDICATES_INCLUDE_FUNCTIONS_SIMD_ISEMPTY_HPP_INCLUDED
#include <nt2/predicates/functions/isempty.hpp>
#include <nt2/predicates/functions/scalar/isempty.hpp>
#endif
|
hainm/pythran
|
third_party/nt2/predicates/include/functions/simd/isempty.hpp
|
C++
|
bsd-3-clause
| 246
|
package models
import (
"OttBot2/settings"
"database/sql"
_ "github.com/go-sql-driver/mysql"
"time"
)
var db *sql.DB
func MakeDB(dbConnectString string) {
newDb, err := sql.Open("mysql", dbConnectString)
if err != nil {
panic(err)
}
db = newDb
timeout, err := time.ParseDuration(settings.GetDatabaseTimeout())
if err != nil {
panic(err)
}
db.SetConnMaxLifetime(timeout)
}
|
NurbsOtter/OttBot2
|
models/database.go
|
GO
|
bsd-3-clause
| 391
|
# -*- coding: utf-8 -*-
from django import forms
from cms_content.settings import EDITOR
from cms_content.models import CMSArticle
from cms_content import widgets
WIDGET = getattr(widgets, EDITOR)
class CMSArticleAdminForm(forms.ModelForm):
content = forms.CharField(widget=WIDGET)
class Meta:
model = CMSArticle
class CMSArticleFrontendForm(forms.ModelForm):
error_css_class = 'error'
required_css_class = 'required'
content = forms.CharField(widget=WIDGET)
class Meta:
model = CMSArticle
fields = ('title', 'slug', 'content', 'category',)
|
indexofire/django-cms-content
|
cms_content_patch/forms.py
|
Python
|
bsd-3-clause
| 604
|
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the COPYING file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
// WebPPicture tools: copy, crop, rescaling and view.
//
// Author: Skal (pascal.massimino@gmail.com)
#include <assert.h>
#include <stdlib.h>
#include "./vp8enci.h"
#include "../utils/rescaler.h"
#include "../utils/utils.h"
#define HALVE(x) (((x) + 1) >> 1)
// Grab the 'specs' (writer, *opaque, width, height...) from 'src' and copy them
// into 'dst'. Mark 'dst' as not owning any memory.
static void PictureGrabSpecs(const WebPPicture* const src,
WebPPicture* const dst) {
assert(src != NULL && dst != NULL);
*dst = *src;
WebPPictureResetBuffers(dst);
}
//------------------------------------------------------------------------------
// Picture copying
static void CopyPlane(const uint8_t* src, int src_stride,
uint8_t* dst, int dst_stride, int width, int height) {
while (height-- > 0) {
memcpy(dst, src, width);
src += src_stride;
dst += dst_stride;
}
}
// Adjust top-left corner to chroma sample position.
static void SnapTopLeftPosition(const WebPPicture* const pic,
int* const left, int* const top) {
if (!pic->use_argb) {
*left &= ~1;
*top &= ~1;
}
}
// Adjust top-left corner and verify that the sub-rectangle is valid.
static int AdjustAndCheckRectangle(const WebPPicture* const pic,
int* const left, int* const top,
int width, int height) {
SnapTopLeftPosition(pic, left, top);
if ((*left) < 0 || (*top) < 0) return 0;
if (width <= 0 || height <= 0) return 0;
if ((*left) + width > pic->width) return 0;
if ((*top) + height > pic->height) return 0;
return 1;
}
int WebPPictureCopy(const WebPPicture* src, WebPPicture* dst) {
if (src == NULL || dst == NULL) return 0;
if (src == dst) return 1;
PictureGrabSpecs(src, dst);
if (!WebPPictureAlloc(dst)) return 0;
if (!src->use_argb) {
CopyPlane(src->y, src->y_stride,
dst->y, dst->y_stride, dst->width, dst->height);
CopyPlane(src->u, src->uv_stride,
dst->u, dst->uv_stride, HALVE(dst->width), HALVE(dst->height));
CopyPlane(src->v, src->uv_stride,
dst->v, dst->uv_stride, HALVE(dst->width), HALVE(dst->height));
if (dst->a != NULL) {
CopyPlane(src->a, src->a_stride,
dst->a, dst->a_stride, dst->width, dst->height);
}
} else {
CopyPlane((const uint8_t*)src->argb, 4 * src->argb_stride,
(uint8_t*)dst->argb, 4 * dst->argb_stride,
4 * dst->width, dst->height);
}
return 1;
}
int WebPPictureIsView(const WebPPicture* picture) {
if (picture == NULL) return 0;
if (picture->use_argb) {
return (picture->memory_argb_ == NULL);
}
return (picture->memory_ == NULL);
}
int WebPPictureView(const WebPPicture* src,
int left, int top, int width, int height,
WebPPicture* dst) {
if (src == NULL || dst == NULL) return 0;
// verify rectangle position.
if (!AdjustAndCheckRectangle(src, &left, &top, width, height)) return 0;
if (src != dst) { // beware of aliasing! We don't want to leak 'memory_'.
PictureGrabSpecs(src, dst);
}
dst->width = width;
dst->height = height;
if (!src->use_argb) {
dst->y = src->y + top * src->y_stride + left;
dst->u = src->u + (top >> 1) * src->uv_stride + (left >> 1);
dst->v = src->v + (top >> 1) * src->uv_stride + (left >> 1);
dst->y_stride = src->y_stride;
dst->uv_stride = src->uv_stride;
if (src->a != NULL) {
dst->a = src->a + top * src->a_stride + left;
dst->a_stride = src->a_stride;
}
} else {
dst->argb = src->argb + top * src->argb_stride + left;
dst->argb_stride = src->argb_stride;
}
return 1;
}
//------------------------------------------------------------------------------
// Picture cropping
int WebPPictureCrop(WebPPicture* pic,
int left, int top, int width, int height) {
WebPPicture tmp;
if (pic == NULL) return 0;
if (!AdjustAndCheckRectangle(pic, &left, &top, width, height)) return 0;
PictureGrabSpecs(pic, &tmp);
tmp.width = width;
tmp.height = height;
if (!WebPPictureAlloc(&tmp)) return 0;
if (!pic->use_argb) {
const int y_offset = top * pic->y_stride + left;
const int uv_offset = (top / 2) * pic->uv_stride + left / 2;
CopyPlane(pic->y + y_offset, pic->y_stride,
tmp.y, tmp.y_stride, width, height);
CopyPlane(pic->u + uv_offset, pic->uv_stride,
tmp.u, tmp.uv_stride, HALVE(width), HALVE(height));
CopyPlane(pic->v + uv_offset, pic->uv_stride,
tmp.v, tmp.uv_stride, HALVE(width), HALVE(height));
if (tmp.a != NULL) {
const int a_offset = top * pic->a_stride + left;
CopyPlane(pic->a + a_offset, pic->a_stride,
tmp.a, tmp.a_stride, width, height);
}
} else {
const uint8_t* const src =
(const uint8_t*)(pic->argb + top * pic->argb_stride + left);
CopyPlane(src, pic->argb_stride * 4,
(uint8_t*)tmp.argb, tmp.argb_stride * 4,
width * 4, height);
}
WebPPictureFree(pic);
*pic = tmp;
return 1;
}
//------------------------------------------------------------------------------
// Simple picture rescaler
static void RescalePlane(const uint8_t* src,
int src_width, int src_height, int src_stride,
uint8_t* dst,
int dst_width, int dst_height, int dst_stride,
rescaler_t* const work,
int num_channels) {
WebPRescaler rescaler;
int y = 0;
WebPRescalerInit(&rescaler, src_width, src_height,
dst, dst_width, dst_height, dst_stride,
num_channels, work);
while (y < src_height) {
y += WebPRescalerImport(&rescaler, src_height - y,
src + y * src_stride, src_stride);
WebPRescalerExport(&rescaler);
}
}
static void AlphaMultiplyARGB(WebPPicture* const pic, int inverse) {
assert(pic->argb != NULL);
WebPMultARGBRows((uint8_t*)pic->argb, pic->argb_stride * sizeof(*pic->argb),
pic->width, pic->height, inverse);
}
static void AlphaMultiplyY(WebPPicture* const pic, int inverse) {
if (pic->a != NULL) {
WebPMultRows(pic->y, pic->y_stride, pic->a, pic->a_stride,
pic->width, pic->height, inverse);
}
}
int WebPPictureRescale(WebPPicture* pic, int width, int height) {
WebPPicture tmp;
int prev_width, prev_height;
rescaler_t* work;
if (pic == NULL) return 0;
prev_width = pic->width;
prev_height = pic->height;
if (!WebPRescalerGetScaledDimensions(
prev_width, prev_height, &width, &height)) {
return 0;
}
PictureGrabSpecs(pic, &tmp);
tmp.width = width;
tmp.height = height;
if (!WebPPictureAlloc(&tmp)) return 0;
if (!pic->use_argb) {
work = (rescaler_t*)WebPSafeMalloc(2ULL * width, sizeof(*work));
if (work == NULL) {
WebPPictureFree(&tmp);
return 0;
}
// If present, we need to rescale alpha first (for AlphaMultiplyY).
if (pic->a != NULL) {
WebPInitAlphaProcessing();
RescalePlane(pic->a, prev_width, prev_height, pic->a_stride,
tmp.a, width, height, tmp.a_stride, work, 1);
}
// We take transparency into account on the luma plane only. That's not
// totally exact blending, but still is a good approximation.
AlphaMultiplyY(pic, 0);
RescalePlane(pic->y, prev_width, prev_height, pic->y_stride,
tmp.y, width, height, tmp.y_stride, work, 1);
AlphaMultiplyY(&tmp, 1);
RescalePlane(pic->u,
HALVE(prev_width), HALVE(prev_height), pic->uv_stride,
tmp.u,
HALVE(width), HALVE(height), tmp.uv_stride, work, 1);
RescalePlane(pic->v,
HALVE(prev_width), HALVE(prev_height), pic->uv_stride,
tmp.v,
HALVE(width), HALVE(height), tmp.uv_stride, work, 1);
} else {
work = (rescaler_t*)WebPSafeMalloc(2ULL * width * 4, sizeof(*work));
if (work == NULL) {
WebPPictureFree(&tmp);
return 0;
}
// In order to correctly interpolate colors, we need to apply the alpha
// weighting first (black-matting), scale the RGB values, and remove
// the premultiplication afterward (while preserving the alpha channel).
WebPInitAlphaProcessing();
AlphaMultiplyARGB(pic, 0);
RescalePlane((const uint8_t*)pic->argb, prev_width, prev_height,
pic->argb_stride * 4,
(uint8_t*)tmp.argb, width, height,
tmp.argb_stride * 4,
work, 4);
AlphaMultiplyARGB(&tmp, 1);
}
WebPPictureFree(pic);
WebPSafeFree(work);
*pic = tmp;
return 1;
}
//------------------------------------------------------------------------------
|
yohunl/libwebp
|
src/enc/picture_rescale.c
|
C
|
bsd-3-clause
| 9,353
|
<?php
/**
* Created by PhpStorm.
* User: sz
* Date: 26.06.15
* Time: 10:51
*/
namespace modules\directory\models\form;
use modules\directory\models\ShopType;
use modules\directory\Module as DirectoryModule;
use modules\base\validators\LangRequiredValidator;
use modules\themes\Module as ThemeModule;
class ShopMarketForm extends ShopBaseForm
{
public $shop_category_id;
public $shop_type_id = ShopType::TYPE_MARKET;
public function rules()
{
$rules = parent::rules();
return array_merge($rules, [
[['region_id', 'province_id', 'city_id', 'address','latitude', 'longitude', 'categories', 'shop_category_id'], 'required'],
[['region_id', 'province_id', 'city_id', 'shop_category_id'], 'integer'],
[['translationName'], LangRequiredValidator::className(), 'langUrls'=>ThemeModule::getSystemLanguage()],
]);
}
public function attributeLabels(){
$labels = parent::attributeLabels();
return array_merge($labels,
[
'shop_category_id' => DirectoryModule::t('shop', 'SHOP_CATEGORY_ID'),
]
);
}
}
|
d-bo/unitaly-dev
|
modules/directory/models/form/ShopMarketForm.php
|
PHP
|
bsd-3-clause
| 1,149
|
package org.hisp.dhis.jdbc.statementbuilder;
/*
* Copyright (c) 2004-2016, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import org.hisp.quick.StatementDialect;
import org.hisp.dhis.jdbc.StatementBuilder;
import org.springframework.beans.factory.FactoryBean;
/**
* @author Lars Helge Overland
* @version $Id$
*/
public class StatementBuilderFactoryBean
implements FactoryBean<StatementBuilder>
{
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
private StatementDialect statementDialect;
public void setStatementDialect( StatementDialect statementDialect )
{
this.statementDialect = statementDialect;
}
private StatementBuilder statementBuilder;
// -------------------------------------------------------------------------
// Initialisation
// -------------------------------------------------------------------------
public void init()
{
if ( statementDialect.equals( StatementDialect.MYSQL ) )
{
this.statementBuilder = new MySQLStatementBuilder();
}
else if ( statementDialect.equals( StatementDialect.POSTGRESQL ) )
{
this.statementBuilder = new PostgreSQLStatementBuilder();
}
else if ( statementDialect.equals( StatementDialect.H2 ) )
{
this.statementBuilder = new H2StatementBuilder();
}
else if ( statementDialect.equals( StatementDialect.HSQL ) )
{
this.statementBuilder = new HsqlStatementBuilder();
}
else
{
throw new RuntimeException( "Unsupported dialect: " + statementDialect.toString() );
}
}
// -------------------------------------------------------------------------
// FactoryBean implementation
// -------------------------------------------------------------------------
@Override
public StatementBuilder getObject()
throws Exception
{
return statementBuilder;
}
@Override
public Class<StatementBuilder> getObjectType()
{
return StatementBuilder.class;
}
@Override
public boolean isSingleton()
{
return true;
}
}
|
uonafya/jphes-core
|
dhis-2/dhis-support/dhis-support-jdbc/src/main/java/org/hisp/dhis/jdbc/statementbuilder/StatementBuilderFactoryBean.java
|
Java
|
bsd-3-clause
| 3,912
|
// Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using EventStore.Common.Log;
using EventStore.Core.Services.Transport.Tcp;
using EventStore.Core.Tests.Helpers;
using EventStore.Transport.Tcp;
using NUnit.Framework;
namespace EventStore.Core.Tests.Services.Transport.Tcp
{
[TestFixture]
public class ssl_connections
{
private static readonly ILogger Log = LogManager.GetLoggerFor<ssl_connections>();
[Test]
public void should_connect_to_each_other_and_send_data()
{
var ip = IPAddress.Loopback;
var port = PortsHelper.GetAvailablePort(ip);
var serverEndPoint = new IPEndPoint(ip, port);
X509Certificate cert = GetCertificate();
var sent = new byte[1000];
new Random().NextBytes(sent);
var received = new MemoryStream();
var done = new ManualResetEventSlim();
var listener = new TcpServerListener(serverEndPoint);
listener.StartListening((endPoint, socket) =>
{
var ssl = TcpConnectionSsl.CreateServerFromSocket(Guid.NewGuid(), endPoint, socket, cert, verbose: true);
ssl.ConnectionClosed += (x, y) => done.Set();
if (ssl.IsClosed) done.Set();
Action<ITcpConnection, IEnumerable<ArraySegment<byte>>> callback = null;
callback = (x, y) =>
{
foreach (var arraySegment in y)
{
received.Write(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
Log.Info("Received: {0} bytes, total: {1}.", arraySegment.Count, received.Length);
}
if (received.Length >= sent.Length)
{
Log.Info("Done receiving...");
done.Set();
}
else
{
Log.Info("Receiving...");
ssl.ReceiveAsync(callback);
}
};
Log.Info("Receiving...");
ssl.ReceiveAsync(callback);
}, "Secure");
var clientSsl = TcpConnectionSsl.CreateConnectingConnection(
Guid.NewGuid(),
serverEndPoint,
"ES",
false,
new TcpClientConnector(),
TcpConnectionManager.ConnectionTimeout,
conn =>
{
Log.Info("Sending bytes...");
conn.EnqueueSend(new[] {new ArraySegment<byte>(sent)});
},
(conn, err) =>
{
Log.Error("Connecting failed: {0}.", err);
done.Set();
},
verbose: true);
Assert.IsTrue(done.Wait(20000), "Too long didn't receive completion.");
Log.Info("Stopping listener...");
listener.Stop();
Log.Info("Closing client ssl connection...");
clientSsl.Close("Normal close.");
Log.Info("Checking received data...");
Assert.AreEqual(sent, received.ToArray());
}
public static X509Certificate2 GetCertificate()
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EventStore.Core.Tests.server.p12"))
using (var mem = new MemoryStream())
{
stream.CopyTo(mem);
return new X509Certificate2(mem.ToArray(), "1111");
}
}
}
}
|
msbahrul/EventStore
|
src/EventStore/EventStore.Core.Tests/Services/Transport/Tcp/ssl_connection.cs
|
C#
|
bsd-3-clause
| 5,364
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 SWIPO Project
#
# Authors (this file):
# Stefan Schinkel <stefan.schinkel@gmail.com>
"""
Provides sanity checks for basic for parallel and serial circiuts.
"""
import numpy as np
import networkx as nx
from pyunicorn import ResNetwork
from .ResistiveNetwork_utils import *
debug = 0
""" Test for basic sanity, parallel and serial circiuts
"""
def testParallelTrivial():
r""" Trivial parallel case:
a) 0 --- 1 --- 2
/---- 3 ---\
b) 0 --- 1 --- 2
c) /---- 3 ---\
0 --- 1 --- 2
\____ 4 ___/
ER(a) = 2*ER(b) = 3*ER(c)
"""
nws = []
# construct nw1
idI, idJ = [0, 1], [1, 2]
nws.append(makeNW(idI, idJ, [.1]))
# construct nw2
idI += [0, 3]
idJ += [3, 2]
nws.append(makeNW(idI, idJ, [.1]))
# nw3
idI += [0, 4]
idJ += [4, 2]
nws.append(makeNW(idI, idJ, [.1]))
ER = []
for nw in nws:
rnw = ResNetwork(nw)
ER.append(rnw.effective_resistance(0, 2))
assert abs(ER[0]/2-ER[1]) < .1E-6
assert abs(ER[0]/3-ER[2]) < .1E-6
def testParallelLessTrivial():
""" Less Trivial Parallel Case:
|--- 1 --- 0
a) 2 |
|--- 3 ----4
|--- 1 --- 0 --- 5 --- |
b) 2 | | 7
|--- 3 ----4 --- 6 --- |
|---- 8 ----------- |
| | |
| |----------| |
| | |
|--- 1 --- 0 --- 5 --- | | |
c) 2 | | 7 | 9
|--- 3 ----4 --- 6 --- | | |
| | |
| ----------| |
| | |
|---- 10 -----------|
"""
nws = []
idI = [0, 1, 1, 2, 3]
idJ = [1, 2, 3, 3, 4]
nws.append(makeNW(idI, idJ, [1]*len(idI)))
idI.extend([0, 5, 5, 6, 6])
idJ.extend([5, 6, 7, 7, 4])
nws.append(makeNW(idI, idJ, [1]*len(idI)))
idI.extend([0, 8, 8, 9, 10])
idJ.extend([8, 9, 10, 10, 4])
nws.append(makeNW(idI, idJ, [1]*len(idI)))
ER = []
Gs = []
for nw in nws:
rnw = ResNetwork(nw)
ER.append(rnw.effective_resistance(0, 4))
# Gs.append(nx.DiGraph(nw))
# # showGraphs(Gs)
# # s = ''
# # for i,e in enumerate(ER):
# # s = s + "NW{:d} {:.3f}\t".format(i,e)
# # print "Effective resistances (0,2)\n %s" % (s)
assert abs(ER[0]/2-ER[1]) < .1E-6
assert abs(ER[0]/3-ER[2]) < .1E-6
# """ Less Trivial Parallel Case:
# /--- 1 --- 0
# a) 2 |
# \--- 3 ----4
# /--- 1 --- 0 --- 5 --- \
# b) 2 | | 7
# \--- 3 ----4 --- 6 --- /
# / --- 8 ----------- \
# | \
# /--- 1 --- 0 --- 5 --- \ \
# c) 2 7 9
# \--- 3 ----4 --- 6 --- / /
# | /
# \ --- 10 -----------/
# """
# nws =[]
# #construct nw1
# idI = [0,1,1,2,3]
# idJ = [1,2,3,3,4]
# val = [.1] * 5
# nws.append(makeNW(idI,idJ,[.1]*len(idI))[0])
# idI.extend([0,5,6,7])
# idJ.extend([5,6,7,4])
# val.extend( val * 6)
# nws.append(makeNW(idI,idJ,[.1]*len(idI))[0])
# idI.extend([0,8,9,10])
# idJ.extend([8,9,10,4])
# val.extend( val * 4)
# nws.append(makeNW(idI,idJ,val)[0])
# ER = []
# for nw in nws:
# rnw = ResNetwork(nw)
# ER.append( rnw.effective_resistance(0,4))
# s = ''
# for i,e in enumerate(ER):
# s = s + "NW{:d} {:.3f}\t".format(i,e)
# print "Effective resistances (0,2)\n %s" % (s)
# assert abs(ER[0]/2-ER[1]) < .1E-6
# assert abs(ER[0]/3-ER[2]) < .1E-6
def testParallelRandom():
""" 50 random parallel cases
"""
N = 10
p = .7
runs = 0
while runs < 50:
G = nx.fast_gnp_random_graph(N, p)
a = 0
b = G.number_of_nodes()-1
try:
nx.shortest_path(G, source=a, target=b)
except RuntimeError:
continue
i, j = [], []
for xx in G.edges():
i.append(xx[0])
j.append(xx[1])
# %.1f values for resistance
val = np.round(np.random.ranf(len(i))*100)/10
# and test
nw1 = makeNW(i, j, val)
nw2 = parallelCopy(nw1, a, b)
ER1 = ResNetwork(nw1).effective_resistance(a, b)
ER2 = ResNetwork(nw2).effective_resistance(a, b)
# assertion
assert (ER1/2-ER2) < 1E-6
# increment runs
runs += 1
def testSerialTrivial():
"""Trivial serial test case
a) 0 --- 1 --- 2
b) 0 --- 1 --- 2 --- 3 --- 4
ER(a)/2 = ER(b)
"""
# construct nw1
idI = [0, 1]
idJ = [1, 2]
val = [1, 1]
nw1 = np.zeros((3, 3))
G1 = nx.DiGraph()
for i, j, v in zip(idI, idJ, val):
nw1[i, j] = v
nw1[j, i] = v
# construct nw2
idI = idI + [2, 3]
idJ = idJ + [3, 4]
val = val + [1, 1]
nw2 = np.zeros((5, 5))
for i, j, v in zip(idI, idJ, val):
nw2[i, j] = v
nw2[j, i] = v
# init ResNetworks
rnw1 = ResNetwork(nw1)
rnw2 = ResNetwork(nw2)
ER1 = rnw1.effective_resistance(0, 2)
ER2 = rnw2.effective_resistance(0, 4)
print "Effective resistances (0,2)"
print "NW1 %.3f\tNW2 %.3f\t 2*NW1 = %.3f" % (ER1, ER2, 2*ER1)
assert (ER1*2-ER2) < 1E-6
def testSerialRandom():
""" 50 Random serial test cases
"""
N = 10
p = .7
runs = 0
while runs < 50:
# a random graph
G = nx.fast_gnp_random_graph(N, p)
try:
nx.shortest_path(G, source=0, target=N-1)
except RuntimeError:
continue
# convert to plain ndarray
nw1 = nx2nw(G)
# copy and join network
nw2 = serialCopy(nw1)
# compute effective resistance
ER1 = ResNetwork(
nw1, silence_level=3).effective_resistance(0, len(nw1)-1)
ER2 = ResNetwork(
nw2, silence_level=3).effective_resistance(0, len(nw2)-1)
# increment runs
runs += 1
# assertion
print ER1*2-ER2
assert (ER1*2-ER2) < 1E-6
|
leftaroundabout/pyunicorn
|
tests/test_core/TestResitiveNetwork-circuits.py
|
Python
|
bsd-3-clause
| 6,379
|
#ifndef TCS_H
#define TCS_H
#include <tss/platform.h>
#include <tss/tss_structs.h>
#include <tss/tcs_typedef.h>
#include <tss/tcs_defines.h>
#include <tss/tcs_structs.h>
#include <tss/tcs_error.h>
#include <tss/tpm.h>
extern TSS_RESULT Tcsi_OpenContext
(
TCS_CONTEXT_HANDLE* hContext // out
);
extern TSS_RESULT Tcsi_CloseContext
(
TCS_CONTEXT_HANDLE hContext // in
);
extern TSS_RESULT Tcsi_FreeMemory
(
TCS_CONTEXT_HANDLE hContext, // in
BYTE* pMemory // in
);
extern TSS_RESULT Tcsi_GetCapability
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_CAPABILITY_AREA capArea, // in
UINT32 subCapSize, // in
BYTE* subCap, // in
UINT32* respSize, // out
BYTE** resp // out
);
extern TSS_RESULT Tcsi_RegisterKey
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_UUID WrappingKeyUUID, // in
TSS_UUID KeyUUID, // in
UINT32 cKeySize, // in
BYTE* rgbKey, // in
UINT32 cVendorDataSize, // in
BYTE* gbVendorData // in
);
extern TSS_RESULT Tcsip_UnregisterKey
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_UUID KeyUUID // in
);
extern TSS_RESULT Tcsip_KeyControlOwner
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE hKey, // in
UINT32 ulPubKeyLength, // in
BYTE* prgbPubKey, // in
UINT32 attribName, // in
TSS_BOOL attribValue, // in
TPM_AUTH* pOwnerAuth, // in, out
TSS_UUID* pUuidData // out
);
extern TSS_RESULT Tcsi_EnumRegisteredKeys
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_UUID* pKeyUUID, // in
UINT32* pcKeyHierarchySize, // out
TSS_KM_KEYINFO** ppKeyHierarchy // out
);
extern TSS_RESULT Tcsi_GetRegisteredKey
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_UUID KeyUUID, // in
TSS_KM_KEYINFO** ppKeyInfo // out
);
extern TSS_RESULT Tcsi_GetRegisteredKeyBlob
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_UUID KeyUUID, // in
UINT32* pcKeySize, // out
BYTE** prgbKey // out
);
extern TSS_RESULT Tcsip_GetRegisteredKeyByPublicInfo
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_ALGORITHM_ID algID, // in
UINT32 ulPublicInfoLength, // in
BYTE* rgbPublicInfo, // in
UINT32* keySize, // out
BYTE** keyBlob // out
);
extern TSS_RESULT Tcsip_LoadKeyByBlob
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE hUnwrappingKey, // in
UINT32 cWrappedKeyBlobSize, // in
BYTE* rgbWrappedKeyBlob, // in
TPM_AUTH* pAuth, // in, out
TCS_KEY_HANDLE* phKeyTCSI, // out
TCS_KEY_HANDLE* phKeyHMAC // out
);
extern TSS_RESULT Tcsip_LoadKeyByUUID
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_UUID KeyUUID, // in
TCS_LOADKEY_INFO* pLoadKeyInfo, // in, out
TCS_KEY_HANDLE* phKeyTCSI // out
);
extern TSS_RESULT Tcsip_EvictKey
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE hKey // in
);
extern TSS_RESULT Tcsip_CreateWrapKey
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE hWrappingKey, // in
TPM_ENCAUTH KeyUsageAuth, // in
TPM_ENCAUTH KeyMigrationAuth, // in
UINT32 keyInfoSize, // in
BYTE* keyInfo, // in
TPM_AUTH* pAuth, // in, out
UINT32* keyDataSize, // out
BYTE** keyData // out
);
extern TSS_RESULT Tcsip_GetPubKey
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE hKey, // in
TPM_AUTH* pAuth, // in, out
UINT32* pcPubKeySize, // out
BYTE** prgbPubKey // out
);
extern TSS_RESULT Tcsip_MakeIdentity
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_ENCAUTH identityAuth, // in
TPM_CHOSENID_HASH IDLabel_PrivCAHash, // in
UINT32 idIdentityKeyInfoSize, // in
BYTE* idIdentityKeyInfo, // in
TPM_AUTH* pSrkAuth, // in, out
TPM_AUTH* pOwnerAuth, // in, out
UINT32* idIdentityKeySize, // out
BYTE** idIdentityKey, // out
UINT32* pcIdentityBindingSize, // out
BYTE** prgbIdentityBinding, // out
UINT32* pcEndorsementCredentialSize, // out
BYTE** prgbEndorsementCredential, // out
UINT32* pcPlatformCredentialSize, // out
BYTE** prgbPlatformCredential, // out
UINT32* pcConformanceCredentialSize, // out
BYTE** prgbConformanceCredential // out
);
extern TSS_RESULT Tcsi_LogPcrEvent
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_PCR_EVENT Event, // in
UINT32* pNumber // out
);
extern TSS_RESULT Tcsi_GetPcrEvent
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 PcrIndex, // in
UINT32* pNumber, // in, out
TSS_PCR_EVENT** ppEvent // out
);
extern TSS_RESULT Tcsi_GetPcrEventsByPcr
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 PcrIndex, // in
UINT32 FirstEvent, // in
UINT32* pEventCount, // in, out
TSS_PCR_EVENT** ppEvents // out
);
extern TSS_RESULT Tcsi_GetPcrEventLog
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32* pEventCount, // out
TSS_PCR_EVENT** ppEvents // out
);
extern TSS_RESULT Tcsip_SetOwnerInstall
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_BOOL state // in
);
extern TSS_RESULT Tcsip_TakeOwnership
(
TCS_CONTEXT_HANDLE hContext, // in
UINT16 protocolID, // in
UINT32 encOwnerAuthSize, // in
BYTE* encOwnerAuth, // in
UINT32 encSrkAuthSize, // in
BYTE* encSrkAuth, // in
UINT32 srkKeyInfoSize, // in
BYTE* srkKeyInfo, // in
TPM_AUTH* ownerAuth, // in, out
UINT32* srkKeyDataSize, // out
BYTE** srkKeyData // out
);
extern TSS_RESULT Tcsip_SetOperatorAuth
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_SECRET operatorAuth // in
);
extern TSS_RESULT Tcsip_OIAP
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_AUTHHANDLE* authHandle, // out
TPM_NONCE* nonce0 // out
);
extern TSS_RESULT Tcsip_OSAP
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_ENTITY_TYPE entityType, // in
UINT32 entityValue, // in
TPM_NONCE nonceOddOSAP, // in
TCS_AUTHHANDLE* authHandle, // out
TPM_NONCE* nonceEven, // out
TPM_NONCE* nonceEvenOSAP // out
);
extern TSS_RESULT Tcsip_ChangeAuth
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE parentHandle, // in
TPM_PROTOCOL_ID protocolID, // in
TPM_ENCAUTH newAuth, // in
TPM_ENTITY_TYPE entityType, // in
UINT32 encDataSize, // in
BYTE* encData, // in
TPM_AUTH* ownerAuth, // in, out
TPM_AUTH* entityAuth, // in, out
UINT32* outDataSize, // out
BYTE** outData // out
);
extern TSS_RESULT Tcsip_ChangeAuthOwner
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_PROTOCOL_ID protocolID, // in
TPM_ENCAUTH newAuth, // in
TPM_ENTITY_TYPE entityType, // in
TPM_AUTH* ownerAuth // in, out
);
extern TSS_RESULT Tcsip_ChangeAuthAsymStart
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE idHandle, // in
TPM_NONCE antiReplay, // in
UINT32 TempKeyInfoSize, // in
BYTE* TempKeyInfoData, // in
TPM_AUTH* pAuth, // in, out
UINT32* TempKeySize, // out
BYTE** TempKeyData, // out
UINT32* CertifyInfoSize, // out
BYTE** CertifyInfo, // out
UINT32* sigSize, // out
BYTE** sig, // out
TCS_KEY_HANDLE* ephHandle // out
);
extern TSS_RESULT Tcsip_ChangeAuthAsymFinish
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE parentHandle, // in
TCS_KEY_HANDLE ephHandle, // in
TPM_ENTITY_TYPE entityType, // in
TPM_HMAC newAuthLink, // in
UINT32 newAuthSize, // in
BYTE* encNewAuth, // in
UINT32 encDataSizeIn, // in
BYTE* encDataIn, // in
TPM_AUTH* ownerAuth, // in, out
UINT32* encDataSizeOut, // out
BYTE** encDataOut, // out
TPM_NONCE* saltNonce, // out
TPM_DIGEST* changeProof // out
);
extern TSS_RESULT Tcsip_TerminateHandle
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_AUTHHANDLE handle // in
);
extern TSS_RESULT Tcsip_ActivateTPMIdentity
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE idKey, // in
UINT32 blobSize, // in
BYTE* blob, // in
TPM_AUTH* idKeyAuth, // in, out
TPM_AUTH* ownerAuth, // in, out
UINT32* SymmetricKeySize, // out
BYTE** SymmetricKey // out
);
extern TSS_RESULT Tcsip_EstablishTransport
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 ulTransControlFlags, // in
TCS_KEY_HANDLE hEncKey, // in
UINT32 ulTransSessionInfoSize, // in
BYTE* rgbTransSessionInfo, // in
UINT32 ulSecretSize, // in
BYTE* rgbSecret, // in
TPM_AUTH* pEncKeyAuth, // in, out
TPM_MODIFIER_INDICATOR* pbLocality, // out
TCS_HANDLE* hTransSession, // out
UINT32* ulCurrentTicksSize, // out
BYTE** prgbCurrentTicks, // out
TPM_NONCE* pTransNonce // out
);
extern TSS_RESULT Tcsip_ExecuteTransport
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_COMMAND_CODE unWrappedCommandOrdinal, // in
UINT32 ulWrappedCmdParamInSize, // in
BYTE* rgbWrappedCmdParamIn, // in
UINT32* pulHandleListSize, // in, out
TCS_HANDLE** rghHandles, // in, out
TPM_AUTH* pWrappedCmdAuth1, // in, out
TPM_AUTH* pWrappedCmdAuth2, // in, out
TPM_AUTH* pTransAuth, // in, out
UINT64* punCurrentTicks, // out
TPM_MODIFIER_INDICATOR* pbLocality, // out
TPM_RESULT* pulWrappedCmdReturnCode, // out
UINT32* ulWrappedCmdParamOutSize, // out
BYTE** rgbWrappedCmdParamOut // out
);
extern TSS_RESULT Tcsip_ReleaseTransportSigned
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE hSignatureKey, // in
TPM_NONCE AntiReplayNonce, // in
TPM_AUTH* pKeyAuth, // in, out
TPM_AUTH* pTransAuth, // in, out
TPM_MODIFIER_INDICATOR* pbLocality, // out
UINT32* pulCurrentTicksSize, // out
BYTE** prgbCurrentTicks, // out
UINT32* pulSignatureSize, // out
BYTE** prgbSignature // out
);
extern TSS_RESULT Tcsip_Extend
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_PCRINDEX pcrNum, // in
TPM_DIGEST inDigest, // in
TPM_PCRVALUE* outDigest // out
);
extern TSS_RESULT Tcsip_PcrRead
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_PCRINDEX pcrNum, // in
TPM_PCRVALUE* outDigest // out
);
extern TSS_RESULT Tcsip_Quote
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE keyHandle, // in
TPM_NONCE antiReplay, // in
UINT32 pcrTargetSize, // in
BYTE* pcrTarget, // in
TPM_AUTH* privAuth, // in, out
UINT32* pcrDataSize, // out
BYTE** pcrData, // out
UINT32* sigSize, // out
BYTE** sig // out
);
extern TSS_RESULT Tcsip_Quote2
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE keyHandle, // in
TPM_NONCE antiReplay, // in
UINT32 pcrTargetSize, // in
BYTE* pcrTarget, // in
TSS_BOOL addVersion, // in
TPM_AUTH* privAuth, // in, out
UINT32* pcrDataSize, // out
BYTE** pcrData, // out
UINT32* versionInfoSize, // out
BYTE** versionInfo, // out
UINT32* sigSize, // out
BYTE** sig // out
);
extern TSS_RESULT Tcsip_DirWriteAuth
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_DIRINDEX dirIndex, // in
TPM_DIRVALUE newContents, // in
TPM_AUTH* ownerAuth // in, out
);
extern TSS_RESULT Tcsip_DirRead
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_DIRINDEX dirIndex, // in
TPM_DIRVALUE* dirValue // out
);
extern TSS_RESULT Tcsip_Seal
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE keyHandle, // in
TPM_ENCAUTH encAuth, // in
UINT32 pcrInfoSize, // in
BYTE* PcrInfo, // in
UINT32 inDataSize, // in
BYTE* inData, // in
TPM_AUTH* pubAuth, // in, out
UINT32* SealedDataSize, // out
BYTE** SealedData // out
);
extern TSS_RESULT Tcsip_Unseal
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE keyHandle, // in
UINT32 SealedDataSize, // in
BYTE* SealedData, // in
TPM_AUTH* keyAuth, // in, out
TPM_AUTH* dataAuth, // in, out
UINT32* DataSize, // out
BYTE** Data // out
);
extern TSS_RESULT Tcsip_UnBind
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE keyHandle, // in
UINT32 inDataSize, // in
BYTE* inData, // in
TPM_AUTH* privAuth, // in, out
UINT32* outDataSize, // out
BYTE** outData // out
);
extern TSS_RESULT Tcsip_Sealx
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE keyHandle, // in
TPM_ENCAUTH encAuth, // in
UINT32 pcrInfoSize, // in
BYTE* PcrInfo, // in
UINT32 inDataSize, // in
BYTE* inData, // in
TPM_AUTH* pubAuth, // in, out
UINT32* SealedDataSize, // out
BYTE** SealedData // out
);
extern TSS_RESULT Tcsip_LoadKey2ByBlob
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE hUnwrappingKey, // in
UINT32 cWrappedKeyBlobSize, // in
BYTE* rgbWrappedKeyBlob, // in
TPM_AUTH* pAuth, // in, out
TCS_KEY_HANDLE* phKeyTCSI // out
);
extern TSS_RESULT Tcsip_CreateMigrationBlob
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE parentHandle, // in
TSS_MIGRATE_SCHEME migrationType, // in
UINT32 MigrationKeyAuthSize, // in
BYTE* MigrationKeyAuth, // in
UINT32 encDataSize, // in
BYTE* encData, // in
TPM_AUTH* parentAuth, // in, out
TPM_AUTH* entityAuth, // in, out
UINT32* randomSize, // out
BYTE** random, // out
UINT32* outDataSize, // out
BYTE** outData // out
);
extern TSS_RESULT Tcsip_ConvertMigrationBlob
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE parentHandle, // in
UINT32 inDataSize, // in
BYTE* inData, // in
UINT32 randomSize, // in
BYTE* random, // in
TPM_AUTH* parentAuth, // in, out
UINT32* outDataSize, // out
BYTE** outData // out
);
extern TSS_RESULT Tcsip_AuthorizeMigrationKey
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_MIGRATE_SCHEME migrateScheme, // in
UINT32 MigrationKeySize, // in
BYTE* MigrationKey, // in
TPM_AUTH* ownerAuth, // in, out
UINT32* MigrationKeyAuthSize, // out
BYTE** MigrationKeyAuth // out
);
extern TSS_RESULT Tcsip_CertifyKey
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE certHandle, // in
TCS_KEY_HANDLE keyHandle, // in
TPM_NONCE antiReplay, // in
TPM_AUTH* certAuth, // in, out
TPM_AUTH* keyAuth, // in, out
UINT32* CertifyInfoSize, // out
BYTE** CertifyInfo, // out
UINT32* outDataSize, // out
BYTE** outData // out
);
extern TSS_RESULT Tcsip_CertifyKey2
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE certHandle, // in
TCS_KEY_HANDLE keyHandle, // in
TPM_DIGEST MSAdigest, // in
TPM_NONCE antiReplay, // in
TPM_AUTH* certAuth, // in, out
TPM_AUTH* keyAuth, // in, out
UINT32* CertifyInfoSize, // out
BYTE** CertifyInfo, // out
UINT32* outDataSize, // out
BYTE** outData // out
);
extern TSS_RESULT Tcsip_Sign
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE keyHandle, // in
UINT32 areaToSignSize, // in
BYTE* areaToSign, // in
TPM_AUTH* privAuth, // in, out
UINT32* sigSize, // out
BYTE** sig // out
);
extern TSS_RESULT Tcsip_GetRandom
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32* bytesRequested, // in, out
BYTE** randomBytes // out
);
extern TSS_RESULT Tcsip_StirRandom
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 inDataSize, // in
BYTE* inData // in
);
extern TSS_RESULT Tcsip_GetCapability
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_CAPABILITY_AREA capArea, // in
UINT32 subCapSize, // in
BYTE* subCap, // in
UINT32* respSize, // out
BYTE** resp // out
);
extern TSS_RESULT Tcsip_GetCapabilitySigned
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE keyHandle, // in
TPM_NONCE antiReplay, // in
TPM_CAPABILITY_AREA capArea, // in
UINT32 subCapSize, // in
BYTE* subCap, // in
TPM_AUTH* privAuth, // in, out
TPM_VERSION* Version, // out
UINT32* respSize, // out
BYTE** resp, // out
UINT32* sigSize, // out
BYTE** sig // out
);
extern TSS_RESULT Tcsip_GetCapabilityOwner
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_AUTH* pOwnerAuth, // in, out
TPM_VERSION* pVersion, // out
UINT32* pNonVolatileFlags, // out
UINT32* pVolatileFlags // out
);
extern TSS_RESULT Tcsip_CreateEndorsementKeyPair
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_NONCE antiReplay, // in
UINT32 endorsementKeyInfoSize, // in
BYTE* endorsementKeyInfo, // in
UINT32* endorsementKeySize, // out
BYTE** endorsementKey, // out
TPM_DIGEST* checksum // out
);
extern TSS_RESULT Tcsip_ReadPubek
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_NONCE antiReplay, // in
UINT32* pubEndorsementKeySize, // out
BYTE** pubEndorsementKey, // out
TPM_DIGEST* checksum // out
);
extern TSS_RESULT Tcsip_DisablePubekRead
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_AUTH* ownerAuth // in, out
);
extern TSS_RESULT Tcsip_OwnerReadPubek
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_AUTH* ownerAuth, // in, out
UINT32* pubEndorsementKeySize, // out
BYTE** pubEndorsementKey // out
);
extern TSS_RESULT Tcsip_SelfTestFull
(
TCS_CONTEXT_HANDLE hContext // in
);
extern TSS_RESULT Tcsip_CertifySelfTest
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE keyHandle, // in
TPM_NONCE antiReplay, // in
TPM_AUTH* privAuth, // in, out
UINT32* sigSize, // out
BYTE** sig // out
);
extern TSS_RESULT Tcsip_ContinueSelfTest
(
TCS_CONTEXT_HANDLE hContext // in
);
extern TSS_RESULT Tcsip_GetTestResult
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32* outDataSize, // out
BYTE** outData // out
);
extern TSS_RESULT Tcsip_OwnerSetDisable
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_BOOL disableState, // in
TPM_AUTH* ownerAuth // in, out
);
extern TSS_RESULT Tcsip_OwnerClear
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_AUTH* ownerAuth // in, out
);
extern TSS_RESULT Tcsip_DisableOwnerClear
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_AUTH* ownerAuth // in, out
);
extern TSS_RESULT Tcsip_ForceClear
(
TCS_CONTEXT_HANDLE hContext // in
);
extern TSS_RESULT Tcsip_DisableForceClear
(
TCS_CONTEXT_HANDLE hContext // in
);
extern TSS_RESULT Tcsip_PhysicalDisable
(
TCS_CONTEXT_HANDLE hContext // in
);
extern TSS_RESULT Tcsip_PhysicalEnable
(
TCS_CONTEXT_HANDLE hContext // in
);
extern TSS_RESULT Tcsip_PhysicalSetDeactivated
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_BOOL state // in
);
extern TSS_RESULT Tcsip_SetTempDeactivated
(
TCS_CONTEXT_HANDLE hContext // in
);
extern TSS_RESULT Tcsip_SetTempDeactivated2
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_AUTH* pOperatorAuth // in, out
);
extern TSS_RESULT Tcsip_OwnerReadInternalPub
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE hKey, // in
TPM_AUTH* pOwnerAuth, // in, out
UINT32* punPubKeySize, // out
BYTE** ppbPubKeyData // out
);
extern TSS_RESULT Tcsip_PhysicalPresence
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_PHYSICAL_PRESENCE fPhysicalPresence // in
);
extern TSS_RESULT Tcsip_FieldUpgrade
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 dataInSize, // in
BYTE* dataIn, // in
TPM_AUTH* ownerAuth, // in, out
UINT32* dataOutSize, // out
BYTE** dataOut // out
);
extern TSS_RESULT Tcsip_ResetLockValue
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_AUTH* ownerAuth // in, out
);
extern TSS_RESULT Tcsip_FlushSpecific
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_HANDLE hResHandle, // in
TPM_RESOURCE_TYPE resourceType // in
);
extern TSS_RESULT Tcsip_SetRedirection
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE keyHandle, // in
UINT32 c1, // in
UINT32 c2, // in
TPM_AUTH* privAuth // in, out
);
extern TSS_RESULT Tcsip_DSAP
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_ENTITY_TYPE entityType, // in
TCS_KEY_HANDLE keyHandle, // in
TPM_NONCE nonceOddDSAP, // in
UINT32 entityValueSize, // in
BYTE* entityValue, // in
TCS_AUTHHANDLE* authHandle, // out
TPM_NONCE* nonceEven, // out
TPM_NONCE* nonceEvenDSAP // out
);
extern TSS_RESULT Tcsip_Delegate_Manage
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_FAMILY_ID familyID, // in
TPM_FAMILY_OPERATION opFlag, // in
UINT32 opDataSize, // in
BYTE* opData, // in
TPM_AUTH* ownerAuth, // in, out
UINT32* retDataSize, // out
BYTE** retData // out
);
extern TSS_RESULT Tcsip_Delegate_CreateKeyDelegation
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE hKey, // in
UINT32 publicInfoSize, // in
BYTE* publicInfo, // in
TPM_ENCAUTH encDelAuth, // in
TPM_AUTH* keyAuth, // in, out
UINT32* blobSize, // out
BYTE** blob // out
);
extern TSS_RESULT Tcsip_Delegate_CreateOwnerDelegation
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_BOOL increment, // in
UINT32 publicInfoSize, // in
BYTE* publicInfo, // in
TPM_ENCAUTH encDelAuth, // in
TPM_AUTH* ownerAuth, // in, out
UINT32* blobSize, // out
BYTE** blob // out
);
extern TSS_RESULT Tcsip_Delegate_LoadOwnerDelegation
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_DELEGATE_INDEX index, // in
UINT32 blobSize, // in
BYTE* blob, // in
TPM_AUTH* ownerAuth // in, out
);
extern TSS_RESULT Tcsip_Delegate_UpdateVerificationCount
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 inputSize, // in
BYTE* input, // in
TPM_AUTH* ownerAuth, // in, out
UINT32* outputSize, // out
BYTE** output // out
);
extern TSS_RESULT Tcsip_Delegate_VerifyDelegation
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 delegateSize, // in
BYTE* delegate // in
);
extern TSS_RESULT Tcsip_Delegate_ReadTable
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32* pulFamilyTableSize, // out
BYTE** ppFamilyTable, // out
UINT32* pulDelegateTableSize, // out
BYTE** ppDelegateTable // out
);
extern TSS_RESULT Tcsip_NV_DefineOrReleaseSpace
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 cPubInfoSize, // in
BYTE* pPubInfo, // in
TPM_ENCAUTH encAuth, // in
TPM_AUTH* pAuth // in, out
);
extern TSS_RESULT Tcsip_NV_WriteValue
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_NV_INDEX hNVStore, // in
UINT32 offset, // in
UINT32 ulDataLength, // in
BYTE* rgbDataToWrite, // in
TPM_AUTH* privAuth // in, out
);
extern TSS_RESULT Tcsip_NV_WriteValueAuth
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_NV_INDEX hNVStore, // in
UINT32 offset, // in
UINT32 ulDataLength, // in
BYTE* rgbDataToWrite, // in
TPM_AUTH* NVAuth // in, out
);
extern TSS_RESULT Tcsip_NV_ReadValue
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_NV_INDEX hNVStore, // in
UINT32 offset, // in
UINT32* pulDataLength, // in, out
TPM_AUTH* privAuth, // in, out
BYTE** rgbDataRead // out
);
extern TSS_RESULT Tcsip_NV_ReadValueAuth
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_NV_INDEX hNVStore, // in
UINT32 offset, // in
UINT32* pulDataLength, // in, out
TPM_AUTH* NVAuth, // in, out
BYTE** rgbDataRead // out
);
extern TSS_RESULT Tcsip_CreateMaintenanceArchive
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_BOOL generateRandom, // in
TPM_AUTH* ownerAuth, // in, out
UINT32* randomSize, // out
BYTE** random, // out
UINT32* archiveSize, // out
BYTE** archive // out
);
extern TSS_RESULT Tcsip_LoadMaintenanceArchive
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 dataInSize, // in
BYTE* dataIn, // in
TPM_AUTH* ownerAuth, // in, out
UINT32* dataOutSize, // out
BYTE** dataOut // out
);
extern TSS_RESULT Tcsip_KillMaintenanceFeature
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_AUTH* ownerAuth // in, out
);
extern TSS_RESULT Tcsip_LoadManuMaintPub
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_NONCE antiReplay, // in
UINT32 PubKeySize, // in
BYTE* PubKey, // in
TPM_DIGEST* checksum // out
);
extern TSS_RESULT Tcsip_ReadManuMaintPub
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_NONCE antiReplay, // in
TPM_DIGEST* checksum // out
);
extern TSS_RESULT Tcsip_CreateRevocableEndorsementKeyPair
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_NONCE antiReplay, // in
UINT32 endorsementKeyInfoSize, // in
BYTE* endorsementKeyInfo, // in
TSS_BOOL GenResetAuth, // in
TPM_DIGEST* EKResetAuth, // in, out
UINT32* endorsementKeySize, // out
BYTE** endorsementKey, // out
TPM_DIGEST* checksum // out
);
extern TSS_RESULT Tcsip_RevokeEndorsementKeyPair
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_DIGEST EKResetAuth // in
);
extern TSS_RESULT Tcsip_PcrReset
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 pcrTargetSize, // in
BYTE* pcrTarget // in
);
extern TSS_RESULT Tcsip_ReadCounter
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_COUNTER_ID idCounter, // in
TPM_COUNTER_VALUE* counterValue // out
);
extern TSS_RESULT Tcsip_CreateCounter
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 LabelSize, // in (=4)
BYTE* pLabel, // in
TPM_ENCAUTH CounterAuth, // in
TPM_AUTH* pOwnerAuth, // in, out
TSS_COUNTER_ID* idCounter, // out
TPM_COUNTER_VALUE* counterValue // out
);
extern TSS_RESULT Tcsip_IncrementCounter
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_COUNTER_ID idCounter, // in
TPM_AUTH* pCounterAuth, // in, out
TPM_COUNTER_VALUE* counterValue // out
);
extern TSS_RESULT Tcsip_ReleaseCounter
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_COUNTER_ID idCounter, // in
TPM_AUTH* pCounterAuth // in, out
);
extern TSS_RESULT Tcsip_ReleaseCounterOwner
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_COUNTER_ID idCounter, // in
TPM_AUTH* pOwnerAuth // in, out
);
extern TSS_RESULT Tcsip_ReadCurrentTicks
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32* pulCurrentTimeSize, // out
BYTE** prgbCurrentTime // out
);
extern TSS_RESULT Tcsip_TickStampBlob
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE hKey, // in
TPM_NONCE antiReplay, // in
TPM_DIGEST digestToStamp, // in
TPM_AUTH* privAuth, // in, out
UINT32* pulSignatureLength, // out
BYTE** prgbSignature, // out
UINT32* pulTickCountSize, // out
BYTE** prgbTickCount // out
);
extern TSS_RESULT Tcsip_TPM_DAA_Join
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_HANDLE handle, // in
BYTE stage, // in
UINT32 inputSize0, // in
BYTE* inputData0, // in
UINT32 inputSize1, // in
BYTE* inputData1, // in
TPM_AUTH* ownerAuth, // in, out
UINT32* outputSize, // out
BYTE** outputData // out
);
extern TSS_RESULT Tcsip_TPM_DAA_Sign
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_HANDLE handle, // in
BYTE stage, // in
UINT32 inputSize0, // in
BYTE* inputData0, // in
UINT32 inputSize1, // in
BYTE* inputData1, // in
TPM_AUTH* ownerAuth, // in, out
UINT32* outputSize, // out
BYTE** outputData // out
);
extern TSS_RESULT Tcsip_MigrateKey
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE hMaKey, // in
UINT32 PublicKeySize, // in
BYTE* PublicKey, // in
UINT32 inDataSize, // in
BYTE* inData, // in
TPM_AUTH* ownerAuth, // in, out
UINT32* outDataSize, // out
BYTE** outData // out
);
extern TSS_RESULT Tcsip_CMK_SetRestrictions
(
TCS_CONTEXT_HANDLE hContext, // in
TSS_CMK_DELEGATE Restriction, // in
TPM_AUTH* ownerAuth // in, out
);
extern TSS_RESULT Tcsip_CMK_ApproveMA
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_DIGEST migAuthorityDigest, // in
TPM_AUTH* ownerAuth, // in, out
TPM_HMAC* HmacMigAuthDigest // out
);
extern TSS_RESULT Tcsip_CMK_CreateKey
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE hWrappingKey, // in
TPM_ENCAUTH KeyUsageAuth, // in
TPM_HMAC MigAuthApproval, // in
TPM_DIGEST MigAuthorityDigest, // in
UINT32* keyDataSize, // in, out
BYTE** prgbKeyData, // in, out
TPM_AUTH* pAuth // in, out
);
extern TSS_RESULT Tcsip_CMK_CreateTicket
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 PublicVerifyKeySize, // in
BYTE* PublicVerifyKey, // in
TPM_DIGEST SignedData, // in
UINT32 SigValueSize, // in
BYTE* SigValue, // in
TPM_AUTH* pOwnerAuth, // in, out
TPM_HMAC* SigTicket // out
);
extern TSS_RESULT Tcsip_CMK_CreateBlob
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE parentHandle, // in
TSS_MIGRATE_SCHEME migrationType, // in
UINT32 MigrationKeyAuthSize, // in
BYTE* MigrationKeyAuth, // in
TPM_DIGEST PubSourceKeyDigest, // in
UINT32 msaListSize, // in
BYTE* msaList, // in
UINT32 restrictTicketSize, // in
BYTE* restrictTicket, // in
UINT32 sigTicketSize, // in
BYTE* sigTicket, // in
UINT32 encDataSize, // in
BYTE* encData, // in
TPM_AUTH* parentAuth, // in, out
UINT32* randomSize, // out
BYTE** random, // out
UINT32* outDataSize, // out
BYTE** outData // out
);
extern TSS_RESULT Tcsip_CMK_ConvertMigration
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE parentHandle, // in
TPM_CMK_AUTH restrictTicket, // in
TPM_HMAC sigTicket, // in
UINT32 keyDataSize, // in
BYTE* prgbKeyData, // in
UINT32 msaListSize, // in
BYTE* msaList, // in
UINT32 randomSize, // in
BYTE* random, // in
TPM_AUTH* parentAuth, // in, out
UINT32* outDataSize, // out
BYTE** outData // out
);
extern TSS_RESULT Tcsip_SetCapability
(
TCS_CONTEXT_HANDLE hContext, // in
TPM_CAPABILITY_AREA capArea, // in
UINT32 subCapSize, // in
BYTE* subCap, // in
UINT32 valueSize, // in
BYTE* value, // in
TPM_AUTH* ownerAuth // in, out
);
extern TSS_RESULT Tcsip_GetAuditDigest
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 startOrdinal, // in
TPM_DIGEST* auditDigest, // out
UINT32* counterValueSize, // out
BYTE** counterValue, // out
TSS_BOOL* more, // out
UINT32* ordSize, // out
UINT32** ordList // out
);
extern TSS_RESULT Tcsip_GetAuditDigestSigned
(
TCS_CONTEXT_HANDLE hContext, // in
TCS_KEY_HANDLE keyHandle, // in
TSS_BOOL closeAudit, // in
TPM_NONCE antiReplay, // in
TPM_AUTH* privAuth, // in, out
UINT32* counterValueSize, // out
BYTE** counterValue, // out
TPM_DIGEST* auditDigest, // out
TPM_DIGEST* ordinalDigest, // out
UINT32* sigSize, // out
BYTE** sig // out
);
extern TSS_RESULT Tcsip_SetOrdinalAuditStatus
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 ordinalToAudit, // in
TSS_BOOL auditState, // in
TPM_AUTH* ownerAuth // in, out
);
extern TSS_RESULT Tcsi_Admin_TSS_SessionsPerLocality
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 ulLocality, // in
UINT32 ulSessions, // in
TPM_AUTH* pOwnerAuth // in, out
);
extern TSS_RESULT Tcsi_GetCredential
(
TCS_CONTEXT_HANDLE hContext, // in
UINT32 ulCredentialType, // in
UINT32 ulCredentialAccessMode, // in
UINT32* pulCredentialSize, // out
BYTE** prgbCredentialData // out
);
#endif /* TCS_H */
|
semenzato/trunks
|
tss/include/tss/tcs.h
|
C
|
bsd-3-clause
| 50,985
|
// Copyright 2015 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "snapshot/win/process_snapshot_win.h"
#include <stddef.h>
#include <wchar.h>
#include <algorithm>
#include <utility>
#include "base/cxx17_backports.h"
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "util/misc/from_pointer_cast.h"
#include "util/misc/time.h"
#include "util/win/nt_internals.h"
#include "util/win/registration_protocol_win.h"
namespace crashpad {
ProcessSnapshotWin::ProcessSnapshotWin()
: ProcessSnapshot(),
system_(),
threads_(),
modules_(),
exception_(),
memory_map_(),
process_reader_(),
report_id_(),
client_id_(),
annotations_simple_map_(),
snapshot_time_(),
options_(),
initialized_() {
}
ProcessSnapshotWin::~ProcessSnapshotWin() {
}
bool ProcessSnapshotWin::Initialize(
HANDLE process,
ProcessSuspensionState suspension_state,
WinVMAddress exception_information_address,
WinVMAddress debug_critical_section_address) {
INITIALIZATION_STATE_SET_INITIALIZING(initialized_);
GetTimeOfDay(&snapshot_time_);
if (!process_reader_.Initialize(process, suspension_state))
return false;
if (exception_information_address != 0) {
ExceptionInformation exception_information = {};
if (!process_reader_.Memory()->Read(exception_information_address,
sizeof(exception_information),
&exception_information)) {
LOG(WARNING) << "ReadMemory ExceptionInformation failed";
return false;
}
exception_.reset(new internal::ExceptionSnapshotWin());
if (!exception_->Initialize(&process_reader_,
exception_information.thread_id,
exception_information.exception_pointers)) {
exception_.reset();
return false;
}
}
system_.Initialize(&process_reader_);
if (process_reader_.Is64Bit()) {
InitializePebData<process_types::internal::Traits64>(
debug_critical_section_address);
} else {
InitializePebData<process_types::internal::Traits32>(
debug_critical_section_address);
}
InitializeModules();
InitializeUnloadedModules();
GetCrashpadOptionsInternal(&options_);
InitializeThreads(
options_.gather_indirectly_referenced_memory == TriState::kEnabled,
options_.indirectly_referenced_memory_cap);
for (const MEMORY_BASIC_INFORMATION64& mbi :
process_reader_.GetProcessInfo().MemoryInfo()) {
memory_map_.push_back(
std::make_unique<internal::MemoryMapRegionSnapshotWin>(mbi));
}
for (const auto& module : modules_) {
for (const auto& range : module->ExtraMemoryRanges()) {
AddMemorySnapshot(range.base(), range.size(), &extra_memory_);
}
}
INITIALIZATION_STATE_SET_VALID(initialized_);
return true;
}
void ProcessSnapshotWin::GetCrashpadOptions(
CrashpadInfoClientOptions* options) {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
*options = options_;
}
crashpad::ProcessID ProcessSnapshotWin::ProcessID() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return process_reader_.GetProcessInfo().ProcessID();
}
crashpad::ProcessID ProcessSnapshotWin::ParentProcessID() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return process_reader_.GetProcessInfo().ParentProcessID();
}
void ProcessSnapshotWin::SnapshotTime(timeval* snapshot_time) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
*snapshot_time = snapshot_time_;
}
void ProcessSnapshotWin::ProcessStartTime(timeval* start_time) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
process_reader_.StartTime(start_time);
}
void ProcessSnapshotWin::ProcessCPUTimes(timeval* user_time,
timeval* system_time) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
process_reader_.CPUTimes(user_time, system_time);
}
void ProcessSnapshotWin::ReportID(UUID* report_id) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
*report_id = report_id_;
}
void ProcessSnapshotWin::ClientID(UUID* client_id) const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
*client_id = client_id_;
}
const std::map<std::string, std::string>&
ProcessSnapshotWin::AnnotationsSimpleMap() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return annotations_simple_map_;
}
const SystemSnapshot* ProcessSnapshotWin::System() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return &system_;
}
std::vector<const ThreadSnapshot*> ProcessSnapshotWin::Threads() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
std::vector<const ThreadSnapshot*> threads;
for (const auto& thread : threads_) {
threads.push_back(thread.get());
}
return threads;
}
std::vector<const ModuleSnapshot*> ProcessSnapshotWin::Modules() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
std::vector<const ModuleSnapshot*> modules;
for (const auto& module : modules_) {
modules.push_back(module.get());
}
return modules;
}
std::vector<UnloadedModuleSnapshot> ProcessSnapshotWin::UnloadedModules()
const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return unloaded_modules_;
}
const ExceptionSnapshot* ProcessSnapshotWin::Exception() const {
return exception_.get();
}
std::vector<const MemoryMapRegionSnapshot*> ProcessSnapshotWin::MemoryMap()
const {
std::vector<const MemoryMapRegionSnapshot*> memory_map;
for (const auto& item : memory_map_) {
memory_map.push_back(item.get());
}
return memory_map;
}
std::vector<HandleSnapshot> ProcessSnapshotWin::Handles() const {
std::vector<HandleSnapshot> result;
for (const auto& handle : process_reader_.GetProcessInfo().Handles()) {
HandleSnapshot snapshot;
// This is probably not strictly correct, but these are not localized so we
// expect them all to be in ASCII range anyway. This will need to be more
// carefully done if the object name is added.
snapshot.type_name = base::WideToUTF8(handle.type_name);
snapshot.handle = handle.handle;
snapshot.attributes = handle.attributes;
snapshot.granted_access = handle.granted_access;
snapshot.pointer_count = handle.pointer_count;
snapshot.handle_count = handle.handle_count;
result.push_back(snapshot);
}
return result;
}
std::vector<const MemorySnapshot*> ProcessSnapshotWin::ExtraMemory() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
std::vector<const MemorySnapshot*> extra_memory;
for (const auto& em : extra_memory_) {
extra_memory.push_back(em.get());
}
return extra_memory;
}
const ProcessMemory* ProcessSnapshotWin::Memory() const {
INITIALIZATION_STATE_DCHECK_VALID(initialized_);
return process_reader_.Memory();
}
void ProcessSnapshotWin::InitializeThreads(
bool gather_indirectly_referenced_memory,
uint32_t indirectly_referenced_memory_cap) {
const std::vector<ProcessReaderWin::Thread>& process_reader_threads =
process_reader_.Threads();
uint32_t* budget_remaining_pointer = nullptr;
uint32_t budget_remaining = indirectly_referenced_memory_cap;
if (gather_indirectly_referenced_memory)
budget_remaining_pointer = &budget_remaining;
for (const ProcessReaderWin::Thread& process_reader_thread :
process_reader_threads) {
auto thread = std::make_unique<internal::ThreadSnapshotWin>();
if (thread->Initialize(&process_reader_,
process_reader_thread,
budget_remaining_pointer)) {
threads_.push_back(std::move(thread));
}
}
}
void ProcessSnapshotWin::InitializeModules() {
const std::vector<ProcessInfo::Module>& process_reader_modules =
process_reader_.Modules();
for (const ProcessInfo::Module& process_reader_module :
process_reader_modules) {
auto module = std::make_unique<internal::ModuleSnapshotWin>();
if (module->Initialize(&process_reader_, process_reader_module)) {
modules_.push_back(std::move(module));
}
}
}
void ProcessSnapshotWin::InitializeUnloadedModules() {
// As documented by https://msdn.microsoft.com/library/cc678403.aspx, we can
// retrieve the location for our unload events, and use that address in the
// target process. Unfortunately, this of course only works for 64-reading-64
// and 32-reading-32, so at the moment, we simply do not retrieve unloaded
// modules for 64-reading-32. See https://crashpad.chromium.org/bug/89.
#if defined(ARCH_CPU_X86_64) || defined(ARCH_CPU_ARM64)
if (!process_reader_.Is64Bit()) {
LOG(ERROR)
<< "reading unloaded modules across bitness not currently supported";
return;
}
using Traits = process_types::internal::Traits64;
#elif defined(ARCH_CPU_X86)
using Traits = process_types::internal::Traits32;
#else
#error port
#endif
ULONG* element_size;
ULONG* element_count;
void* event_trace_address;
RtlGetUnloadEventTraceEx(&element_size, &element_count, &event_trace_address);
if (*element_size < sizeof(RTL_UNLOAD_EVENT_TRACE<Traits>)) {
LOG(ERROR) << "unexpected unloaded module list element size";
return;
}
const WinVMAddress address_in_target_process =
FromPointerCast<WinVMAddress>(event_trace_address);
Traits::Pointer pointer_to_array;
if (!process_reader_.Memory()->Read(address_in_target_process,
sizeof(pointer_to_array),
&pointer_to_array)) {
LOG(ERROR) << "failed to read target address";
return;
}
// No unloaded modules.
if (pointer_to_array == 0)
return;
const size_t data_size = *element_size * *element_count;
std::vector<uint8_t> data(data_size);
if (!process_reader_.Memory()->Read(pointer_to_array, data_size, &data[0])) {
LOG(ERROR) << "failed to read unloaded module data";
return;
}
for (ULONG i = 0; i < *element_count; ++i) {
const uint8_t* base_address = &data[i * *element_size];
const auto& uet =
*reinterpret_cast<const RTL_UNLOAD_EVENT_TRACE<Traits>*>(base_address);
if (uet.ImageName[0] != 0) {
unloaded_modules_.push_back(UnloadedModuleSnapshot(
uet.BaseAddress,
uet.SizeOfImage,
uet.CheckSum,
uet.TimeDateStamp,
base::WideToUTF8(base::WStringPiece(
uet.ImageName,
wcsnlen(uet.ImageName, base::size(uet.ImageName))))));
}
}
}
void ProcessSnapshotWin::GetCrashpadOptionsInternal(
CrashpadInfoClientOptions* options) {
CrashpadInfoClientOptions local_options;
for (const auto& module : modules_) {
CrashpadInfoClientOptions module_options;
module->GetCrashpadOptions(&module_options);
if (local_options.crashpad_handler_behavior == TriState::kUnset) {
local_options.crashpad_handler_behavior =
module_options.crashpad_handler_behavior;
}
if (local_options.system_crash_reporter_forwarding == TriState::kUnset) {
local_options.system_crash_reporter_forwarding =
module_options.system_crash_reporter_forwarding;
}
if (local_options.gather_indirectly_referenced_memory == TriState::kUnset) {
local_options.gather_indirectly_referenced_memory =
module_options.gather_indirectly_referenced_memory;
local_options.indirectly_referenced_memory_cap =
module_options.indirectly_referenced_memory_cap;
}
// If non-default values have been found for all options, the loop can end
// early.
if (local_options.crashpad_handler_behavior != TriState::kUnset &&
local_options.system_crash_reporter_forwarding != TriState::kUnset &&
local_options.gather_indirectly_referenced_memory != TriState::kUnset) {
break;
}
}
*options = local_options;
}
template <class Traits>
void ProcessSnapshotWin::InitializePebData(
WinVMAddress debug_critical_section_address) {
WinVMAddress peb_address;
WinVMSize peb_size;
process_reader_.GetProcessInfo().Peb(&peb_address, &peb_size);
AddMemorySnapshot(peb_address, peb_size, &extra_memory_);
process_types::PEB<Traits> peb_data;
if (!process_reader_.Memory()->Read(
peb_address, base::checked_cast<size_t>(peb_size), &peb_data)) {
LOG(ERROR) << "ReadMemory PEB";
return;
}
process_types::PEB_LDR_DATA<Traits> peb_ldr_data;
AddMemorySnapshot(peb_data.Ldr, sizeof(peb_ldr_data), &extra_memory_);
if (!process_reader_.Memory()->Read(
peb_data.Ldr, sizeof(peb_ldr_data), &peb_ldr_data)) {
LOG(ERROR) << "ReadMemory PEB_LDR_DATA";
} else {
// Walk the LDR structure to retrieve its pointed-to data.
AddMemorySnapshotForLdrLIST_ENTRY(
peb_ldr_data.InLoadOrderModuleList,
offsetof(process_types::LDR_DATA_TABLE_ENTRY<Traits>, InLoadOrderLinks),
&extra_memory_);
AddMemorySnapshotForLdrLIST_ENTRY(
peb_ldr_data.InMemoryOrderModuleList,
offsetof(process_types::LDR_DATA_TABLE_ENTRY<Traits>,
InMemoryOrderLinks),
&extra_memory_);
AddMemorySnapshotForLdrLIST_ENTRY(
peb_ldr_data.InInitializationOrderModuleList,
offsetof(process_types::LDR_DATA_TABLE_ENTRY<Traits>,
InInitializationOrderLinks),
&extra_memory_);
}
process_types::RTL_USER_PROCESS_PARAMETERS<Traits> process_parameters;
if (!process_reader_.Memory()->Read(peb_data.ProcessParameters,
sizeof(process_parameters),
&process_parameters)) {
LOG(ERROR) << "ReadMemory RTL_USER_PROCESS_PARAMETERS";
return;
}
AddMemorySnapshot(
peb_data.ProcessParameters, sizeof(process_parameters), &extra_memory_);
AddMemorySnapshotForUNICODE_STRING(
process_parameters.CurrentDirectory.DosPath, &extra_memory_);
AddMemorySnapshotForUNICODE_STRING(process_parameters.DllPath,
&extra_memory_);
AddMemorySnapshotForUNICODE_STRING(process_parameters.ImagePathName,
&extra_memory_);
AddMemorySnapshotForUNICODE_STRING(process_parameters.CommandLine,
&extra_memory_);
AddMemorySnapshotForUNICODE_STRING(process_parameters.WindowTitle,
&extra_memory_);
AddMemorySnapshotForUNICODE_STRING(process_parameters.DesktopInfo,
&extra_memory_);
AddMemorySnapshotForUNICODE_STRING(process_parameters.ShellInfo,
&extra_memory_);
AddMemorySnapshotForUNICODE_STRING(process_parameters.RuntimeData,
&extra_memory_);
AddMemorySnapshot(
process_parameters.Environment,
DetermineSizeOfEnvironmentBlock(process_parameters.Environment),
&extra_memory_);
// Walk the loader lock which is directly referenced by the PEB.
ReadLock<Traits>(peb_data.LoaderLock, &extra_memory_);
// TODO(scottmg): Use debug_critical_section_address to walk the list of
// locks (see history of this file for walking code). In some configurations
// this can walk many thousands of locks, so we may want to get some
// annotation from the client for which locks to grab. Unfortunately, without
// walking the list, the !locks command in windbg won't work because it
// requires the lock pointed to by ntdll!RtlCriticalSectionList, which we
// won't have captured.
}
void ProcessSnapshotWin::AddMemorySnapshot(
WinVMAddress address,
WinVMSize size,
std::vector<std::unique_ptr<internal::MemorySnapshotGeneric>>* into) {
if (size == 0)
return;
if (!process_reader_.GetProcessInfo().LoggingRangeIsFullyReadable(
CheckedRange<WinVMAddress, WinVMSize>(address, size))) {
return;
}
// If we have already added this exact range, don't add it again. This is
// useful for the LDR module lists which are a set of doubly-linked lists, all
// pointing to the same module name strings.
// TODO(scottmg): A more general version of this, handling overlapping,
// contained, etc. https://crashpad.chromium.org/bug/61.
for (const auto& memory_snapshot : *into) {
if (memory_snapshot->Address() == address &&
memory_snapshot->Size() == size) {
return;
}
}
into->push_back(std::make_unique<internal::MemorySnapshotGeneric>());
into->back()->Initialize(process_reader_.Memory(), address, size);
}
template <class Traits>
void ProcessSnapshotWin::AddMemorySnapshotForUNICODE_STRING(
const process_types::UNICODE_STRING<Traits>& us,
std::vector<std::unique_ptr<internal::MemorySnapshotGeneric>>* into) {
AddMemorySnapshot(us.Buffer, us.Length, into);
}
template <class Traits>
void ProcessSnapshotWin::AddMemorySnapshotForLdrLIST_ENTRY(
const process_types::LIST_ENTRY<Traits>& le,
size_t offset_of_member,
std::vector<std::unique_ptr<internal::MemorySnapshotGeneric>>* into) {
// Walk the doubly-linked list of entries, adding the list memory itself, as
// well as pointed-to strings.
typename Traits::Pointer last = le.Blink;
process_types::LDR_DATA_TABLE_ENTRY<Traits> entry;
typename Traits::Pointer cur = le.Flink;
for (;;) {
// |cur| is the pointer to LIST_ENTRY embedded in the LDR_DATA_TABLE_ENTRY.
// So we need to offset back to the beginning of the structure.
if (!process_reader_.Memory()->Read(
cur - offset_of_member, sizeof(entry), &entry)) {
return;
}
AddMemorySnapshot(cur - offset_of_member, sizeof(entry), into);
AddMemorySnapshotForUNICODE_STRING(entry.FullDllName, into);
AddMemorySnapshotForUNICODE_STRING(entry.BaseDllName, into);
process_types::LIST_ENTRY<Traits>* links =
reinterpret_cast<process_types::LIST_ENTRY<Traits>*>(
reinterpret_cast<unsigned char*>(&entry) + offset_of_member);
cur = links->Flink;
if (cur == last)
break;
}
}
WinVMSize ProcessSnapshotWin::DetermineSizeOfEnvironmentBlock(
WinVMAddress start_of_environment_block) {
// https://blogs.msdn.microsoft.com/oldnewthing/20100203-00/?p=15083: On newer
// OSs there's no stated limit, but in practice grabbing 32k characters should
// be more than enough.
std::wstring env_block;
env_block.resize(32768);
size_t bytes_read = process_reader_.Memory()->ReadAvailableMemory(
start_of_environment_block,
env_block.size() * sizeof(env_block[0]),
&env_block[0]);
env_block.resize(
static_cast<unsigned int>(bytes_read / sizeof(env_block[0])));
static constexpr wchar_t terminator[] = {0, 0};
size_t at = env_block.find(std::wstring(terminator, base::size(terminator)));
if (at != std::wstring::npos)
env_block.resize(at + base::size(terminator));
return env_block.size() * sizeof(env_block[0]);
}
template <class Traits>
void ProcessSnapshotWin::ReadLock(
WinVMAddress start,
std::vector<std::unique_ptr<internal::MemorySnapshotGeneric>>* into) {
// We're walking the RTL_CRITICAL_SECTION_DEBUG ProcessLocksList, but starting
// from an actual RTL_CRITICAL_SECTION, so start by getting to the first
// RTL_CRITICAL_SECTION_DEBUG.
process_types::RTL_CRITICAL_SECTION<Traits> critical_section;
if (!process_reader_.Memory()->Read(
start, sizeof(critical_section), &critical_section)) {
LOG(ERROR) << "failed to read RTL_CRITICAL_SECTION";
return;
}
AddMemorySnapshot(
start, sizeof(process_types::RTL_CRITICAL_SECTION<Traits>), into);
constexpr decltype(critical_section.DebugInfo) kInvalid =
static_cast<decltype(critical_section.DebugInfo)>(-1);
if (critical_section.DebugInfo == kInvalid)
return;
AddMemorySnapshot(critical_section.DebugInfo,
sizeof(process_types::RTL_CRITICAL_SECTION_DEBUG<Traits>),
into);
}
} // namespace crashpad
|
nwjs/chromium.src
|
third_party/crashpad/crashpad/snapshot/win/process_snapshot_win.cc
|
C++
|
bsd-3-clause
| 20,529
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
-- | Run sub-processes.
module System.Process.Run
(runCmd
,runCmd'
,callProcess
,callProcess'
,callProcessInheritStderrStdout
,createProcess'
,ProcessExitedUnsuccessfully
,Cmd(..)
)
where
import Control.Exception.Lifted
import Control.Monad (liftM)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger (MonadLogger, logError)
import Control.Monad.Trans.Control (MonadBaseControl)
import Data.Conduit.Process hiding (callProcess)
import Data.Foldable (forM_)
import Data.Text (Text)
import qualified Data.Text as T
import Path (Dir, Abs, Path)
import Path (toFilePath)
import Prelude -- Fix AMP warning
import System.Exit (exitWith, ExitCode (..))
import System.IO
import qualified System.Process
import System.Process.Log
import System.Process.Read
-- | Cmd holds common infos needed to running a process in most cases
data Cmd = Cmd
{ cmdDirectoryToRunIn :: Maybe (Path Abs Dir) -- ^ directory to run in
, cmdCommandToRun :: FilePath -- ^ command to run
, cmdEnvOverride :: EnvOverride
, cmdCommandLineArguments :: [String] -- ^ command line arguments
}
-- | Run the given command in the given directory, inheriting stdout and stderr.
--
-- If it exits with anything but success, prints an error
-- and then calls 'exitWith' to exit the program.
runCmd :: forall (m :: * -> *).
(MonadLogger m,MonadIO m,MonadBaseControl IO m)
=> Cmd
-> Maybe Text -- ^ optional additional error message
-> m ()
runCmd = runCmd' id
runCmd' :: forall (m :: * -> *).
(MonadLogger m,MonadIO m,MonadBaseControl IO m)
=> (CreateProcess -> CreateProcess)
-> Cmd
-> Maybe Text -- ^ optional additional error message
-> m ()
runCmd' modCP cmd@(Cmd{..}) mbErrMsg = do
result <- try (callProcess' modCP cmd)
case result of
Left (ProcessExitedUnsuccessfully _ ec) -> do
$logError $
T.pack $
concat $
[ "Exit code "
, show ec
, " while running "
, show (cmdCommandToRun : cmdCommandLineArguments)
] ++ (case cmdDirectoryToRunIn of
Nothing -> []
Just mbDir -> [" in ", toFilePath mbDir]
)
forM_ mbErrMsg $logError
liftIO (exitWith ec)
Right () -> return ()
-- | Like 'System.Process.callProcess', but takes an optional working directory and
-- environment override, and throws 'ProcessExitedUnsuccessfully' if the
-- process exits unsuccessfully.
--
-- Inherits stdout and stderr.
callProcess :: (MonadIO m, MonadLogger m) => Cmd -> m ()
callProcess = callProcess' id
-- | Like 'System.Process.callProcess', but takes an optional working directory and
-- environment override, and throws 'ProcessExitedUnsuccessfully' if the
-- process exits unsuccessfully.
--
-- Inherits stdout and stderr.
callProcess' :: (MonadIO m, MonadLogger m)
=> (CreateProcess -> CreateProcess) -> Cmd -> m ()
callProcess' modCP cmd = do
c <- liftM modCP (cmdToCreateProcess cmd)
$logCreateProcess c
liftIO $ do
(_, _, _, p) <- System.Process.createProcess c
exit_code <- waitForProcess p
case exit_code of
ExitSuccess -> return ()
ExitFailure _ -> throwIO (ProcessExitedUnsuccessfully c exit_code)
callProcessInheritStderrStdout :: (MonadIO m, MonadLogger m) => Cmd -> m ()
callProcessInheritStderrStdout cmd = do
let inheritOutput cp = cp { std_in = CreatePipe, std_out = Inherit, std_err = Inherit }
callProcess' inheritOutput cmd
-- | Like 'System.Process.Internal.createProcess_', but taking a 'Cmd'.
-- Note that the 'Handle's provided by 'UseHandle' are not closed
-- automatically.
createProcess' :: (MonadIO m, MonadLogger m)
=> String
-> (CreateProcess -> CreateProcess)
-> Cmd
-> m (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
createProcess' tag modCP cmd = do
c <- liftM modCP (cmdToCreateProcess cmd)
$logCreateProcess c
liftIO $ System.Process.createProcess_ tag c
cmdToCreateProcess :: MonadIO m => Cmd -> m CreateProcess
cmdToCreateProcess (Cmd wd cmd0 menv args) = do
cmd <- preProcess wd menv cmd0
return $ (proc cmd args) { delegate_ctlc = True
, cwd = fmap toFilePath wd
, env = envHelper menv }
|
Heather/stack
|
src/System/Process/Run.hs
|
Haskell
|
bsd-3-clause
| 4,928
|
@ECHO OFF
if defined JAVA_HOME (
"%JAVA_HOME%\bin\java" -Xmx512m -jar jsonde.jar
) ELSE (
java -Xmx512m -jar jsonde.jar
)
|
bedrin/jsonde
|
jsonde.deployment/src/main/scripts/jsonde.cmd
|
Batchfile
|
bsd-3-clause
| 122
|
/* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2014, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "slamdemoApp.h" // These are just to avoid weird WX compile issues with UNICODE, etc..
#include "slamdemoMain.h"
#include "CLogView.h"
//(*InternalHeaders(CLogView)
#include <wx/string.h>
#include <wx/intl.h>
#include <wx/font.h>
//*)
//(*IdInit(CLogView)
const long CLogView::ID_TEXTCTRL1 = wxNewId();
const long CLogView::ID_BUTTON1 = wxNewId();
//*)
BEGIN_EVENT_TABLE(CLogView,wxDialog)
//(*EventTable(CLogView)
//*)
END_EVENT_TABLE()
CLogView::CLogView(wxWindow* parent,wxWindowID id,const wxPoint& pos,const wxSize& size)
{
//(*Initialize(CLogView)
wxFlexGridSizer* FlexGridSizer1;
Create(parent, id, _("Log view"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER|wxMAXIMIZE_BOX, _T("id"));
SetClientSize(wxDefaultSize);
Move(wxDefaultPosition);
FlexGridSizer1 = new wxFlexGridSizer(2, 1, 0, 0);
FlexGridSizer1->AddGrowableCol(0);
FlexGridSizer1->AddGrowableRow(0);
edLog = new wxTextCtrl(this, ID_TEXTCTRL1, wxEmptyString, wxDefaultPosition, wxSize(835,437), wxTE_MULTILINE|wxTE_READONLY|wxHSCROLL|wxTE_DONTWRAP, wxDefaultValidator, _T("ID_TEXTCTRL1"));
wxFont edLogFont(wxDEFAULT,wxTELETYPE,wxFONTSTYLE_NORMAL,wxNORMAL,false,wxEmptyString,wxFONTENCODING_DEFAULT);
edLog->SetFont(edLogFont);
FlexGridSizer1->Add(edLog, 1, wxALL|wxEXPAND|wxALIGN_LEFT|wxALIGN_TOP, 5);
btnOk = new wxButton(this, ID_BUTTON1, _("Close"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON1"));
btnOk->SetDefault();
FlexGridSizer1->Add(btnOk, 1, wxALL|wxALIGN_TOP|wxALIGN_CENTER_HORIZONTAL, 5);
SetSizer(FlexGridSizer1);
FlexGridSizer1->Fit(this);
FlexGridSizer1->SetSizeHints(this);
Center();
Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&CLogView::OnbtnOkClick);
//*)
}
CLogView::~CLogView()
{
//(*Destroy(CLogView)
//*)
}
void CLogView::OnbtnOkClick(wxCommandEvent& event)
{
Close();
}
|
samuelpfchoi/mrpt
|
apps/2d-slam-demo/CLogView.cpp
|
C++
|
bsd-3-clause
| 2,547
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE127_Buffer_Underread__CWE839_fgets_06.c
Label Definition File: CWE127_Buffer_Underread__CWE839.label.xml
Template File: sources-sinks-06.tmpl.c
*/
/*
* @description
* CWE: 127 Buffer Underread
* BadSource: fgets Read data from the console using fgets()
* GoodSource: Non-negative but less than 10
* Sinks:
* GoodSink: Ensure the array index is valid
* BadSink : Improperly check the array index by not checking to see if the value is negative
* Flow Variant: 06 Control flow: if(STATIC_CONST_FIVE==5) and if(STATIC_CONST_FIVE!=5)
*
* */
#include "std_testcase.h"
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
/* The variable below is declared "const", so a tool should be able
to identify that reads of this will always give its initialized
value. */
static const int STATIC_CONST_FIVE = 5;
#ifndef OMITBAD
void CWE127_Buffer_Underread__CWE839_fgets_06_bad()
{
int data;
/* Initialize data */
data = -1;
if(STATIC_CONST_FIVE==5)
{
{
char inputBuffer[CHAR_ARRAY_SIZE] = "";
/* POTENTIAL FLAW: Read data from the console using fgets() */
if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL)
{
/* Convert to int */
data = atoi(inputBuffer);
}
else
{
printLine("fgets() failed.");
}
}
}
if(STATIC_CONST_FIVE==5)
{
{
int buffer[10] = { 0 };
/* POTENTIAL FLAW: Attempt to access a negative index of the array
* This check does not check to see if the array index is negative */
if (data < 10)
{
printIntLine(buffer[data]);
}
else
{
printLine("ERROR: Array index is too big.");
}
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second STATIC_CONST_FIVE==5 to STATIC_CONST_FIVE!=5 */
static void goodB2G1()
{
int data;
/* Initialize data */
data = -1;
if(STATIC_CONST_FIVE==5)
{
{
char inputBuffer[CHAR_ARRAY_SIZE] = "";
/* POTENTIAL FLAW: Read data from the console using fgets() */
if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL)
{
/* Convert to int */
data = atoi(inputBuffer);
}
else
{
printLine("fgets() failed.");
}
}
}
if(STATIC_CONST_FIVE!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
{
int buffer[10] = { 0 };
/* FIX: Properly validate the array index and prevent a buffer underread */
if (data >= 0 && data < (10))
{
printIntLine(buffer[data]);
}
else
{
printLine("ERROR: Array index is out-of-bounds");
}
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
int data;
/* Initialize data */
data = -1;
if(STATIC_CONST_FIVE==5)
{
{
char inputBuffer[CHAR_ARRAY_SIZE] = "";
/* POTENTIAL FLAW: Read data from the console using fgets() */
if (fgets(inputBuffer, CHAR_ARRAY_SIZE, stdin) != NULL)
{
/* Convert to int */
data = atoi(inputBuffer);
}
else
{
printLine("fgets() failed.");
}
}
}
if(STATIC_CONST_FIVE==5)
{
{
int buffer[10] = { 0 };
/* FIX: Properly validate the array index and prevent a buffer underread */
if (data >= 0 && data < (10))
{
printIntLine(buffer[data]);
}
else
{
printLine("ERROR: Array index is out-of-bounds");
}
}
}
}
/* goodG2B1() - use goodsource and badsink by changing the first STATIC_CONST_FIVE==5 to STATIC_CONST_FIVE!=5 */
static void goodG2B1()
{
int data;
/* Initialize data */
data = -1;
if(STATIC_CONST_FIVE!=5)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Use a value greater than 0, but less than 10 to avoid attempting to
* access an index of the array in the sink that is out-of-bounds */
data = 7;
}
if(STATIC_CONST_FIVE==5)
{
{
int buffer[10] = { 0 };
/* POTENTIAL FLAW: Attempt to access a negative index of the array
* This check does not check to see if the array index is negative */
if (data < 10)
{
printIntLine(buffer[data]);
}
else
{
printLine("ERROR: Array index is too big.");
}
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
int data;
/* Initialize data */
data = -1;
if(STATIC_CONST_FIVE==5)
{
/* FIX: Use a value greater than 0, but less than 10 to avoid attempting to
* access an index of the array in the sink that is out-of-bounds */
data = 7;
}
if(STATIC_CONST_FIVE==5)
{
{
int buffer[10] = { 0 };
/* POTENTIAL FLAW: Attempt to access a negative index of the array
* This check does not check to see if the array index is negative */
if (data < 10)
{
printIntLine(buffer[data]);
}
else
{
printLine("ERROR: Array index is too big.");
}
}
}
}
void CWE127_Buffer_Underread__CWE839_fgets_06_good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE127_Buffer_Underread__CWE839_fgets_06_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE127_Buffer_Underread__CWE839_fgets_06_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
JianpingZeng/xcc
|
xcc/test/juliet/testcases/CWE127_Buffer_Underread/s01/CWE127_Buffer_Underread__CWE839_fgets_06.c
|
C
|
bsd-3-clause
| 7,206
|
/*****************************************************************************
FFTReal.h
Copyright (c) 2005 Laurent de Soras
--- Legal stuff ---
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*Tab=3***********************************************************************/
#if ! defined (FFTReal_HEADER_INCLUDED)
#define FFTReal_HEADER_INCLUDED
#if defined (_MSC_VER)
#pragma once
#pragma warning (4 : 4250) // "Inherits via dominance."
#endif
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
#include "def.h"
#include "DynArray.h"
#include "OscSinCos.h"
template <class DT>
class FFTReal
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
public:
enum { MAX_BIT_DEPTH = 30 }; // So length can be represented as long int
typedef DT DataType;
explicit FFTReal (long length);
virtual ~FFTReal () {}
long get_length () const;
void do_fft (DataType f [], const DataType x []) const;
void do_ifft (const DataType f [], DataType x []) const;
void rescale (DataType x []) const;
DataType * use_buffer () const;
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
protected:
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
private:
// Over this bit depth, we use direct calculation for sin/cos
enum { TRIGO_BD_LIMIT = 12 };
typedef OscSinCos <DataType> OscType;
void init_br_lut ();
void init_trigo_lut ();
void init_trigo_osc ();
FORCEINLINE const long *
get_br_ptr () const;
FORCEINLINE const DataType *
get_trigo_ptr (int level) const;
FORCEINLINE long
get_trigo_level_index (int level) const;
inline void compute_fft_general (DataType f [], const DataType x []) const;
inline void compute_direct_pass_1_2 (DataType df [], const DataType x []) const;
inline void compute_direct_pass_3 (DataType df [], const DataType sf []) const;
inline void compute_direct_pass_n (DataType df [], const DataType sf [], int pass) const;
inline void compute_direct_pass_n_lut (DataType df [], const DataType sf [], int pass) const;
inline void compute_direct_pass_n_osc (DataType df [], const DataType sf [], int pass) const;
inline void compute_ifft_general (const DataType f [], DataType x []) const;
inline void compute_inverse_pass_n (DataType df [], const DataType sf [], int pass) const;
inline void compute_inverse_pass_n_osc (DataType df [], const DataType sf [], int pass) const;
inline void compute_inverse_pass_n_lut (DataType df [], const DataType sf [], int pass) const;
inline void compute_inverse_pass_3 (DataType df [], const DataType sf []) const;
inline void compute_inverse_pass_1_2 (DataType x [], const DataType sf []) const;
const long _length;
const int _nbr_bits;
DynArray <long>
_br_lut;
DynArray <DataType>
_trigo_lut;
mutable DynArray <DataType>
_buffer;
mutable DynArray <OscType>
_trigo_osc;
/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
private:
FFTReal ();
FFTReal (const FFTReal &other);
FFTReal & operator = (const FFTReal &other);
bool operator == (const FFTReal &other);
bool operator != (const FFTReal &other);
}; // class FFTReal
#include "FFTReal.hpp"
#endif // FFTReal_HEADER_INCLUDED
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
|
chock-mostlyharmless/mostlyharmless
|
voice2/voice1/fft/FFTReal.h
|
C
|
bsd-3-clause
| 4,248
|
#ifndef _AVR_TIME_H_
#define _AVR_TIME_H_
#include <stdint.h>
void avr_time_init(void);
uint32_t avr_time_now(void);
#endif
|
iti-luebeck/HANSE2012
|
hanse_ros/hanse_movingcamera/src/avr_time.h
|
C
|
bsd-3-clause
| 126
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_24) on Tue May 01 09:56:13 CEST 2012 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class net.sourceforge.pmd.lang.ecmascript.ast.ASTArrayComprehension (PMD 5.0.0 API)
</TITLE>
<META NAME="date" CONTENT="2012-05-01">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class net.sourceforge.pmd.lang.ecmascript.ast.ASTArrayComprehension (PMD 5.0.0 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/ast/ASTArrayComprehension.html" title="class in net.sourceforge.pmd.lang.ecmascript.ast"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?net/sourceforge/pmd/lang/ecmascript/ast//class-useASTArrayComprehension.html" target="_top"><B>FRAMES</B></A>
<A HREF="ASTArrayComprehension.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>net.sourceforge.pmd.lang.ecmascript.ast.ASTArrayComprehension</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/ast/ASTArrayComprehension.html" title="class in net.sourceforge.pmd.lang.ecmascript.ast">ASTArrayComprehension</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#net.sourceforge.pmd.lang.ecmascript.ast"><B>net.sourceforge.pmd.lang.ecmascript.ast</B></A></TD>
<TD> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#net.sourceforge.pmd.lang.ecmascript.rule"><B>net.sourceforge.pmd.lang.ecmascript.rule</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="net.sourceforge.pmd.lang.ecmascript.ast"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/ast/ASTArrayComprehension.html" title="class in net.sourceforge.pmd.lang.ecmascript.ast">ASTArrayComprehension</A> in <A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/ast/package-summary.html">net.sourceforge.pmd.lang.ecmascript.ast</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/ast/package-summary.html">net.sourceforge.pmd.lang.ecmascript.ast</A> with parameters of type <A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/ast/ASTArrayComprehension.html" title="class in net.sourceforge.pmd.lang.ecmascript.ast">ASTArrayComprehension</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></CODE></FONT></TD>
<TD><CODE><B>EcmascriptParserVisitorAdapter.</B><B><A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/ast/EcmascriptParserVisitorAdapter.html#visit(net.sourceforge.pmd.lang.ecmascript.ast.ASTArrayComprehension, java.lang.Object)">visit</A></B>(<A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/ast/ASTArrayComprehension.html" title="class in net.sourceforge.pmd.lang.ecmascript.ast">ASTArrayComprehension</A> node,
<A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A> data)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></CODE></FONT></TD>
<TD><CODE><B>EcmascriptParserVisitor.</B><B><A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/ast/EcmascriptParserVisitor.html#visit(net.sourceforge.pmd.lang.ecmascript.ast.ASTArrayComprehension, java.lang.Object)">visit</A></B>(<A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/ast/ASTArrayComprehension.html" title="class in net.sourceforge.pmd.lang.ecmascript.ast">ASTArrayComprehension</A> node,
<A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A> data)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<A NAME="net.sourceforge.pmd.lang.ecmascript.rule"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/ast/ASTArrayComprehension.html" title="class in net.sourceforge.pmd.lang.ecmascript.ast">ASTArrayComprehension</A> in <A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/rule/package-summary.html">net.sourceforge.pmd.lang.ecmascript.rule</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/rule/package-summary.html">net.sourceforge.pmd.lang.ecmascript.rule</A> with parameters of type <A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/ast/ASTArrayComprehension.html" title="class in net.sourceforge.pmd.lang.ecmascript.ast">ASTArrayComprehension</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A></CODE></FONT></TD>
<TD><CODE><B>AbstractEcmascriptRule.</B><B><A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/rule/AbstractEcmascriptRule.html#visit(net.sourceforge.pmd.lang.ecmascript.ast.ASTArrayComprehension, java.lang.Object)">visit</A></B>(<A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/ast/ASTArrayComprehension.html" title="class in net.sourceforge.pmd.lang.ecmascript.ast">ASTArrayComprehension</A> node,
<A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A> data)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../net/sourceforge/pmd/lang/ecmascript/ast/ASTArrayComprehension.html" title="class in net.sourceforge.pmd.lang.ecmascript.ast"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?net/sourceforge/pmd/lang/ecmascript/ast//class-useASTArrayComprehension.html" target="_top"><B>FRAMES</B></A>
<A HREF="ASTArrayComprehension.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2002-2012 <a href="http://pmd.sourceforge.net/">InfoEther</a>. All Rights Reserved.
</BODY>
</HTML>
|
daejunpark/jsaf
|
third_party/pmd/docs/apidocs/net/sourceforge/pmd/lang/ecmascript/ast/class-use/ASTArrayComprehension.html
|
HTML
|
bsd-3-clause
| 12,371
|
/*
* Copyright 2001 The Aerospace Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of The Aerospace Corporation may not be used to endorse or
* promote products derived from this software.
*
* THIS SOFTWARE IS PROVIDED BY THE AEROSPACE CORPORATION ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AEROSPACE CORPORATION BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
/*-
* Copyright (c) 1997, 1998, 2000 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
* NASA Ames Research Center.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <sys/time.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_types.h>
#include <net/if_media.h>
#include <net/route.h>
#include <net80211/ieee80211_ioctl.h>
#include <net80211/ieee80211_freebsd.h>
#include <net80211/ieee80211_superg.h>
#include <net80211/ieee80211_tdma.h>
#include <net80211/ieee80211_mesh.h>
#include <assert.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <stddef.h> /* NB: for offsetof */
#include "ifconfig.h"
#include "regdomain.h"
#ifndef IEEE80211_FIXED_RATE_NONE
#define IEEE80211_FIXED_RATE_NONE 0xff
#endif
/* XXX need these publicly defined or similar */
#ifndef IEEE80211_NODE_AUTH
#define IEEE80211_NODE_AUTH 0x000001 /* authorized for data */
#define IEEE80211_NODE_QOS 0x000002 /* QoS enabled */
#define IEEE80211_NODE_ERP 0x000004 /* ERP enabled */
#define IEEE80211_NODE_PWR_MGT 0x000010 /* power save mode enabled */
#define IEEE80211_NODE_AREF 0x000020 /* authentication ref held */
#define IEEE80211_NODE_HT 0x000040 /* HT enabled */
#define IEEE80211_NODE_HTCOMPAT 0x000080 /* HT setup w/ vendor OUI's */
#define IEEE80211_NODE_WPS 0x000100 /* WPS association */
#define IEEE80211_NODE_TSN 0x000200 /* TSN association */
#define IEEE80211_NODE_AMPDU_RX 0x000400 /* AMPDU rx enabled */
#define IEEE80211_NODE_AMPDU_TX 0x000800 /* AMPDU tx enabled */
#define IEEE80211_NODE_MIMO_PS 0x001000 /* MIMO power save enabled */
#define IEEE80211_NODE_MIMO_RTS 0x002000 /* send RTS in MIMO PS */
#define IEEE80211_NODE_RIFS 0x004000 /* RIFS enabled */
#define IEEE80211_NODE_SGI20 0x008000 /* Short GI in HT20 enabled */
#define IEEE80211_NODE_SGI40 0x010000 /* Short GI in HT40 enabled */
#define IEEE80211_NODE_ASSOCID 0x020000 /* xmit requires associd */
#define IEEE80211_NODE_AMSDU_RX 0x040000 /* AMSDU rx enabled */
#define IEEE80211_NODE_AMSDU_TX 0x080000 /* AMSDU tx enabled */
#endif
#define MAXCHAN 1536 /* max 1.5K channels */
#define MAXCOL 78
static int col;
static char spacer;
static void LINE_INIT(char c);
static void LINE_BREAK(void);
static void LINE_CHECK(const char *fmt, ...);
static const char *modename[IEEE80211_MODE_MAX] = {
[IEEE80211_MODE_AUTO] = "auto",
[IEEE80211_MODE_11A] = "11a",
[IEEE80211_MODE_11B] = "11b",
[IEEE80211_MODE_11G] = "11g",
[IEEE80211_MODE_FH] = "fh",
[IEEE80211_MODE_TURBO_A] = "turboA",
[IEEE80211_MODE_TURBO_G] = "turboG",
[IEEE80211_MODE_STURBO_A] = "sturbo",
[IEEE80211_MODE_11NA] = "11na",
[IEEE80211_MODE_11NG] = "11ng",
[IEEE80211_MODE_HALF] = "half",
[IEEE80211_MODE_QUARTER] = "quarter"
};
static void set80211(int s, int type, int val, int len, void *data);
static int get80211(int s, int type, void *data, int len);
static int get80211len(int s, int type, void *data, int len, int *plen);
static int get80211val(int s, int type, int *val);
static const char *get_string(const char *val, const char *sep,
u_int8_t *buf, int *lenp);
static void print_string(const u_int8_t *buf, int len);
static void print_regdomain(const struct ieee80211_regdomain *, int);
static void print_channels(int, const struct ieee80211req_chaninfo *,
int allchans, int verbose);
static void regdomain_makechannels(struct ieee80211_regdomain_req *,
const struct ieee80211_devcaps_req *);
static const char *mesh_linkstate_string(uint8_t state);
static struct ieee80211req_chaninfo *chaninfo;
static struct ieee80211_regdomain regdomain;
static int gotregdomain = 0;
static struct ieee80211_roamparams_req roamparams;
static int gotroam = 0;
static struct ieee80211_txparams_req txparams;
static int gottxparams = 0;
static struct ieee80211_channel curchan;
static int gotcurchan = 0;
static struct ifmediareq *ifmr;
static int htconf = 0;
static int gothtconf = 0;
static void
gethtconf(int s)
{
if (gothtconf)
return;
if (get80211val(s, IEEE80211_IOC_HTCONF, &htconf) < 0)
warn("unable to get HT configuration information");
gothtconf = 1;
}
/*
* Collect channel info from the kernel. We use this (mostly)
* to handle mapping between frequency and IEEE channel number.
*/
static void
getchaninfo(int s)
{
if (chaninfo != NULL)
return;
chaninfo = malloc(IEEE80211_CHANINFO_SIZE(MAXCHAN));
if (chaninfo == NULL)
errx(1, "no space for channel list");
if (get80211(s, IEEE80211_IOC_CHANINFO, chaninfo,
IEEE80211_CHANINFO_SIZE(MAXCHAN)) < 0)
err(1, "unable to get channel information");
ifmr = ifmedia_getstate(s);
gethtconf(s);
}
static struct regdata *
getregdata(void)
{
static struct regdata *rdp = NULL;
if (rdp == NULL) {
rdp = lib80211_alloc_regdata();
if (rdp == NULL)
errx(-1, "missing or corrupted regdomain database");
}
return rdp;
}
/*
* Given the channel at index i with attributes from,
* check if there is a channel with attributes to in
* the channel table. With suitable attributes this
* allows the caller to look for promotion; e.g. from
* 11b > 11g.
*/
static int
canpromote(int i, int from, int to)
{
const struct ieee80211_channel *fc = &chaninfo->ic_chans[i];
int j;
if ((fc->ic_flags & from) != from)
return i;
/* NB: quick check exploiting ordering of chans w/ same frequency */
if (i+1 < chaninfo->ic_nchans &&
chaninfo->ic_chans[i+1].ic_freq == fc->ic_freq &&
(chaninfo->ic_chans[i+1].ic_flags & to) == to)
return i+1;
/* brute force search in case channel list is not ordered */
for (j = 0; j < chaninfo->ic_nchans; j++) {
const struct ieee80211_channel *tc = &chaninfo->ic_chans[j];
if (j != i &&
tc->ic_freq == fc->ic_freq && (tc->ic_flags & to) == to)
return j;
}
return i;
}
/*
* Handle channel promotion. When a channel is specified with
* only a frequency we want to promote it to the ``best'' channel
* available. The channel list has separate entries for 11b, 11g,
* 11a, and 11n[ga] channels so specifying a frequency w/o any
* attributes requires we upgrade, e.g. from 11b -> 11g. This
* gets complicated when the channel is specified on the same
* command line with a media request that constrains the available
* channe list (e.g. mode 11a); we want to honor that to avoid
* confusing behaviour.
*/
static int
promote(int i)
{
/*
* Query the current mode of the interface in case it's
* constrained (e.g. to 11a). We must do this carefully
* as there may be a pending ifmedia request in which case
* asking the kernel will give us the wrong answer. This
* is an unfortunate side-effect of the way ifconfig is
* structure for modularity (yech).
*
* NB: ifmr is actually setup in getchaninfo (above); we
* assume it's called coincident with to this call so
* we have a ``current setting''; otherwise we must pass
* the socket descriptor down to here so we can make
* the ifmedia_getstate call ourselves.
*/
int chanmode = ifmr != NULL ? IFM_MODE(ifmr->ifm_current) : IFM_AUTO;
/* when ambiguous promote to ``best'' */
/* NB: we abitrarily pick HT40+ over HT40- */
if (chanmode != IFM_IEEE80211_11B)
i = canpromote(i, IEEE80211_CHAN_B, IEEE80211_CHAN_G);
if (chanmode != IFM_IEEE80211_11G && (htconf & 1)) {
i = canpromote(i, IEEE80211_CHAN_G,
IEEE80211_CHAN_G | IEEE80211_CHAN_HT20);
if (htconf & 2) {
i = canpromote(i, IEEE80211_CHAN_G,
IEEE80211_CHAN_G | IEEE80211_CHAN_HT40D);
i = canpromote(i, IEEE80211_CHAN_G,
IEEE80211_CHAN_G | IEEE80211_CHAN_HT40U);
}
}
if (chanmode != IFM_IEEE80211_11A && (htconf & 1)) {
i = canpromote(i, IEEE80211_CHAN_A,
IEEE80211_CHAN_A | IEEE80211_CHAN_HT20);
if (htconf & 2) {
i = canpromote(i, IEEE80211_CHAN_A,
IEEE80211_CHAN_A | IEEE80211_CHAN_HT40D);
i = canpromote(i, IEEE80211_CHAN_A,
IEEE80211_CHAN_A | IEEE80211_CHAN_HT40U);
}
}
return i;
}
static void
mapfreq(struct ieee80211_channel *chan, int freq, int flags)
{
int i;
for (i = 0; i < chaninfo->ic_nchans; i++) {
const struct ieee80211_channel *c = &chaninfo->ic_chans[i];
if (c->ic_freq == freq && (c->ic_flags & flags) == flags) {
if (flags == 0) {
/* when ambiguous promote to ``best'' */
c = &chaninfo->ic_chans[promote(i)];
}
*chan = *c;
return;
}
}
errx(1, "unknown/undefined frequency %u/0x%x", freq, flags);
}
static void
mapchan(struct ieee80211_channel *chan, int ieee, int flags)
{
int i;
for (i = 0; i < chaninfo->ic_nchans; i++) {
const struct ieee80211_channel *c = &chaninfo->ic_chans[i];
if (c->ic_ieee == ieee && (c->ic_flags & flags) == flags) {
if (flags == 0) {
/* when ambiguous promote to ``best'' */
c = &chaninfo->ic_chans[promote(i)];
}
*chan = *c;
return;
}
}
errx(1, "unknown/undefined channel number %d flags 0x%x", ieee, flags);
}
static const struct ieee80211_channel *
getcurchan(int s)
{
if (gotcurchan)
return &curchan;
if (get80211(s, IEEE80211_IOC_CURCHAN, &curchan, sizeof(curchan)) < 0) {
int val;
/* fall back to legacy ioctl */
if (get80211val(s, IEEE80211_IOC_CHANNEL, &val) < 0)
err(-1, "cannot figure out current channel");
getchaninfo(s);
mapchan(&curchan, val, 0);
}
gotcurchan = 1;
return &curchan;
}
static enum ieee80211_phymode
chan2mode(const struct ieee80211_channel *c)
{
if (IEEE80211_IS_CHAN_HTA(c))
return IEEE80211_MODE_11NA;
if (IEEE80211_IS_CHAN_HTG(c))
return IEEE80211_MODE_11NG;
if (IEEE80211_IS_CHAN_108A(c))
return IEEE80211_MODE_TURBO_A;
if (IEEE80211_IS_CHAN_108G(c))
return IEEE80211_MODE_TURBO_G;
if (IEEE80211_IS_CHAN_ST(c))
return IEEE80211_MODE_STURBO_A;
if (IEEE80211_IS_CHAN_FHSS(c))
return IEEE80211_MODE_FH;
if (IEEE80211_IS_CHAN_HALF(c))
return IEEE80211_MODE_HALF;
if (IEEE80211_IS_CHAN_QUARTER(c))
return IEEE80211_MODE_QUARTER;
if (IEEE80211_IS_CHAN_A(c))
return IEEE80211_MODE_11A;
if (IEEE80211_IS_CHAN_ANYG(c))
return IEEE80211_MODE_11G;
if (IEEE80211_IS_CHAN_B(c))
return IEEE80211_MODE_11B;
return IEEE80211_MODE_AUTO;
}
static void
getroam(int s)
{
if (gotroam)
return;
if (get80211(s, IEEE80211_IOC_ROAM,
&roamparams, sizeof(roamparams)) < 0)
err(1, "unable to get roaming parameters");
gotroam = 1;
}
static void
setroam_cb(int s, void *arg)
{
struct ieee80211_roamparams_req *roam = arg;
set80211(s, IEEE80211_IOC_ROAM, 0, sizeof(*roam), roam);
}
static void
gettxparams(int s)
{
if (gottxparams)
return;
if (get80211(s, IEEE80211_IOC_TXPARAMS,
&txparams, sizeof(txparams)) < 0)
err(1, "unable to get transmit parameters");
gottxparams = 1;
}
static void
settxparams_cb(int s, void *arg)
{
struct ieee80211_txparams_req *txp = arg;
set80211(s, IEEE80211_IOC_TXPARAMS, 0, sizeof(*txp), txp);
}
static void
getregdomain(int s)
{
if (gotregdomain)
return;
if (get80211(s, IEEE80211_IOC_REGDOMAIN,
®domain, sizeof(regdomain)) < 0)
err(1, "unable to get regulatory domain info");
gotregdomain = 1;
}
static void
getdevcaps(int s, struct ieee80211_devcaps_req *dc)
{
if (get80211(s, IEEE80211_IOC_DEVCAPS, dc,
IEEE80211_DEVCAPS_SPACE(dc)) < 0)
err(1, "unable to get device capabilities");
}
static void
setregdomain_cb(int s, void *arg)
{
struct ieee80211_regdomain_req *req;
struct ieee80211_regdomain *rd = arg;
struct ieee80211_devcaps_req *dc;
struct regdata *rdp = getregdata();
if (rd->country != NO_COUNTRY) {
const struct country *cc;
/*
* Check current country seting to make sure it's
* compatible with the new regdomain. If not, then
* override it with any default country for this
* SKU. If we cannot arrange a match, then abort.
*/
cc = lib80211_country_findbycc(rdp, rd->country);
if (cc == NULL)
errx(1, "unknown ISO country code %d", rd->country);
if (cc->rd->sku != rd->regdomain) {
const struct regdomain *rp;
/*
* Check if country is incompatible with regdomain.
* To enable multiple regdomains for a country code
* we permit a mismatch between the regdomain and
* the country's associated regdomain when the
* regdomain is setup w/o a default country. For
* example, US is bound to the FCC regdomain but
* we allow US to be combined with FCC3 because FCC3
* has not default country. This allows bogus
* combinations like FCC3+DK which are resolved when
* constructing the channel list by deferring to the
* regdomain to construct the channel list.
*/
rp = lib80211_regdomain_findbysku(rdp, rd->regdomain);
if (rp == NULL)
errx(1, "country %s (%s) is not usable with "
"regdomain %d", cc->isoname, cc->name,
rd->regdomain);
else if (rp->cc != NULL && rp->cc != cc)
errx(1, "country %s (%s) is not usable with "
"regdomain %s", cc->isoname, cc->name,
rp->name);
}
}
/*
* Fetch the device capabilities and calculate the
* full set of netbands for which we request a new
* channel list be constructed. Once that's done we
* push the regdomain info + channel list to the kernel.
*/
dc = malloc(IEEE80211_DEVCAPS_SIZE(MAXCHAN));
if (dc == NULL)
errx(1, "no space for device capabilities");
dc->dc_chaninfo.ic_nchans = MAXCHAN;
getdevcaps(s, dc);
#if 0
if (verbose) {
printf("drivercaps: 0x%x\n", dc->dc_drivercaps);
printf("cryptocaps: 0x%x\n", dc->dc_cryptocaps);
printf("htcaps : 0x%x\n", dc->dc_htcaps);
memcpy(chaninfo, &dc->dc_chaninfo,
IEEE80211_CHANINFO_SPACE(&dc->dc_chaninfo));
print_channels(s, &dc->dc_chaninfo, 1/*allchans*/, 1/*verbose*/);
}
#endif
req = malloc(IEEE80211_REGDOMAIN_SIZE(dc->dc_chaninfo.ic_nchans));
if (req == NULL)
errx(1, "no space for regdomain request");
req->rd = *rd;
regdomain_makechannels(req, dc);
if (verbose) {
LINE_INIT(':');
print_regdomain(rd, 1/*verbose*/);
LINE_BREAK();
/* blech, reallocate channel list for new data */
if (chaninfo != NULL)
free(chaninfo);
chaninfo = malloc(IEEE80211_CHANINFO_SPACE(&req->chaninfo));
if (chaninfo == NULL)
errx(1, "no space for channel list");
memcpy(chaninfo, &req->chaninfo,
IEEE80211_CHANINFO_SPACE(&req->chaninfo));
print_channels(s, &req->chaninfo, 1/*allchans*/, 1/*verbose*/);
}
if (req->chaninfo.ic_nchans == 0)
errx(1, "no channels calculated");
set80211(s, IEEE80211_IOC_REGDOMAIN, 0,
IEEE80211_REGDOMAIN_SPACE(req), req);
free(req);
free(dc);
}
static int
ieee80211_mhz2ieee(int freq, int flags)
{
struct ieee80211_channel chan;
mapfreq(&chan, freq, flags);
return chan.ic_ieee;
}
static int
isanyarg(const char *arg)
{
return (strncmp(arg, "-", 1) == 0 ||
strncasecmp(arg, "any", 3) == 0 || strncasecmp(arg, "off", 3) == 0);
}
static void
set80211ssid(const char *val, int d, int s, const struct afswtch *rafp)
{
int ssid;
int len;
u_int8_t data[IEEE80211_NWID_LEN];
ssid = 0;
len = strlen(val);
if (len > 2 && isdigit((int)val[0]) && val[1] == ':') {
ssid = atoi(val)-1;
val += 2;
}
bzero(data, sizeof(data));
len = sizeof(data);
if (get_string(val, NULL, data, &len) == NULL)
exit(1);
set80211(s, IEEE80211_IOC_SSID, ssid, len, data);
}
static void
set80211meshid(const char *val, int d, int s, const struct afswtch *rafp)
{
int len;
u_int8_t data[IEEE80211_NWID_LEN];
memset(data, 0, sizeof(data));
len = sizeof(data);
if (get_string(val, NULL, data, &len) == NULL)
exit(1);
set80211(s, IEEE80211_IOC_MESH_ID, 0, len, data);
}
static void
set80211stationname(const char *val, int d, int s, const struct afswtch *rafp)
{
int len;
u_int8_t data[33];
bzero(data, sizeof(data));
len = sizeof(data);
get_string(val, NULL, data, &len);
set80211(s, IEEE80211_IOC_STATIONNAME, 0, len, data);
}
/*
* Parse a channel specification for attributes/flags.
* The syntax is:
* freq/xx channel width (5,10,20,40,40+,40-)
* freq:mode channel mode (a,b,g,h,n,t,s,d)
*
* These can be combined in either order; e.g. 2437:ng/40.
* Modes are case insensitive.
*
* The result is not validated here; it's assumed to be
* checked against the channel table fetched from the kernel.
*/
static int
getchannelflags(const char *val, int freq)
{
#define _CHAN_HT 0x80000000
const char *cp;
int flags;
flags = 0;
cp = strchr(val, ':');
if (cp != NULL) {
for (cp++; isalpha((int) *cp); cp++) {
/* accept mixed case */
int c = *cp;
if (isupper(c))
c = tolower(c);
switch (c) {
case 'a': /* 802.11a */
flags |= IEEE80211_CHAN_A;
break;
case 'b': /* 802.11b */
flags |= IEEE80211_CHAN_B;
break;
case 'g': /* 802.11g */
flags |= IEEE80211_CHAN_G;
break;
case 'h': /* ht = 802.11n */
case 'n': /* 802.11n */
flags |= _CHAN_HT; /* NB: private */
break;
case 'd': /* dt = Atheros Dynamic Turbo */
flags |= IEEE80211_CHAN_TURBO;
break;
case 't': /* ht, dt, st, t */
/* dt and unadorned t specify Dynamic Turbo */
if ((flags & (IEEE80211_CHAN_STURBO|_CHAN_HT)) == 0)
flags |= IEEE80211_CHAN_TURBO;
break;
case 's': /* st = Atheros Static Turbo */
flags |= IEEE80211_CHAN_STURBO;
break;
default:
errx(-1, "%s: Invalid channel attribute %c\n",
val, *cp);
}
}
}
cp = strchr(val, '/');
if (cp != NULL) {
char *ep;
u_long cw = strtoul(cp+1, &ep, 10);
switch (cw) {
case 5:
flags |= IEEE80211_CHAN_QUARTER;
break;
case 10:
flags |= IEEE80211_CHAN_HALF;
break;
case 20:
/* NB: this may be removed below */
flags |= IEEE80211_CHAN_HT20;
break;
case 40:
if (ep != NULL && *ep == '+')
flags |= IEEE80211_CHAN_HT40U;
else if (ep != NULL && *ep == '-')
flags |= IEEE80211_CHAN_HT40D;
break;
default:
errx(-1, "%s: Invalid channel width\n", val);
}
}
/*
* Cleanup specifications.
*/
if ((flags & _CHAN_HT) == 0) {
/*
* If user specified freq/20 or freq/40 quietly remove
* HT cw attributes depending on channel use. To give
* an explicit 20/40 width for an HT channel you must
* indicate it is an HT channel since all HT channels
* are also usable for legacy operation; e.g. freq:n/40.
*/
flags &= ~IEEE80211_CHAN_HT;
} else {
/*
* Remove private indicator that this is an HT channel
* and if no explicit channel width has been given
* provide the default settings.
*/
flags &= ~_CHAN_HT;
if ((flags & IEEE80211_CHAN_HT) == 0) {
struct ieee80211_channel chan;
/*
* Consult the channel list to see if we can use
* HT40+ or HT40- (if both the map routines choose).
*/
if (freq > 255)
mapfreq(&chan, freq, 0);
else
mapchan(&chan, freq, 0);
flags |= (chan.ic_flags & IEEE80211_CHAN_HT);
}
}
return flags;
#undef _CHAN_HT
}
static void
getchannel(int s, struct ieee80211_channel *chan, const char *val)
{
int v, flags;
char *eptr;
memset(chan, 0, sizeof(*chan));
if (isanyarg(val)) {
chan->ic_freq = IEEE80211_CHAN_ANY;
return;
}
getchaninfo(s);
errno = 0;
v = strtol(val, &eptr, 10);
if (val[0] == '\0' || val == eptr || errno == ERANGE ||
/* channel may be suffixed with nothing, :flag, or /width */
(eptr[0] != '\0' && eptr[0] != ':' && eptr[0] != '/'))
errx(1, "invalid channel specification%s",
errno == ERANGE ? " (out of range)" : "");
flags = getchannelflags(val, v);
if (v > 255) { /* treat as frequency */
mapfreq(chan, v, flags);
} else {
mapchan(chan, v, flags);
}
}
static void
set80211channel(const char *val, int d, int s, const struct afswtch *rafp)
{
struct ieee80211_channel chan;
getchannel(s, &chan, val);
set80211(s, IEEE80211_IOC_CURCHAN, 0, sizeof(chan), &chan);
}
static void
set80211chanswitch(const char *val, int d, int s, const struct afswtch *rafp)
{
struct ieee80211_chanswitch_req csr;
getchannel(s, &csr.csa_chan, val);
csr.csa_mode = 1;
csr.csa_count = 5;
set80211(s, IEEE80211_IOC_CHANSWITCH, 0, sizeof(csr), &csr);
}
static void
set80211authmode(const char *val, int d, int s, const struct afswtch *rafp)
{
int mode;
if (strcasecmp(val, "none") == 0) {
mode = IEEE80211_AUTH_NONE;
} else if (strcasecmp(val, "open") == 0) {
mode = IEEE80211_AUTH_OPEN;
} else if (strcasecmp(val, "shared") == 0) {
mode = IEEE80211_AUTH_SHARED;
} else if (strcasecmp(val, "8021x") == 0) {
mode = IEEE80211_AUTH_8021X;
} else if (strcasecmp(val, "wpa") == 0) {
mode = IEEE80211_AUTH_WPA;
} else {
errx(1, "unknown authmode");
}
set80211(s, IEEE80211_IOC_AUTHMODE, mode, 0, NULL);
}
static void
set80211powersavemode(const char *val, int d, int s, const struct afswtch *rafp)
{
int mode;
if (strcasecmp(val, "off") == 0) {
mode = IEEE80211_POWERSAVE_OFF;
} else if (strcasecmp(val, "on") == 0) {
mode = IEEE80211_POWERSAVE_ON;
} else if (strcasecmp(val, "cam") == 0) {
mode = IEEE80211_POWERSAVE_CAM;
} else if (strcasecmp(val, "psp") == 0) {
mode = IEEE80211_POWERSAVE_PSP;
} else if (strcasecmp(val, "psp-cam") == 0) {
mode = IEEE80211_POWERSAVE_PSP_CAM;
} else {
errx(1, "unknown powersavemode");
}
set80211(s, IEEE80211_IOC_POWERSAVE, mode, 0, NULL);
}
static void
set80211powersave(const char *val, int d, int s, const struct afswtch *rafp)
{
if (d == 0)
set80211(s, IEEE80211_IOC_POWERSAVE, IEEE80211_POWERSAVE_OFF,
0, NULL);
else
set80211(s, IEEE80211_IOC_POWERSAVE, IEEE80211_POWERSAVE_ON,
0, NULL);
}
static void
set80211powersavesleep(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_POWERSAVESLEEP, atoi(val), 0, NULL);
}
static void
set80211wepmode(const char *val, int d, int s, const struct afswtch *rafp)
{
int mode;
if (strcasecmp(val, "off") == 0) {
mode = IEEE80211_WEP_OFF;
} else if (strcasecmp(val, "on") == 0) {
mode = IEEE80211_WEP_ON;
} else if (strcasecmp(val, "mixed") == 0) {
mode = IEEE80211_WEP_MIXED;
} else {
errx(1, "unknown wep mode");
}
set80211(s, IEEE80211_IOC_WEP, mode, 0, NULL);
}
static void
set80211wep(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_WEP, d, 0, NULL);
}
static int
isundefarg(const char *arg)
{
return (strcmp(arg, "-") == 0 || strncasecmp(arg, "undef", 5) == 0);
}
static void
set80211weptxkey(const char *val, int d, int s, const struct afswtch *rafp)
{
if (isundefarg(val))
set80211(s, IEEE80211_IOC_WEPTXKEY, IEEE80211_KEYIX_NONE, 0, NULL);
else
set80211(s, IEEE80211_IOC_WEPTXKEY, atoi(val)-1, 0, NULL);
}
static void
set80211wepkey(const char *val, int d, int s, const struct afswtch *rafp)
{
int key = 0;
int len;
u_int8_t data[IEEE80211_KEYBUF_SIZE];
if (isdigit((int)val[0]) && val[1] == ':') {
key = atoi(val)-1;
val += 2;
}
bzero(data, sizeof(data));
len = sizeof(data);
get_string(val, NULL, data, &len);
set80211(s, IEEE80211_IOC_WEPKEY, key, len, data);
}
/*
* This function is purely a NetBSD compatibility interface. The NetBSD
* interface is too inflexible, but it's there so we'll support it since
* it's not all that hard.
*/
static void
set80211nwkey(const char *val, int d, int s, const struct afswtch *rafp)
{
int txkey;
int i, len;
u_int8_t data[IEEE80211_KEYBUF_SIZE];
set80211(s, IEEE80211_IOC_WEP, IEEE80211_WEP_ON, 0, NULL);
if (isdigit((int)val[0]) && val[1] == ':') {
txkey = val[0]-'0'-1;
val += 2;
for (i = 0; i < 4; i++) {
bzero(data, sizeof(data));
len = sizeof(data);
val = get_string(val, ",", data, &len);
if (val == NULL)
exit(1);
set80211(s, IEEE80211_IOC_WEPKEY, i, len, data);
}
} else {
bzero(data, sizeof(data));
len = sizeof(data);
get_string(val, NULL, data, &len);
txkey = 0;
set80211(s, IEEE80211_IOC_WEPKEY, 0, len, data);
bzero(data, sizeof(data));
for (i = 1; i < 4; i++)
set80211(s, IEEE80211_IOC_WEPKEY, i, 0, data);
}
set80211(s, IEEE80211_IOC_WEPTXKEY, txkey, 0, NULL);
}
static void
set80211rtsthreshold(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_RTSTHRESHOLD,
isundefarg(val) ? IEEE80211_RTS_MAX : atoi(val), 0, NULL);
}
static void
set80211protmode(const char *val, int d, int s, const struct afswtch *rafp)
{
int mode;
if (strcasecmp(val, "off") == 0) {
mode = IEEE80211_PROTMODE_OFF;
} else if (strcasecmp(val, "cts") == 0) {
mode = IEEE80211_PROTMODE_CTS;
} else if (strncasecmp(val, "rtscts", 3) == 0) {
mode = IEEE80211_PROTMODE_RTSCTS;
} else {
errx(1, "unknown protection mode");
}
set80211(s, IEEE80211_IOC_PROTMODE, mode, 0, NULL);
}
static void
set80211htprotmode(const char *val, int d, int s, const struct afswtch *rafp)
{
int mode;
if (strcasecmp(val, "off") == 0) {
mode = IEEE80211_PROTMODE_OFF;
} else if (strncasecmp(val, "rts", 3) == 0) {
mode = IEEE80211_PROTMODE_RTSCTS;
} else {
errx(1, "unknown protection mode");
}
set80211(s, IEEE80211_IOC_HTPROTMODE, mode, 0, NULL);
}
static void
set80211txpower(const char *val, int d, int s, const struct afswtch *rafp)
{
double v = atof(val);
int txpow;
txpow = (int) (2*v);
if (txpow != 2*v)
errx(-1, "invalid tx power (must be .5 dBm units)");
set80211(s, IEEE80211_IOC_TXPOWER, txpow, 0, NULL);
}
#define IEEE80211_ROAMING_DEVICE 0
#define IEEE80211_ROAMING_AUTO 1
#define IEEE80211_ROAMING_MANUAL 2
static void
set80211roaming(const char *val, int d, int s, const struct afswtch *rafp)
{
int mode;
if (strcasecmp(val, "device") == 0) {
mode = IEEE80211_ROAMING_DEVICE;
} else if (strcasecmp(val, "auto") == 0) {
mode = IEEE80211_ROAMING_AUTO;
} else if (strcasecmp(val, "manual") == 0) {
mode = IEEE80211_ROAMING_MANUAL;
} else {
errx(1, "unknown roaming mode");
}
set80211(s, IEEE80211_IOC_ROAMING, mode, 0, NULL);
}
static void
set80211wme(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_WME, d, 0, NULL);
}
static void
set80211hidessid(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_HIDESSID, d, 0, NULL);
}
static void
set80211apbridge(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_APBRIDGE, d, 0, NULL);
}
static void
set80211fastframes(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_FF, d, 0, NULL);
}
static void
set80211dturbo(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_TURBOP, d, 0, NULL);
}
static void
set80211chanlist(const char *val, int d, int s, const struct afswtch *rafp)
{
struct ieee80211req_chanlist chanlist;
char *temp, *cp, *tp;
temp = malloc(strlen(val) + 1);
if (temp == NULL)
errx(1, "malloc failed");
strcpy(temp, val);
memset(&chanlist, 0, sizeof(chanlist));
cp = temp;
for (;;) {
int first, last, f, c;
tp = strchr(cp, ',');
if (tp != NULL)
*tp++ = '\0';
switch (sscanf(cp, "%u-%u", &first, &last)) {
case 1:
if (first > IEEE80211_CHAN_MAX)
errx(-1, "channel %u out of range, max %u",
first, IEEE80211_CHAN_MAX);
setbit(chanlist.ic_channels, first);
break;
case 2:
if (first > IEEE80211_CHAN_MAX)
errx(-1, "channel %u out of range, max %u",
first, IEEE80211_CHAN_MAX);
if (last > IEEE80211_CHAN_MAX)
errx(-1, "channel %u out of range, max %u",
last, IEEE80211_CHAN_MAX);
if (first > last)
errx(-1, "void channel range, %u > %u",
first, last);
for (f = first; f <= last; f++)
setbit(chanlist.ic_channels, f);
break;
}
if (tp == NULL)
break;
c = *tp;
while (isspace(c))
tp++;
if (!isdigit(c))
break;
cp = tp;
}
set80211(s, IEEE80211_IOC_CHANLIST, 0, sizeof(chanlist), &chanlist);
}
static void
set80211bssid(const char *val, int d, int s, const struct afswtch *rafp)
{
if (!isanyarg(val)) {
char *temp;
struct sockaddr_dl sdl;
temp = malloc(strlen(val) + 2); /* ':' and '\0' */
if (temp == NULL)
errx(1, "malloc failed");
temp[0] = ':';
strcpy(temp + 1, val);
sdl.sdl_len = sizeof(sdl);
link_addr(temp, &sdl);
free(temp);
if (sdl.sdl_alen != IEEE80211_ADDR_LEN)
errx(1, "malformed link-level address");
set80211(s, IEEE80211_IOC_BSSID, 0,
IEEE80211_ADDR_LEN, LLADDR(&sdl));
} else {
uint8_t zerobssid[IEEE80211_ADDR_LEN];
memset(zerobssid, 0, sizeof(zerobssid));
set80211(s, IEEE80211_IOC_BSSID, 0,
IEEE80211_ADDR_LEN, zerobssid);
}
}
static int
getac(const char *ac)
{
if (strcasecmp(ac, "ac_be") == 0 || strcasecmp(ac, "be") == 0)
return WME_AC_BE;
if (strcasecmp(ac, "ac_bk") == 0 || strcasecmp(ac, "bk") == 0)
return WME_AC_BK;
if (strcasecmp(ac, "ac_vi") == 0 || strcasecmp(ac, "vi") == 0)
return WME_AC_VI;
if (strcasecmp(ac, "ac_vo") == 0 || strcasecmp(ac, "vo") == 0)
return WME_AC_VO;
errx(1, "unknown wme access class %s", ac);
}
static
DECL_CMD_FUNC2(set80211cwmin, ac, val)
{
set80211(s, IEEE80211_IOC_WME_CWMIN, atoi(val), getac(ac), NULL);
}
static
DECL_CMD_FUNC2(set80211cwmax, ac, val)
{
set80211(s, IEEE80211_IOC_WME_CWMAX, atoi(val), getac(ac), NULL);
}
static
DECL_CMD_FUNC2(set80211aifs, ac, val)
{
set80211(s, IEEE80211_IOC_WME_AIFS, atoi(val), getac(ac), NULL);
}
static
DECL_CMD_FUNC2(set80211txoplimit, ac, val)
{
set80211(s, IEEE80211_IOC_WME_TXOPLIMIT, atoi(val), getac(ac), NULL);
}
static
DECL_CMD_FUNC(set80211acm, ac, d)
{
set80211(s, IEEE80211_IOC_WME_ACM, 1, getac(ac), NULL);
}
static
DECL_CMD_FUNC(set80211noacm, ac, d)
{
set80211(s, IEEE80211_IOC_WME_ACM, 0, getac(ac), NULL);
}
static
DECL_CMD_FUNC(set80211ackpolicy, ac, d)
{
set80211(s, IEEE80211_IOC_WME_ACKPOLICY, 1, getac(ac), NULL);
}
static
DECL_CMD_FUNC(set80211noackpolicy, ac, d)
{
set80211(s, IEEE80211_IOC_WME_ACKPOLICY, 0, getac(ac), NULL);
}
static
DECL_CMD_FUNC2(set80211bsscwmin, ac, val)
{
set80211(s, IEEE80211_IOC_WME_CWMIN, atoi(val),
getac(ac)|IEEE80211_WMEPARAM_BSS, NULL);
}
static
DECL_CMD_FUNC2(set80211bsscwmax, ac, val)
{
set80211(s, IEEE80211_IOC_WME_CWMAX, atoi(val),
getac(ac)|IEEE80211_WMEPARAM_BSS, NULL);
}
static
DECL_CMD_FUNC2(set80211bssaifs, ac, val)
{
set80211(s, IEEE80211_IOC_WME_AIFS, atoi(val),
getac(ac)|IEEE80211_WMEPARAM_BSS, NULL);
}
static
DECL_CMD_FUNC2(set80211bsstxoplimit, ac, val)
{
set80211(s, IEEE80211_IOC_WME_TXOPLIMIT, atoi(val),
getac(ac)|IEEE80211_WMEPARAM_BSS, NULL);
}
static
DECL_CMD_FUNC(set80211dtimperiod, val, d)
{
set80211(s, IEEE80211_IOC_DTIM_PERIOD, atoi(val), 0, NULL);
}
static
DECL_CMD_FUNC(set80211bintval, val, d)
{
set80211(s, IEEE80211_IOC_BEACON_INTERVAL, atoi(val), 0, NULL);
}
static void
set80211macmac(int s, int op, const char *val)
{
char *temp;
struct sockaddr_dl sdl;
temp = malloc(strlen(val) + 2); /* ':' and '\0' */
if (temp == NULL)
errx(1, "malloc failed");
temp[0] = ':';
strcpy(temp + 1, val);
sdl.sdl_len = sizeof(sdl);
link_addr(temp, &sdl);
free(temp);
if (sdl.sdl_alen != IEEE80211_ADDR_LEN)
errx(1, "malformed link-level address");
set80211(s, op, 0, IEEE80211_ADDR_LEN, LLADDR(&sdl));
}
static
DECL_CMD_FUNC(set80211addmac, val, d)
{
set80211macmac(s, IEEE80211_IOC_ADDMAC, val);
}
static
DECL_CMD_FUNC(set80211delmac, val, d)
{
set80211macmac(s, IEEE80211_IOC_DELMAC, val);
}
static
DECL_CMD_FUNC(set80211kickmac, val, d)
{
char *temp;
struct sockaddr_dl sdl;
struct ieee80211req_mlme mlme;
temp = malloc(strlen(val) + 2); /* ':' and '\0' */
if (temp == NULL)
errx(1, "malloc failed");
temp[0] = ':';
strcpy(temp + 1, val);
sdl.sdl_len = sizeof(sdl);
link_addr(temp, &sdl);
free(temp);
if (sdl.sdl_alen != IEEE80211_ADDR_LEN)
errx(1, "malformed link-level address");
memset(&mlme, 0, sizeof(mlme));
mlme.im_op = IEEE80211_MLME_DEAUTH;
mlme.im_reason = IEEE80211_REASON_AUTH_EXPIRE;
memcpy(mlme.im_macaddr, LLADDR(&sdl), IEEE80211_ADDR_LEN);
set80211(s, IEEE80211_IOC_MLME, 0, sizeof(mlme), &mlme);
}
static
DECL_CMD_FUNC(set80211maccmd, val, d)
{
set80211(s, IEEE80211_IOC_MACCMD, d, 0, NULL);
}
static void
set80211meshrtmac(int s, int req, const char *val)
{
char *temp;
struct sockaddr_dl sdl;
temp = malloc(strlen(val) + 2); /* ':' and '\0' */
if (temp == NULL)
errx(1, "malloc failed");
temp[0] = ':';
strcpy(temp + 1, val);
sdl.sdl_len = sizeof(sdl);
link_addr(temp, &sdl);
free(temp);
if (sdl.sdl_alen != IEEE80211_ADDR_LEN)
errx(1, "malformed link-level address");
set80211(s, IEEE80211_IOC_MESH_RTCMD, req,
IEEE80211_ADDR_LEN, LLADDR(&sdl));
}
static
DECL_CMD_FUNC(set80211addmeshrt, val, d)
{
set80211meshrtmac(s, IEEE80211_MESH_RTCMD_ADD, val);
}
static
DECL_CMD_FUNC(set80211delmeshrt, val, d)
{
set80211meshrtmac(s, IEEE80211_MESH_RTCMD_DELETE, val);
}
static
DECL_CMD_FUNC(set80211meshrtcmd, val, d)
{
set80211(s, IEEE80211_IOC_MESH_RTCMD, d, 0, NULL);
}
static
DECL_CMD_FUNC(set80211hwmprootmode, val, d)
{
int mode;
if (strcasecmp(val, "normal") == 0)
mode = IEEE80211_HWMP_ROOTMODE_NORMAL;
else if (strcasecmp(val, "proactive") == 0)
mode = IEEE80211_HWMP_ROOTMODE_PROACTIVE;
else if (strcasecmp(val, "rann") == 0)
mode = IEEE80211_HWMP_ROOTMODE_RANN;
else
mode = IEEE80211_HWMP_ROOTMODE_DISABLED;
set80211(s, IEEE80211_IOC_HWMP_ROOTMODE, mode, 0, NULL);
}
static
DECL_CMD_FUNC(set80211hwmpmaxhops, val, d)
{
set80211(s, IEEE80211_IOC_HWMP_MAXHOPS, atoi(val), 0, NULL);
}
static void
set80211pureg(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_PUREG, d, 0, NULL);
}
static void
set80211quiet(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_QUIET, d, 0, NULL);
}
static
DECL_CMD_FUNC(set80211quietperiod, val, d)
{
set80211(s, IEEE80211_IOC_QUIET_PERIOD, atoi(val), 0, NULL);
}
static
DECL_CMD_FUNC(set80211quietcount, val, d)
{
set80211(s, IEEE80211_IOC_QUIET_COUNT, atoi(val), 0, NULL);
}
static
DECL_CMD_FUNC(set80211quietduration, val, d)
{
set80211(s, IEEE80211_IOC_QUIET_DUR, atoi(val), 0, NULL);
}
static
DECL_CMD_FUNC(set80211quietoffset, val, d)
{
set80211(s, IEEE80211_IOC_QUIET_OFFSET, atoi(val), 0, NULL);
}
static void
set80211bgscan(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_BGSCAN, d, 0, NULL);
}
static
DECL_CMD_FUNC(set80211bgscanidle, val, d)
{
set80211(s, IEEE80211_IOC_BGSCAN_IDLE, atoi(val), 0, NULL);
}
static
DECL_CMD_FUNC(set80211bgscanintvl, val, d)
{
set80211(s, IEEE80211_IOC_BGSCAN_INTERVAL, atoi(val), 0, NULL);
}
static
DECL_CMD_FUNC(set80211scanvalid, val, d)
{
set80211(s, IEEE80211_IOC_SCANVALID, atoi(val), 0, NULL);
}
/*
* Parse an optional trailing specification of which netbands
* to apply a parameter to. This is basically the same syntax
* as used for channels but you can concatenate to specify
* multiple. For example:
* 14:abg apply to 11a, 11b, and 11g
* 6:ht apply to 11na and 11ng
* We don't make a big effort to catch silly things; this is
* really a convenience mechanism.
*/
static int
getmodeflags(const char *val)
{
const char *cp;
int flags;
flags = 0;
cp = strchr(val, ':');
if (cp != NULL) {
for (cp++; isalpha((int) *cp); cp++) {
/* accept mixed case */
int c = *cp;
if (isupper(c))
c = tolower(c);
switch (c) {
case 'a': /* 802.11a */
flags |= IEEE80211_CHAN_A;
break;
case 'b': /* 802.11b */
flags |= IEEE80211_CHAN_B;
break;
case 'g': /* 802.11g */
flags |= IEEE80211_CHAN_G;
break;
case 'n': /* 802.11n */
flags |= IEEE80211_CHAN_HT;
break;
case 'd': /* dt = Atheros Dynamic Turbo */
flags |= IEEE80211_CHAN_TURBO;
break;
case 't': /* ht, dt, st, t */
/* dt and unadorned t specify Dynamic Turbo */
if ((flags & (IEEE80211_CHAN_STURBO|IEEE80211_CHAN_HT)) == 0)
flags |= IEEE80211_CHAN_TURBO;
break;
case 's': /* st = Atheros Static Turbo */
flags |= IEEE80211_CHAN_STURBO;
break;
case 'h': /* 1/2-width channels */
flags |= IEEE80211_CHAN_HALF;
break;
case 'q': /* 1/4-width channels */
flags |= IEEE80211_CHAN_QUARTER;
break;
default:
errx(-1, "%s: Invalid mode attribute %c\n",
val, *cp);
}
}
}
return flags;
}
#define IEEE80211_CHAN_HTA (IEEE80211_CHAN_HT|IEEE80211_CHAN_5GHZ)
#define IEEE80211_CHAN_HTG (IEEE80211_CHAN_HT|IEEE80211_CHAN_2GHZ)
#define _APPLY(_flags, _base, _param, _v) do { \
if (_flags & IEEE80211_CHAN_HT) { \
if ((_flags & (IEEE80211_CHAN_5GHZ|IEEE80211_CHAN_2GHZ)) == 0) {\
_base.params[IEEE80211_MODE_11NA]._param = _v; \
_base.params[IEEE80211_MODE_11NG]._param = _v; \
} else if (_flags & IEEE80211_CHAN_5GHZ) \
_base.params[IEEE80211_MODE_11NA]._param = _v; \
else \
_base.params[IEEE80211_MODE_11NG]._param = _v; \
} \
if (_flags & IEEE80211_CHAN_TURBO) { \
if ((_flags & (IEEE80211_CHAN_5GHZ|IEEE80211_CHAN_2GHZ)) == 0) {\
_base.params[IEEE80211_MODE_TURBO_A]._param = _v; \
_base.params[IEEE80211_MODE_TURBO_G]._param = _v; \
} else if (_flags & IEEE80211_CHAN_5GHZ) \
_base.params[IEEE80211_MODE_TURBO_A]._param = _v; \
else \
_base.params[IEEE80211_MODE_TURBO_G]._param = _v; \
} \
if (_flags & IEEE80211_CHAN_STURBO) \
_base.params[IEEE80211_MODE_STURBO_A]._param = _v; \
if ((_flags & IEEE80211_CHAN_A) == IEEE80211_CHAN_A) \
_base.params[IEEE80211_MODE_11A]._param = _v; \
if ((_flags & IEEE80211_CHAN_G) == IEEE80211_CHAN_G) \
_base.params[IEEE80211_MODE_11G]._param = _v; \
if ((_flags & IEEE80211_CHAN_B) == IEEE80211_CHAN_B) \
_base.params[IEEE80211_MODE_11B]._param = _v; \
if (_flags & IEEE80211_CHAN_HALF) \
_base.params[IEEE80211_MODE_HALF]._param = _v; \
if (_flags & IEEE80211_CHAN_QUARTER) \
_base.params[IEEE80211_MODE_QUARTER]._param = _v; \
} while (0)
#define _APPLY1(_flags, _base, _param, _v) do { \
if (_flags & IEEE80211_CHAN_HT) { \
if (_flags & IEEE80211_CHAN_5GHZ) \
_base.params[IEEE80211_MODE_11NA]._param = _v; \
else \
_base.params[IEEE80211_MODE_11NG]._param = _v; \
} else if ((_flags & IEEE80211_CHAN_108A) == IEEE80211_CHAN_108A) \
_base.params[IEEE80211_MODE_TURBO_A]._param = _v; \
else if ((_flags & IEEE80211_CHAN_108G) == IEEE80211_CHAN_108G) \
_base.params[IEEE80211_MODE_TURBO_G]._param = _v; \
else if ((_flags & IEEE80211_CHAN_ST) == IEEE80211_CHAN_ST) \
_base.params[IEEE80211_MODE_STURBO_A]._param = _v; \
else if (_flags & IEEE80211_CHAN_HALF) \
_base.params[IEEE80211_MODE_HALF]._param = _v; \
else if (_flags & IEEE80211_CHAN_QUARTER) \
_base.params[IEEE80211_MODE_QUARTER]._param = _v; \
else if ((_flags & IEEE80211_CHAN_A) == IEEE80211_CHAN_A) \
_base.params[IEEE80211_MODE_11A]._param = _v; \
else if ((_flags & IEEE80211_CHAN_G) == IEEE80211_CHAN_G) \
_base.params[IEEE80211_MODE_11G]._param = _v; \
else if ((_flags & IEEE80211_CHAN_B) == IEEE80211_CHAN_B) \
_base.params[IEEE80211_MODE_11B]._param = _v; \
} while (0)
#define _APPLY_RATE(_flags, _base, _param, _v) do { \
if (_flags & IEEE80211_CHAN_HT) { \
(_v) = (_v / 2) | IEEE80211_RATE_MCS; \
} \
_APPLY(_flags, _base, _param, _v); \
} while (0)
#define _APPLY_RATE1(_flags, _base, _param, _v) do { \
if (_flags & IEEE80211_CHAN_HT) { \
(_v) = (_v / 2) | IEEE80211_RATE_MCS; \
} \
_APPLY1(_flags, _base, _param, _v); \
} while (0)
static
DECL_CMD_FUNC(set80211roamrssi, val, d)
{
double v = atof(val);
int rssi, flags;
rssi = (int) (2*v);
if (rssi != 2*v)
errx(-1, "invalid rssi (must be .5 dBm units)");
flags = getmodeflags(val);
getroam(s);
if (flags == 0) { /* NB: no flags => current channel */
flags = getcurchan(s)->ic_flags;
_APPLY1(flags, roamparams, rssi, rssi);
} else
_APPLY(flags, roamparams, rssi, rssi);
callback_register(setroam_cb, &roamparams);
}
static int
getrate(const char *val, const char *tag)
{
double v = atof(val);
int rate;
rate = (int) (2*v);
if (rate != 2*v)
errx(-1, "invalid %s rate (must be .5 Mb/s units)", tag);
return rate; /* NB: returns 2x the specified value */
}
static
DECL_CMD_FUNC(set80211roamrate, val, d)
{
int rate, flags;
rate = getrate(val, "roam");
flags = getmodeflags(val);
getroam(s);
if (flags == 0) { /* NB: no flags => current channel */
flags = getcurchan(s)->ic_flags;
_APPLY_RATE1(flags, roamparams, rate, rate);
} else
_APPLY_RATE(flags, roamparams, rate, rate);
callback_register(setroam_cb, &roamparams);
}
static
DECL_CMD_FUNC(set80211mcastrate, val, d)
{
int rate, flags;
rate = getrate(val, "mcast");
flags = getmodeflags(val);
gettxparams(s);
if (flags == 0) { /* NB: no flags => current channel */
flags = getcurchan(s)->ic_flags;
_APPLY_RATE1(flags, txparams, mcastrate, rate);
} else
_APPLY_RATE(flags, txparams, mcastrate, rate);
callback_register(settxparams_cb, &txparams);
}
static
DECL_CMD_FUNC(set80211mgtrate, val, d)
{
int rate, flags;
rate = getrate(val, "mgmt");
flags = getmodeflags(val);
gettxparams(s);
if (flags == 0) { /* NB: no flags => current channel */
flags = getcurchan(s)->ic_flags;
_APPLY_RATE1(flags, txparams, mgmtrate, rate);
} else
_APPLY_RATE(flags, txparams, mgmtrate, rate);
callback_register(settxparams_cb, &txparams);
}
static
DECL_CMD_FUNC(set80211ucastrate, val, d)
{
int flags;
gettxparams(s);
flags = getmodeflags(val);
if (isanyarg(val)) {
if (flags == 0) { /* NB: no flags => current channel */
flags = getcurchan(s)->ic_flags;
_APPLY1(flags, txparams, ucastrate,
IEEE80211_FIXED_RATE_NONE);
} else
_APPLY(flags, txparams, ucastrate,
IEEE80211_FIXED_RATE_NONE);
} else {
int rate = getrate(val, "ucast");
if (flags == 0) { /* NB: no flags => current channel */
flags = getcurchan(s)->ic_flags;
_APPLY_RATE1(flags, txparams, ucastrate, rate);
} else
_APPLY_RATE(flags, txparams, ucastrate, rate);
}
callback_register(settxparams_cb, &txparams);
}
static
DECL_CMD_FUNC(set80211maxretry, val, d)
{
int v = atoi(val), flags;
flags = getmodeflags(val);
gettxparams(s);
if (flags == 0) { /* NB: no flags => current channel */
flags = getcurchan(s)->ic_flags;
_APPLY1(flags, txparams, maxretry, v);
} else
_APPLY(flags, txparams, maxretry, v);
callback_register(settxparams_cb, &txparams);
}
#undef _APPLY_RATE
#undef _APPLY
#undef IEEE80211_CHAN_HTA
#undef IEEE80211_CHAN_HTG
static
DECL_CMD_FUNC(set80211fragthreshold, val, d)
{
set80211(s, IEEE80211_IOC_FRAGTHRESHOLD,
isundefarg(val) ? IEEE80211_FRAG_MAX : atoi(val), 0, NULL);
}
static
DECL_CMD_FUNC(set80211bmissthreshold, val, d)
{
set80211(s, IEEE80211_IOC_BMISSTHRESHOLD,
isundefarg(val) ? IEEE80211_HWBMISS_MAX : atoi(val), 0, NULL);
}
static void
set80211burst(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_BURST, d, 0, NULL);
}
static void
set80211doth(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_DOTH, d, 0, NULL);
}
static void
set80211dfs(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_DFS, d, 0, NULL);
}
static void
set80211shortgi(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_SHORTGI,
d ? (IEEE80211_HTCAP_SHORTGI20 | IEEE80211_HTCAP_SHORTGI40) : 0,
0, NULL);
}
static void
set80211ampdu(const char *val, int d, int s, const struct afswtch *rafp)
{
int ampdu;
if (get80211val(s, IEEE80211_IOC_AMPDU, &du) < 0)
errx(-1, "cannot get AMPDU setting");
if (d < 0) {
d = -d;
ampdu &= ~d;
} else
ampdu |= d;
set80211(s, IEEE80211_IOC_AMPDU, ampdu, 0, NULL);
}
static
DECL_CMD_FUNC(set80211ampdulimit, val, d)
{
int v;
switch (atoi(val)) {
case 8:
case 8*1024:
v = IEEE80211_HTCAP_MAXRXAMPDU_8K;
break;
case 16:
case 16*1024:
v = IEEE80211_HTCAP_MAXRXAMPDU_16K;
break;
case 32:
case 32*1024:
v = IEEE80211_HTCAP_MAXRXAMPDU_32K;
break;
case 64:
case 64*1024:
v = IEEE80211_HTCAP_MAXRXAMPDU_64K;
break;
default:
errx(-1, "invalid A-MPDU limit %s", val);
}
set80211(s, IEEE80211_IOC_AMPDU_LIMIT, v, 0, NULL);
}
static
DECL_CMD_FUNC(set80211ampdudensity, val, d)
{
int v;
if (isanyarg(val) || strcasecmp(val, "na") == 0)
v = IEEE80211_HTCAP_MPDUDENSITY_NA;
else switch ((int)(atof(val)*4)) {
case 0:
v = IEEE80211_HTCAP_MPDUDENSITY_NA;
break;
case 1:
v = IEEE80211_HTCAP_MPDUDENSITY_025;
break;
case 2:
v = IEEE80211_HTCAP_MPDUDENSITY_05;
break;
case 4:
v = IEEE80211_HTCAP_MPDUDENSITY_1;
break;
case 8:
v = IEEE80211_HTCAP_MPDUDENSITY_2;
break;
case 16:
v = IEEE80211_HTCAP_MPDUDENSITY_4;
break;
case 32:
v = IEEE80211_HTCAP_MPDUDENSITY_8;
break;
case 64:
v = IEEE80211_HTCAP_MPDUDENSITY_16;
break;
default:
errx(-1, "invalid A-MPDU density %s", val);
}
set80211(s, IEEE80211_IOC_AMPDU_DENSITY, v, 0, NULL);
}
static void
set80211amsdu(const char *val, int d, int s, const struct afswtch *rafp)
{
int amsdu;
if (get80211val(s, IEEE80211_IOC_AMSDU, &amsdu) < 0)
err(-1, "cannot get AMSDU setting");
if (d < 0) {
d = -d;
amsdu &= ~d;
} else
amsdu |= d;
set80211(s, IEEE80211_IOC_AMSDU, amsdu, 0, NULL);
}
static
DECL_CMD_FUNC(set80211amsdulimit, val, d)
{
set80211(s, IEEE80211_IOC_AMSDU_LIMIT, atoi(val), 0, NULL);
}
static void
set80211puren(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_PUREN, d, 0, NULL);
}
static void
set80211htcompat(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_HTCOMPAT, d, 0, NULL);
}
static void
set80211htconf(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_HTCONF, d, 0, NULL);
htconf = d;
}
static void
set80211dwds(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_DWDS, d, 0, NULL);
}
static void
set80211inact(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_INACTIVITY, d, 0, NULL);
}
static void
set80211tsn(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_TSN, d, 0, NULL);
}
static void
set80211dotd(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_DOTD, d, 0, NULL);
}
static void
set80211smps(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_SMPS, d, 0, NULL);
}
static void
set80211rifs(const char *val, int d, int s, const struct afswtch *rafp)
{
set80211(s, IEEE80211_IOC_RIFS, d, 0, NULL);
}
static
DECL_CMD_FUNC(set80211tdmaslot, val, d)
{
set80211(s, IEEE80211_IOC_TDMA_SLOT, atoi(val), 0, NULL);
}
static
DECL_CMD_FUNC(set80211tdmaslotcnt, val, d)
{
set80211(s, IEEE80211_IOC_TDMA_SLOTCNT, atoi(val), 0, NULL);
}
static
DECL_CMD_FUNC(set80211tdmaslotlen, val, d)
{
set80211(s, IEEE80211_IOC_TDMA_SLOTLEN, atoi(val), 0, NULL);
}
static
DECL_CMD_FUNC(set80211tdmabintval, val, d)
{
set80211(s, IEEE80211_IOC_TDMA_BINTERVAL, atoi(val), 0, NULL);
}
static
DECL_CMD_FUNC(set80211meshttl, val, d)
{
set80211(s, IEEE80211_IOC_MESH_TTL, atoi(val), 0, NULL);
}
static
DECL_CMD_FUNC(set80211meshforward, val, d)
{
set80211(s, IEEE80211_IOC_MESH_FWRD, d, 0, NULL);
}
static
DECL_CMD_FUNC(set80211meshgate, val, d)
{
set80211(s, IEEE80211_IOC_MESH_GATE, d, 0, NULL);
}
static
DECL_CMD_FUNC(set80211meshpeering, val, d)
{
set80211(s, IEEE80211_IOC_MESH_AP, d, 0, NULL);
}
static
DECL_CMD_FUNC(set80211meshmetric, val, d)
{
char v[12];
memcpy(v, val, sizeof(v));
set80211(s, IEEE80211_IOC_MESH_PR_METRIC, 0, 0, v);
}
static
DECL_CMD_FUNC(set80211meshpath, val, d)
{
char v[12];
memcpy(v, val, sizeof(v));
set80211(s, IEEE80211_IOC_MESH_PR_PATH, 0, 0, v);
}
static int
regdomain_sort(const void *a, const void *b)
{
#define CHAN_ALL \
(IEEE80211_CHAN_ALLTURBO|IEEE80211_CHAN_HALF|IEEE80211_CHAN_QUARTER)
const struct ieee80211_channel *ca = a;
const struct ieee80211_channel *cb = b;
return ca->ic_freq == cb->ic_freq ?
(ca->ic_flags & CHAN_ALL) - (cb->ic_flags & CHAN_ALL) :
ca->ic_freq - cb->ic_freq;
#undef CHAN_ALL
}
static const struct ieee80211_channel *
chanlookup(const struct ieee80211_channel chans[], int nchans,
int freq, int flags)
{
int i;
flags &= IEEE80211_CHAN_ALLTURBO;
for (i = 0; i < nchans; i++) {
const struct ieee80211_channel *c = &chans[i];
if (c->ic_freq == freq &&
(c->ic_flags & IEEE80211_CHAN_ALLTURBO) == flags)
return c;
}
return NULL;
}
static int
chanfind(const struct ieee80211_channel chans[], int nchans, int flags)
{
int i;
for (i = 0; i < nchans; i++) {
const struct ieee80211_channel *c = &chans[i];
if ((c->ic_flags & flags) == flags)
return 1;
}
return 0;
}
/*
* Check channel compatibility.
*/
static int
checkchan(const struct ieee80211req_chaninfo *avail, int freq, int flags)
{
flags &= ~REQ_FLAGS;
/*
* Check if exact channel is in the calibration table;
* everything below is to deal with channels that we
* want to include but that are not explicitly listed.
*/
if (flags & IEEE80211_CHAN_HT40) {
/* NB: we use an HT40 channel center that matches HT20 */
flags = (flags &~ IEEE80211_CHAN_HT40) | IEEE80211_CHAN_HT20;
}
if (chanlookup(avail->ic_chans, avail->ic_nchans, freq, flags) != NULL)
return 1;
if (flags & IEEE80211_CHAN_GSM) {
/*
* XXX GSM frequency mapping is handled in the kernel
* so we cannot find them in the calibration table;
* just accept the channel and the kernel will reject
* the channel list if it's wrong.
*/
return 1;
}
/*
* If this is a 1/2 or 1/4 width channel allow it if a full
* width channel is present for this frequency, and the device
* supports fractional channels on this band. This is a hack
* that avoids bloating the calibration table; it may be better
* by per-band attributes though (we are effectively calculating
* this attribute by scanning the channel list ourself).
*/
if ((flags & (IEEE80211_CHAN_HALF | IEEE80211_CHAN_QUARTER)) == 0)
return 0;
if (chanlookup(avail->ic_chans, avail->ic_nchans, freq,
flags &~ (IEEE80211_CHAN_HALF | IEEE80211_CHAN_QUARTER)) == NULL)
return 0;
if (flags & IEEE80211_CHAN_HALF) {
return chanfind(avail->ic_chans, avail->ic_nchans,
IEEE80211_CHAN_HALF |
(flags & (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_5GHZ)));
} else {
return chanfind(avail->ic_chans, avail->ic_nchans,
IEEE80211_CHAN_QUARTER |
(flags & (IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_5GHZ)));
}
}
static void
regdomain_addchans(struct ieee80211req_chaninfo *ci,
const netband_head *bands,
const struct ieee80211_regdomain *reg,
uint32_t chanFlags,
const struct ieee80211req_chaninfo *avail)
{
const struct netband *nb;
const struct freqband *b;
struct ieee80211_channel *c, *prev;
int freq, hi_adj, lo_adj, channelSep;
uint32_t flags;
hi_adj = (chanFlags & IEEE80211_CHAN_HT40U) ? -20 : 0;
lo_adj = (chanFlags & IEEE80211_CHAN_HT40D) ? 20 : 0;
channelSep = (chanFlags & IEEE80211_CHAN_2GHZ) ? 0 : 40;
LIST_FOREACH(nb, bands, next) {
b = nb->band;
if (verbose) {
printf("%s:", __func__);
printb(" chanFlags", chanFlags, IEEE80211_CHAN_BITS);
printb(" bandFlags", nb->flags | b->flags,
IEEE80211_CHAN_BITS);
putchar('\n');
}
prev = NULL;
for (freq = b->freqStart + lo_adj;
freq <= b->freqEnd + hi_adj; freq += b->chanSep) {
/*
* Construct flags for the new channel. We take
* the attributes from the band descriptions except
* for HT40 which is enabled generically (i.e. +/-
* extension channel) in the band description and
* then constrained according by channel separation.
*/
flags = nb->flags | b->flags;
if (flags & IEEE80211_CHAN_HT) {
/*
* HT channels are generated specially; we're
* called to add HT20, HT40+, and HT40- chan's
* so we need to expand only band specs for
* the HT channel type being added.
*/
if ((chanFlags & IEEE80211_CHAN_HT20) &&
(flags & IEEE80211_CHAN_HT20) == 0) {
if (verbose)
printf("%u: skip, not an "
"HT20 channel\n", freq);
continue;
}
if ((chanFlags & IEEE80211_CHAN_HT40) &&
(flags & IEEE80211_CHAN_HT40) == 0) {
if (verbose)
printf("%u: skip, not an "
"HT40 channel\n", freq);
continue;
}
/* NB: HT attribute comes from caller */
flags &= ~IEEE80211_CHAN_HT;
flags |= chanFlags & IEEE80211_CHAN_HT;
}
/*
* Check if device can operate on this frequency.
*/
if (!checkchan(avail, freq, flags)) {
if (verbose) {
printf("%u: skip, ", freq);
printb("flags", flags,
IEEE80211_CHAN_BITS);
printf(" not available\n");
}
continue;
}
if ((flags & REQ_ECM) && !reg->ecm) {
if (verbose)
printf("%u: skip, ECM channel\n", freq);
continue;
}
if ((flags & REQ_INDOOR) && reg->location == 'O') {
if (verbose)
printf("%u: skip, indoor channel\n",
freq);
continue;
}
if ((flags & REQ_OUTDOOR) && reg->location == 'I') {
if (verbose)
printf("%u: skip, outdoor channel\n",
freq);
continue;
}
if ((flags & IEEE80211_CHAN_HT40) &&
prev != NULL && (freq - prev->ic_freq) < channelSep) {
if (verbose)
printf("%u: skip, only %u channel "
"separation, need %d\n", freq,
freq - prev->ic_freq, channelSep);
continue;
}
if (ci->ic_nchans == IEEE80211_CHAN_MAX) {
if (verbose)
printf("%u: skip, channel table full\n",
freq);
break;
}
c = &ci->ic_chans[ci->ic_nchans++];
memset(c, 0, sizeof(*c));
c->ic_freq = freq;
c->ic_flags = flags;
if (c->ic_flags & IEEE80211_CHAN_DFS)
c->ic_maxregpower = nb->maxPowerDFS;
else
c->ic_maxregpower = nb->maxPower;
if (verbose) {
printf("[%3d] add freq %u ",
ci->ic_nchans-1, c->ic_freq);
printb("flags", c->ic_flags, IEEE80211_CHAN_BITS);
printf(" power %u\n", c->ic_maxregpower);
}
/* NB: kernel fills in other fields */
prev = c;
}
}
}
static void
regdomain_makechannels(
struct ieee80211_regdomain_req *req,
const struct ieee80211_devcaps_req *dc)
{
struct regdata *rdp = getregdata();
const struct country *cc;
const struct ieee80211_regdomain *reg = &req->rd;
struct ieee80211req_chaninfo *ci = &req->chaninfo;
const struct regdomain *rd;
/*
* Locate construction table for new channel list. We treat
* the regdomain/SKU as definitive so a country can be in
* multiple with different properties (e.g. US in FCC+FCC3).
* If no regdomain is specified then we fallback on the country
* code to find the associated regdomain since countries always
* belong to at least one regdomain.
*/
if (reg->regdomain == 0) {
cc = lib80211_country_findbycc(rdp, reg->country);
if (cc == NULL)
errx(1, "internal error, country %d not found",
reg->country);
rd = cc->rd;
} else
rd = lib80211_regdomain_findbysku(rdp, reg->regdomain);
if (rd == NULL)
errx(1, "internal error, regdomain %d not found",
reg->regdomain);
if (rd->sku != SKU_DEBUG) {
/*
* regdomain_addchans incrememnts the channel count for
* each channel it adds so initialize ic_nchans to zero.
* Note that we know we have enough space to hold all possible
* channels because the devcaps list size was used to
* allocate our request.
*/
ci->ic_nchans = 0;
if (!LIST_EMPTY(&rd->bands_11b))
regdomain_addchans(ci, &rd->bands_11b, reg,
IEEE80211_CHAN_B, &dc->dc_chaninfo);
if (!LIST_EMPTY(&rd->bands_11g))
regdomain_addchans(ci, &rd->bands_11g, reg,
IEEE80211_CHAN_G, &dc->dc_chaninfo);
if (!LIST_EMPTY(&rd->bands_11a))
regdomain_addchans(ci, &rd->bands_11a, reg,
IEEE80211_CHAN_A, &dc->dc_chaninfo);
if (!LIST_EMPTY(&rd->bands_11na) && dc->dc_htcaps != 0) {
regdomain_addchans(ci, &rd->bands_11na, reg,
IEEE80211_CHAN_A | IEEE80211_CHAN_HT20,
&dc->dc_chaninfo);
if (dc->dc_htcaps & IEEE80211_HTCAP_CHWIDTH40) {
regdomain_addchans(ci, &rd->bands_11na, reg,
IEEE80211_CHAN_A | IEEE80211_CHAN_HT40U,
&dc->dc_chaninfo);
regdomain_addchans(ci, &rd->bands_11na, reg,
IEEE80211_CHAN_A | IEEE80211_CHAN_HT40D,
&dc->dc_chaninfo);
}
}
if (!LIST_EMPTY(&rd->bands_11ng) && dc->dc_htcaps != 0) {
regdomain_addchans(ci, &rd->bands_11ng, reg,
IEEE80211_CHAN_G | IEEE80211_CHAN_HT20,
&dc->dc_chaninfo);
if (dc->dc_htcaps & IEEE80211_HTCAP_CHWIDTH40) {
regdomain_addchans(ci, &rd->bands_11ng, reg,
IEEE80211_CHAN_G | IEEE80211_CHAN_HT40U,
&dc->dc_chaninfo);
regdomain_addchans(ci, &rd->bands_11ng, reg,
IEEE80211_CHAN_G | IEEE80211_CHAN_HT40D,
&dc->dc_chaninfo);
}
}
qsort(ci->ic_chans, ci->ic_nchans, sizeof(ci->ic_chans[0]),
regdomain_sort);
} else
memcpy(ci, &dc->dc_chaninfo,
IEEE80211_CHANINFO_SPACE(&dc->dc_chaninfo));
}
static void
list_countries(void)
{
struct regdata *rdp = getregdata();
const struct country *cp;
const struct regdomain *dp;
int i;
i = 0;
printf("\nCountry codes:\n");
LIST_FOREACH(cp, &rdp->countries, next) {
printf("%2s %-15.15s%s", cp->isoname,
cp->name, ((i+1)%4) == 0 ? "\n" : " ");
i++;
}
i = 0;
printf("\nRegulatory domains:\n");
LIST_FOREACH(dp, &rdp->domains, next) {
printf("%-15.15s%s", dp->name, ((i+1)%4) == 0 ? "\n" : " ");
i++;
}
printf("\n");
}
static void
defaultcountry(const struct regdomain *rd)
{
struct regdata *rdp = getregdata();
const struct country *cc;
cc = lib80211_country_findbycc(rdp, rd->cc->code);
if (cc == NULL)
errx(1, "internal error, ISO country code %d not "
"defined for regdomain %s", rd->cc->code, rd->name);
regdomain.country = cc->code;
regdomain.isocc[0] = cc->isoname[0];
regdomain.isocc[1] = cc->isoname[1];
}
static
DECL_CMD_FUNC(set80211regdomain, val, d)
{
struct regdata *rdp = getregdata();
const struct regdomain *rd;
rd = lib80211_regdomain_findbyname(rdp, val);
if (rd == NULL) {
char *eptr;
long sku = strtol(val, &eptr, 0);
if (eptr != val)
rd = lib80211_regdomain_findbysku(rdp, sku);
if (eptr == val || rd == NULL)
errx(1, "unknown regdomain %s", val);
}
getregdomain(s);
regdomain.regdomain = rd->sku;
if (regdomain.country == 0 && rd->cc != NULL) {
/*
* No country code setup and there's a default
* one for this regdomain fill it in.
*/
defaultcountry(rd);
}
callback_register(setregdomain_cb, ®domain);
}
static
DECL_CMD_FUNC(set80211country, val, d)
{
struct regdata *rdp = getregdata();
const struct country *cc;
cc = lib80211_country_findbyname(rdp, val);
if (cc == NULL) {
char *eptr;
long code = strtol(val, &eptr, 0);
if (eptr != val)
cc = lib80211_country_findbycc(rdp, code);
if (eptr == val || cc == NULL)
errx(1, "unknown ISO country code %s", val);
}
getregdomain(s);
regdomain.regdomain = cc->rd->sku;
regdomain.country = cc->code;
regdomain.isocc[0] = cc->isoname[0];
regdomain.isocc[1] = cc->isoname[1];
callback_register(setregdomain_cb, ®domain);
}
static void
set80211location(const char *val, int d, int s, const struct afswtch *rafp)
{
getregdomain(s);
regdomain.location = d;
callback_register(setregdomain_cb, ®domain);
}
static void
set80211ecm(const char *val, int d, int s, const struct afswtch *rafp)
{
getregdomain(s);
regdomain.ecm = d;
callback_register(setregdomain_cb, ®domain);
}
static void
LINE_INIT(char c)
{
spacer = c;
if (c == '\t')
col = 8;
else
col = 1;
}
static void
LINE_BREAK(void)
{
if (spacer != '\t') {
printf("\n");
spacer = '\t';
}
col = 8; /* 8-col tab */
}
static void
LINE_CHECK(const char *fmt, ...)
{
char buf[80];
va_list ap;
int n;
va_start(ap, fmt);
n = vsnprintf(buf+1, sizeof(buf)-1, fmt, ap);
va_end(ap);
col += 1+n;
if (col > MAXCOL) {
LINE_BREAK();
col += n;
}
buf[0] = spacer;
printf("%s", buf);
spacer = ' ';
}
static int
getmaxrate(const uint8_t rates[15], uint8_t nrates)
{
int i, maxrate = -1;
for (i = 0; i < nrates; i++) {
int rate = rates[i] & IEEE80211_RATE_VAL;
if (rate > maxrate)
maxrate = rate;
}
return maxrate / 2;
}
static const char *
getcaps(int capinfo)
{
static char capstring[32];
char *cp = capstring;
if (capinfo & IEEE80211_CAPINFO_ESS)
*cp++ = 'E';
if (capinfo & IEEE80211_CAPINFO_IBSS)
*cp++ = 'I';
if (capinfo & IEEE80211_CAPINFO_CF_POLLABLE)
*cp++ = 'c';
if (capinfo & IEEE80211_CAPINFO_CF_POLLREQ)
*cp++ = 'C';
if (capinfo & IEEE80211_CAPINFO_PRIVACY)
*cp++ = 'P';
if (capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)
*cp++ = 'S';
if (capinfo & IEEE80211_CAPINFO_PBCC)
*cp++ = 'B';
if (capinfo & IEEE80211_CAPINFO_CHNL_AGILITY)
*cp++ = 'A';
if (capinfo & IEEE80211_CAPINFO_SHORT_SLOTTIME)
*cp++ = 's';
if (capinfo & IEEE80211_CAPINFO_RSN)
*cp++ = 'R';
if (capinfo & IEEE80211_CAPINFO_DSSSOFDM)
*cp++ = 'D';
*cp = '\0';
return capstring;
}
static const char *
getflags(int flags)
{
static char flagstring[32];
char *cp = flagstring;
if (flags & IEEE80211_NODE_AUTH)
*cp++ = 'A';
if (flags & IEEE80211_NODE_QOS)
*cp++ = 'Q';
if (flags & IEEE80211_NODE_ERP)
*cp++ = 'E';
if (flags & IEEE80211_NODE_PWR_MGT)
*cp++ = 'P';
if (flags & IEEE80211_NODE_HT) {
*cp++ = 'H';
if (flags & IEEE80211_NODE_HTCOMPAT)
*cp++ = '+';
}
if (flags & IEEE80211_NODE_WPS)
*cp++ = 'W';
if (flags & IEEE80211_NODE_TSN)
*cp++ = 'N';
if (flags & IEEE80211_NODE_AMPDU_TX)
*cp++ = 'T';
if (flags & IEEE80211_NODE_AMPDU_RX)
*cp++ = 'R';
if (flags & IEEE80211_NODE_MIMO_PS) {
*cp++ = 'M';
if (flags & IEEE80211_NODE_MIMO_RTS)
*cp++ = '+';
}
if (flags & IEEE80211_NODE_RIFS)
*cp++ = 'I';
if (flags & IEEE80211_NODE_SGI40) {
*cp++ = 'S';
if (flags & IEEE80211_NODE_SGI20)
*cp++ = '+';
} else if (flags & IEEE80211_NODE_SGI20)
*cp++ = 's';
if (flags & IEEE80211_NODE_AMSDU_TX)
*cp++ = 't';
if (flags & IEEE80211_NODE_AMSDU_RX)
*cp++ = 'r';
*cp = '\0';
return flagstring;
}
static void
printie(const char* tag, const uint8_t *ie, size_t ielen, int maxlen)
{
printf("%s", tag);
if (verbose) {
maxlen -= strlen(tag)+2;
if (2*ielen > maxlen)
maxlen--;
printf("<");
for (; ielen > 0; ie++, ielen--) {
if (maxlen-- <= 0)
break;
printf("%02x", *ie);
}
if (ielen != 0)
printf("-");
printf(">");
}
}
#define LE_READ_2(p) \
((u_int16_t) \
((((const u_int8_t *)(p))[0] ) | \
(((const u_int8_t *)(p))[1] << 8)))
#define LE_READ_4(p) \
((u_int32_t) \
((((const u_int8_t *)(p))[0] ) | \
(((const u_int8_t *)(p))[1] << 8) | \
(((const u_int8_t *)(p))[2] << 16) | \
(((const u_int8_t *)(p))[3] << 24)))
/*
* NB: The decoding routines assume a properly formatted ie
* which should be safe as the kernel only retains them
* if they parse ok.
*/
static void
printwmeparam(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
{
#define MS(_v, _f) (((_v) & _f) >> _f##_S)
static const char *acnames[] = { "BE", "BK", "VO", "VI" };
const struct ieee80211_wme_param *wme =
(const struct ieee80211_wme_param *) ie;
int i;
printf("%s", tag);
if (!verbose)
return;
printf("<qosinfo 0x%x", wme->param_qosInfo);
ie += offsetof(struct ieee80211_wme_param, params_acParams);
for (i = 0; i < WME_NUM_AC; i++) {
const struct ieee80211_wme_acparams *ac =
&wme->params_acParams[i];
printf(" %s[%saifsn %u cwmin %u cwmax %u txop %u]"
, acnames[i]
, MS(ac->acp_aci_aifsn, WME_PARAM_ACM) ? "acm " : ""
, MS(ac->acp_aci_aifsn, WME_PARAM_AIFSN)
, MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMIN)
, MS(ac->acp_logcwminmax, WME_PARAM_LOGCWMAX)
, LE_READ_2(&ac->acp_txop)
);
}
printf(">");
#undef MS
}
static void
printwmeinfo(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
{
printf("%s", tag);
if (verbose) {
const struct ieee80211_wme_info *wme =
(const struct ieee80211_wme_info *) ie;
printf("<version 0x%x info 0x%x>",
wme->wme_version, wme->wme_info);
}
}
static void
printhtcap(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
{
printf("%s", tag);
if (verbose) {
const struct ieee80211_ie_htcap *htcap =
(const struct ieee80211_ie_htcap *) ie;
const char *sep;
int i, j;
printf("<cap 0x%x param 0x%x",
LE_READ_2(&htcap->hc_cap), htcap->hc_param);
printf(" mcsset[");
sep = "";
for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++)
if (isset(htcap->hc_mcsset, i)) {
for (j = i+1; j < IEEE80211_HTRATE_MAXSIZE; j++)
if (isclr(htcap->hc_mcsset, j))
break;
j--;
if (i == j)
printf("%s%u", sep, i);
else
printf("%s%u-%u", sep, i, j);
i += j-i;
sep = ",";
}
printf("] extcap 0x%x txbf 0x%x antenna 0x%x>",
LE_READ_2(&htcap->hc_extcap),
LE_READ_4(&htcap->hc_txbf),
htcap->hc_antenna);
}
}
static void
printhtinfo(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
{
printf("%s", tag);
if (verbose) {
const struct ieee80211_ie_htinfo *htinfo =
(const struct ieee80211_ie_htinfo *) ie;
const char *sep;
int i, j;
printf("<ctl %u, %x,%x,%x,%x", htinfo->hi_ctrlchannel,
htinfo->hi_byte1, htinfo->hi_byte2, htinfo->hi_byte3,
LE_READ_2(&htinfo->hi_byte45));
printf(" basicmcs[");
sep = "";
for (i = 0; i < IEEE80211_HTRATE_MAXSIZE; i++)
if (isset(htinfo->hi_basicmcsset, i)) {
for (j = i+1; j < IEEE80211_HTRATE_MAXSIZE; j++)
if (isclr(htinfo->hi_basicmcsset, j))
break;
j--;
if (i == j)
printf("%s%u", sep, i);
else
printf("%s%u-%u", sep, i, j);
i += j-i;
sep = ",";
}
printf("]>");
}
}
static void
printathie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
{
printf("%s", tag);
if (verbose) {
const struct ieee80211_ath_ie *ath =
(const struct ieee80211_ath_ie *)ie;
printf("<");
if (ath->ath_capability & ATHEROS_CAP_TURBO_PRIME)
printf("DTURBO,");
if (ath->ath_capability & ATHEROS_CAP_COMPRESSION)
printf("COMP,");
if (ath->ath_capability & ATHEROS_CAP_FAST_FRAME)
printf("FF,");
if (ath->ath_capability & ATHEROS_CAP_XR)
printf("XR,");
if (ath->ath_capability & ATHEROS_CAP_AR)
printf("AR,");
if (ath->ath_capability & ATHEROS_CAP_BURST)
printf("BURST,");
if (ath->ath_capability & ATHEROS_CAP_WME)
printf("WME,");
if (ath->ath_capability & ATHEROS_CAP_BOOST)
printf("BOOST,");
printf("0x%x>", LE_READ_2(ath->ath_defkeyix));
}
}
static void
printmeshconf(const char *tag, const uint8_t *ie, size_t ielen, int maxlen)
{
#define MATCHOUI(field, oui, string) \
do { \
if (memcmp(field, oui, 4) == 0) \
printf("%s", string); \
} while (0)
printf("%s", tag);
if (verbose) {
const struct ieee80211_meshconf_ie *mconf =
(const struct ieee80211_meshconf_ie *)ie;
printf("<PATH:");
if (mconf->conf_pselid == IEEE80211_MESHCONF_PATH_HWMP)
printf("HWMP");
else
printf("UNKNOWN");
printf(" LINK:");
if (mconf->conf_pmetid == IEEE80211_MESHCONF_METRIC_AIRTIME)
printf("AIRTIME");
else
printf("UNKNOWN");
printf(" CONGESTION:");
if (mconf->conf_ccid == IEEE80211_MESHCONF_CC_DISABLED)
printf("DISABLED");
else
printf("UNKNOWN");
printf(" SYNC:");
if (mconf->conf_syncid == IEEE80211_MESHCONF_SYNC_NEIGHOFF)
printf("NEIGHOFF");
else
printf("UNKNOWN");
printf(" AUTH:");
if (mconf->conf_authid == IEEE80211_MESHCONF_AUTH_DISABLED)
printf("DISABLED");
else
printf("UNKNOWN");
printf(" FORM:0x%x CAPS:0x%x>", mconf->conf_form,
mconf->conf_cap);
}
#undef MATCHOUI
}
static const char *
wpa_cipher(const u_int8_t *sel)
{
#define WPA_SEL(x) (((x)<<24)|WPA_OUI)
u_int32_t w = LE_READ_4(sel);
switch (w) {
case WPA_SEL(WPA_CSE_NULL):
return "NONE";
case WPA_SEL(WPA_CSE_WEP40):
return "WEP40";
case WPA_SEL(WPA_CSE_WEP104):
return "WEP104";
case WPA_SEL(WPA_CSE_TKIP):
return "TKIP";
case WPA_SEL(WPA_CSE_CCMP):
return "AES-CCMP";
}
return "?"; /* NB: so 1<< is discarded */
#undef WPA_SEL
}
static const char *
wpa_keymgmt(const u_int8_t *sel)
{
#define WPA_SEL(x) (((x)<<24)|WPA_OUI)
u_int32_t w = LE_READ_4(sel);
switch (w) {
case WPA_SEL(WPA_ASE_8021X_UNSPEC):
return "8021X-UNSPEC";
case WPA_SEL(WPA_ASE_8021X_PSK):
return "8021X-PSK";
case WPA_SEL(WPA_ASE_NONE):
return "NONE";
}
return "?";
#undef WPA_SEL
}
static void
printwpaie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
{
u_int8_t len = ie[1];
printf("%s", tag);
if (verbose) {
const char *sep;
int n;
ie += 6, len -= 4; /* NB: len is payload only */
printf("<v%u", LE_READ_2(ie));
ie += 2, len -= 2;
printf(" mc:%s", wpa_cipher(ie));
ie += 4, len -= 4;
/* unicast ciphers */
n = LE_READ_2(ie);
ie += 2, len -= 2;
sep = " uc:";
for (; n > 0; n--) {
printf("%s%s", sep, wpa_cipher(ie));
ie += 4, len -= 4;
sep = "+";
}
/* key management algorithms */
n = LE_READ_2(ie);
ie += 2, len -= 2;
sep = " km:";
for (; n > 0; n--) {
printf("%s%s", sep, wpa_keymgmt(ie));
ie += 4, len -= 4;
sep = "+";
}
if (len > 2) /* optional capabilities */
printf(", caps 0x%x", LE_READ_2(ie));
printf(">");
}
}
static const char *
rsn_cipher(const u_int8_t *sel)
{
#define RSN_SEL(x) (((x)<<24)|RSN_OUI)
u_int32_t w = LE_READ_4(sel);
switch (w) {
case RSN_SEL(RSN_CSE_NULL):
return "NONE";
case RSN_SEL(RSN_CSE_WEP40):
return "WEP40";
case RSN_SEL(RSN_CSE_WEP104):
return "WEP104";
case RSN_SEL(RSN_CSE_TKIP):
return "TKIP";
case RSN_SEL(RSN_CSE_CCMP):
return "AES-CCMP";
case RSN_SEL(RSN_CSE_WRAP):
return "AES-OCB";
}
return "?";
#undef WPA_SEL
}
static const char *
rsn_keymgmt(const u_int8_t *sel)
{
#define RSN_SEL(x) (((x)<<24)|RSN_OUI)
u_int32_t w = LE_READ_4(sel);
switch (w) {
case RSN_SEL(RSN_ASE_8021X_UNSPEC):
return "8021X-UNSPEC";
case RSN_SEL(RSN_ASE_8021X_PSK):
return "8021X-PSK";
case RSN_SEL(RSN_ASE_NONE):
return "NONE";
}
return "?";
#undef RSN_SEL
}
static void
printrsnie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
{
printf("%s", tag);
if (verbose) {
const char *sep;
int n;
ie += 2, ielen -= 2;
printf("<v%u", LE_READ_2(ie));
ie += 2, ielen -= 2;
printf(" mc:%s", rsn_cipher(ie));
ie += 4, ielen -= 4;
/* unicast ciphers */
n = LE_READ_2(ie);
ie += 2, ielen -= 2;
sep = " uc:";
for (; n > 0; n--) {
printf("%s%s", sep, rsn_cipher(ie));
ie += 4, ielen -= 4;
sep = "+";
}
/* key management algorithms */
n = LE_READ_2(ie);
ie += 2, ielen -= 2;
sep = " km:";
for (; n > 0; n--) {
printf("%s%s", sep, rsn_keymgmt(ie));
ie += 4, ielen -= 4;
sep = "+";
}
if (ielen > 2) /* optional capabilities */
printf(", caps 0x%x", LE_READ_2(ie));
/* XXXPMKID */
printf(">");
}
}
/* XXX move to a public include file */
#define IEEE80211_WPS_DEV_PASS_ID 0x1012
#define IEEE80211_WPS_SELECTED_REG 0x1041
#define IEEE80211_WPS_SETUP_STATE 0x1044
#define IEEE80211_WPS_UUID_E 0x1047
#define IEEE80211_WPS_VERSION 0x104a
#define BE_READ_2(p) \
((u_int16_t) \
((((const u_int8_t *)(p))[1] ) | \
(((const u_int8_t *)(p))[0] << 8)))
static void
printwpsie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
{
#define N(a) (sizeof(a) / sizeof(a[0]))
u_int8_t len = ie[1];
printf("%s", tag);
if (verbose) {
static const char *dev_pass_id[] = {
"D", /* Default (PIN) */
"U", /* User-specified */
"M", /* Machine-specified */
"K", /* Rekey */
"P", /* PushButton */
"R" /* Registrar-specified */
};
int n;
ie +=6, len -= 4; /* NB: len is payload only */
/* WPS IE in Beacon and Probe Resp frames have different fields */
printf("<");
while (len) {
uint16_t tlv_type = BE_READ_2(ie);
uint16_t tlv_len = BE_READ_2(ie + 2);
ie += 4, len -= 4;
switch (tlv_type) {
case IEEE80211_WPS_VERSION:
printf("v:%d.%d", *ie >> 4, *ie & 0xf);
break;
case IEEE80211_WPS_SETUP_STATE:
/* Only 1 and 2 are valid */
if (*ie == 0 || *ie >= 3)
printf(" state:B");
else
printf(" st:%s", *ie == 1 ? "N" : "C");
break;
case IEEE80211_WPS_SELECTED_REG:
printf(" sel:%s", *ie ? "T" : "F");
break;
case IEEE80211_WPS_DEV_PASS_ID:
n = LE_READ_2(ie);
if (n < N(dev_pass_id))
printf(" dpi:%s", dev_pass_id[n]);
break;
case IEEE80211_WPS_UUID_E:
printf(" uuid-e:");
for (n = 0; n < (tlv_len - 1); n++)
printf("%02x-", ie[n]);
printf("%02x", ie[n]);
break;
}
ie += tlv_len, len -= tlv_len;
}
printf(">");
}
#undef N
}
static void
printtdmaie(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
{
printf("%s", tag);
if (verbose && ielen >= sizeof(struct ieee80211_tdma_param)) {
const struct ieee80211_tdma_param *tdma =
(const struct ieee80211_tdma_param *) ie;
/* XXX tstamp */
printf("<v%u slot:%u slotcnt:%u slotlen:%u bintval:%u inuse:0x%x>",
tdma->tdma_version, tdma->tdma_slot, tdma->tdma_slotcnt,
LE_READ_2(&tdma->tdma_slotlen), tdma->tdma_bintval,
tdma->tdma_inuse[0]);
}
}
/*
* Copy the ssid string contents into buf, truncating to fit. If the
* ssid is entirely printable then just copy intact. Otherwise convert
* to hexadecimal. If the result is truncated then replace the last
* three characters with "...".
*/
static int
copy_essid(char buf[], size_t bufsize, const u_int8_t *essid, size_t essid_len)
{
const u_int8_t *p;
size_t maxlen;
int i;
if (essid_len > bufsize)
maxlen = bufsize;
else
maxlen = essid_len;
/* determine printable or not */
for (i = 0, p = essid; i < maxlen; i++, p++) {
if (*p < ' ' || *p > 0x7e)
break;
}
if (i != maxlen) { /* not printable, print as hex */
if (bufsize < 3)
return 0;
strlcpy(buf, "0x", bufsize);
bufsize -= 2;
p = essid;
for (i = 0; i < maxlen && bufsize >= 2; i++) {
sprintf(&buf[2+2*i], "%02x", p[i]);
bufsize -= 2;
}
if (i != essid_len)
memcpy(&buf[2+2*i-3], "...", 3);
} else { /* printable, truncate as needed */
memcpy(buf, essid, maxlen);
if (maxlen != essid_len)
memcpy(&buf[maxlen-3], "...", 3);
}
return maxlen;
}
static void
printssid(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
{
char ssid[2*IEEE80211_NWID_LEN+1];
printf("%s<%.*s>", tag, copy_essid(ssid, maxlen, ie+2, ie[1]), ssid);
}
static void
printrates(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
{
const char *sep;
int i;
printf("%s", tag);
sep = "<";
for (i = 2; i < ielen; i++) {
printf("%s%s%d", sep,
ie[i] & IEEE80211_RATE_BASIC ? "B" : "",
ie[i] & IEEE80211_RATE_VAL);
sep = ",";
}
printf(">");
}
static void
printcountry(const char *tag, const u_int8_t *ie, size_t ielen, int maxlen)
{
const struct ieee80211_country_ie *cie =
(const struct ieee80211_country_ie *) ie;
int i, nbands, schan, nchan;
printf("%s<%c%c%c", tag, cie->cc[0], cie->cc[1], cie->cc[2]);
nbands = (cie->len - 3) / sizeof(cie->band[0]);
for (i = 0; i < nbands; i++) {
schan = cie->band[i].schan;
nchan = cie->band[i].nchan;
if (nchan != 1)
printf(" %u-%u,%u", schan, schan + nchan-1,
cie->band[i].maxtxpwr);
else
printf(" %u,%u", schan, cie->band[i].maxtxpwr);
}
printf(">");
}
/* unaligned little endian access */
#define LE_READ_4(p) \
((u_int32_t) \
((((const u_int8_t *)(p))[0] ) | \
(((const u_int8_t *)(p))[1] << 8) | \
(((const u_int8_t *)(p))[2] << 16) | \
(((const u_int8_t *)(p))[3] << 24)))
static __inline int
iswpaoui(const u_int8_t *frm)
{
return frm[1] > 3 && LE_READ_4(frm+2) == ((WPA_OUI_TYPE<<24)|WPA_OUI);
}
static __inline int
iswmeinfo(const u_int8_t *frm)
{
return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
frm[6] == WME_INFO_OUI_SUBTYPE;
}
static __inline int
iswmeparam(const u_int8_t *frm)
{
return frm[1] > 5 && LE_READ_4(frm+2) == ((WME_OUI_TYPE<<24)|WME_OUI) &&
frm[6] == WME_PARAM_OUI_SUBTYPE;
}
static __inline int
isatherosoui(const u_int8_t *frm)
{
return frm[1] > 3 && LE_READ_4(frm+2) == ((ATH_OUI_TYPE<<24)|ATH_OUI);
}
static __inline int
istdmaoui(const uint8_t *frm)
{
return frm[1] > 3 && LE_READ_4(frm+2) == ((TDMA_OUI_TYPE<<24)|TDMA_OUI);
}
static __inline int
iswpsoui(const uint8_t *frm)
{
return frm[1] > 3 && LE_READ_4(frm+2) == ((WPS_OUI_TYPE<<24)|WPA_OUI);
}
static const char *
iename(int elemid)
{
switch (elemid) {
case IEEE80211_ELEMID_FHPARMS: return " FHPARMS";
case IEEE80211_ELEMID_CFPARMS: return " CFPARMS";
case IEEE80211_ELEMID_TIM: return " TIM";
case IEEE80211_ELEMID_IBSSPARMS:return " IBSSPARMS";
case IEEE80211_ELEMID_CHALLENGE:return " CHALLENGE";
case IEEE80211_ELEMID_PWRCNSTR: return " PWRCNSTR";
case IEEE80211_ELEMID_PWRCAP: return " PWRCAP";
case IEEE80211_ELEMID_TPCREQ: return " TPCREQ";
case IEEE80211_ELEMID_TPCREP: return " TPCREP";
case IEEE80211_ELEMID_SUPPCHAN: return " SUPPCHAN";
case IEEE80211_ELEMID_CSA: return " CSA";
case IEEE80211_ELEMID_MEASREQ: return " MEASREQ";
case IEEE80211_ELEMID_MEASREP: return " MEASREP";
case IEEE80211_ELEMID_QUIET: return " QUIET";
case IEEE80211_ELEMID_IBSSDFS: return " IBSSDFS";
case IEEE80211_ELEMID_TPC: return " TPC";
case IEEE80211_ELEMID_CCKM: return " CCKM";
}
return " ???";
}
static void
printies(const u_int8_t *vp, int ielen, int maxcols)
{
while (ielen > 0) {
switch (vp[0]) {
case IEEE80211_ELEMID_SSID:
if (verbose)
printssid(" SSID", vp, 2+vp[1], maxcols);
break;
case IEEE80211_ELEMID_RATES:
case IEEE80211_ELEMID_XRATES:
if (verbose)
printrates(vp[0] == IEEE80211_ELEMID_RATES ?
" RATES" : " XRATES", vp, 2+vp[1], maxcols);
break;
case IEEE80211_ELEMID_DSPARMS:
if (verbose)
printf(" DSPARMS<%u>", vp[2]);
break;
case IEEE80211_ELEMID_COUNTRY:
if (verbose)
printcountry(" COUNTRY", vp, 2+vp[1], maxcols);
break;
case IEEE80211_ELEMID_ERP:
if (verbose)
printf(" ERP<0x%x>", vp[2]);
break;
case IEEE80211_ELEMID_VENDOR:
if (iswpaoui(vp))
printwpaie(" WPA", vp, 2+vp[1], maxcols);
else if (iswmeinfo(vp))
printwmeinfo(" WME", vp, 2+vp[1], maxcols);
else if (iswmeparam(vp))
printwmeparam(" WME", vp, 2+vp[1], maxcols);
else if (isatherosoui(vp))
printathie(" ATH", vp, 2+vp[1], maxcols);
else if (iswpsoui(vp))
printwpsie(" WPS", vp, 2+vp[1], maxcols);
else if (istdmaoui(vp))
printtdmaie(" TDMA", vp, 2+vp[1], maxcols);
else if (verbose)
printie(" VEN", vp, 2+vp[1], maxcols);
break;
case IEEE80211_ELEMID_RSN:
printrsnie(" RSN", vp, 2+vp[1], maxcols);
break;
case IEEE80211_ELEMID_HTCAP:
printhtcap(" HTCAP", vp, 2+vp[1], maxcols);
break;
case IEEE80211_ELEMID_HTINFO:
if (verbose)
printhtinfo(" HTINFO", vp, 2+vp[1], maxcols);
break;
case IEEE80211_ELEMID_MESHID:
if (verbose)
printssid(" MESHID", vp, 2+vp[1], maxcols);
break;
case IEEE80211_ELEMID_MESHCONF:
printmeshconf(" MESHCONF", vp, 2+vp[1], maxcols);
break;
default:
if (verbose)
printie(iename(vp[0]), vp, 2+vp[1], maxcols);
break;
}
ielen -= 2+vp[1];
vp += 2+vp[1];
}
}
static void
printmimo(const struct ieee80211_mimo_info *mi)
{
/* NB: don't muddy display unless there's something to show */
if (mi->rssi[0] != 0 || mi->rssi[1] != 0 || mi->rssi[2] != 0) {
/* XXX ignore EVM for now */
printf(" (rssi %d:%d:%d nf %d:%d:%d)",
mi->rssi[0], mi->rssi[1], mi->rssi[2],
mi->noise[0], mi->noise[1], mi->noise[2]);
}
}
static void
list_scan(int s)
{
uint8_t buf[24*1024];
char ssid[IEEE80211_NWID_LEN+1];
const uint8_t *cp;
int len, ssidmax, idlen;
if (get80211len(s, IEEE80211_IOC_SCAN_RESULTS, buf, sizeof(buf), &len) < 0)
errx(1, "unable to get scan results");
if (len < sizeof(struct ieee80211req_scan_result))
return;
getchaninfo(s);
ssidmax = verbose ? IEEE80211_NWID_LEN - 1 : 14;
printf("%-*.*s %-17.17s %4s %4s %-7s %3s %4s\n"
, ssidmax, ssidmax, "SSID/MESH ID"
, "BSSID"
, "CHAN"
, "RATE"
, " S:N"
, "INT"
, "CAPS"
);
cp = buf;
do {
const struct ieee80211req_scan_result *sr;
const uint8_t *vp, *idp;
sr = (const struct ieee80211req_scan_result *) cp;
vp = cp + sr->isr_ie_off;
if (sr->isr_meshid_len) {
idp = vp + sr->isr_ssid_len;
idlen = sr->isr_meshid_len;
} else {
idp = vp;
idlen = sr->isr_ssid_len;
}
printf("%-*.*s %s %3d %3dM %3d:%-3d %3d %-4.4s"
, ssidmax
, copy_essid(ssid, ssidmax, idp, idlen)
, ssid
, ether_ntoa((const struct ether_addr *) sr->isr_bssid)
, ieee80211_mhz2ieee(sr->isr_freq, sr->isr_flags)
, getmaxrate(sr->isr_rates, sr->isr_nrates)
, (sr->isr_rssi/2)+sr->isr_noise, sr->isr_noise
, sr->isr_intval
, getcaps(sr->isr_capinfo)
);
printies(vp + sr->isr_ssid_len + sr->isr_meshid_len,
sr->isr_ie_len, 24);
printf("\n");
cp += sr->isr_len, len -= sr->isr_len;
} while (len >= sizeof(struct ieee80211req_scan_result));
}
static void
scan_and_wait(int s)
{
struct ieee80211_scan_req sr;
struct ieee80211req ireq;
int sroute;
sroute = socket(PF_ROUTE, SOCK_RAW, 0);
if (sroute < 0) {
perror("socket(PF_ROUTE,SOCK_RAW)");
return;
}
(void) memset(&ireq, 0, sizeof(ireq));
(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
ireq.i_type = IEEE80211_IOC_SCAN_REQ;
memset(&sr, 0, sizeof(sr));
sr.sr_flags = IEEE80211_IOC_SCAN_ACTIVE
| IEEE80211_IOC_SCAN_BGSCAN
| IEEE80211_IOC_SCAN_NOPICK
| IEEE80211_IOC_SCAN_ONCE;
sr.sr_duration = IEEE80211_IOC_SCAN_FOREVER;
sr.sr_nssid = 0;
ireq.i_data = &sr;
ireq.i_len = sizeof(sr);
/*
* NB: only root can trigger a scan so ignore errors. Also ignore
* possible errors from net80211, even if no new scan could be
* started there might still be a valid scan cache.
*/
if (ioctl(s, SIOCS80211, &ireq) == 0) {
char buf[2048];
struct if_announcemsghdr *ifan;
struct rt_msghdr *rtm;
do {
if (read(sroute, buf, sizeof(buf)) < 0) {
perror("read(PF_ROUTE)");
break;
}
rtm = (struct rt_msghdr *) buf;
if (rtm->rtm_version != RTM_VERSION)
break;
ifan = (struct if_announcemsghdr *) rtm;
} while (rtm->rtm_type != RTM_IEEE80211 ||
ifan->ifan_what != RTM_IEEE80211_SCAN);
}
close(sroute);
}
static
DECL_CMD_FUNC(set80211scan, val, d)
{
scan_and_wait(s);
list_scan(s);
}
static enum ieee80211_opmode get80211opmode(int s);
static int
gettxseq(const struct ieee80211req_sta_info *si)
{
int i, txseq;
if ((si->isi_state & IEEE80211_NODE_QOS) == 0)
return si->isi_txseqs[0];
/* XXX not right but usually what folks want */
txseq = 0;
for (i = 0; i < IEEE80211_TID_SIZE; i++)
if (si->isi_txseqs[i] > txseq)
txseq = si->isi_txseqs[i];
return txseq;
}
static int
getrxseq(const struct ieee80211req_sta_info *si)
{
int i, rxseq;
if ((si->isi_state & IEEE80211_NODE_QOS) == 0)
return si->isi_rxseqs[0];
/* XXX not right but usually what folks want */
rxseq = 0;
for (i = 0; i < IEEE80211_TID_SIZE; i++)
if (si->isi_rxseqs[i] > rxseq)
rxseq = si->isi_rxseqs[i];
return rxseq;
}
static void
list_stations(int s)
{
union {
struct ieee80211req_sta_req req;
uint8_t buf[24*1024];
} u;
enum ieee80211_opmode opmode = get80211opmode(s);
const uint8_t *cp;
int len;
/* broadcast address =>'s get all stations */
(void) memset(u.req.is_u.macaddr, 0xff, IEEE80211_ADDR_LEN);
if (opmode == IEEE80211_M_STA) {
/*
* Get information about the associated AP.
*/
(void) get80211(s, IEEE80211_IOC_BSSID,
u.req.is_u.macaddr, IEEE80211_ADDR_LEN);
}
if (get80211len(s, IEEE80211_IOC_STA_INFO, &u, sizeof(u), &len) < 0)
errx(1, "unable to get station information");
if (len < sizeof(struct ieee80211req_sta_info))
return;
getchaninfo(s);
if (opmode == IEEE80211_M_MBSS)
printf("%-17.17s %4s %5s %5s %7s %4s %4s %4s %6s %6s\n"
, "ADDR"
, "CHAN"
, "LOCAL"
, "PEER"
, "STATE"
, "RATE"
, "RSSI"
, "IDLE"
, "TXSEQ"
, "RXSEQ"
);
else
printf("%-17.17s %4s %4s %4s %4s %4s %6s %6s %4s %-7s\n"
, "ADDR"
, "AID"
, "CHAN"
, "RATE"
, "RSSI"
, "IDLE"
, "TXSEQ"
, "RXSEQ"
, "CAPS"
, "FLAG"
);
cp = (const uint8_t *) u.req.info;
do {
const struct ieee80211req_sta_info *si;
si = (const struct ieee80211req_sta_info *) cp;
if (si->isi_len < sizeof(*si))
break;
if (opmode == IEEE80211_M_MBSS)
printf("%s %4d %5x %5x %7.7s %3dM %4.1f %4d %6d %6d"
, ether_ntoa((const struct ether_addr*)
si->isi_macaddr)
, ieee80211_mhz2ieee(si->isi_freq,
si->isi_flags)
, si->isi_localid
, si->isi_peerid
, mesh_linkstate_string(si->isi_peerstate)
, si->isi_txmbps/2
, si->isi_rssi/2.
, si->isi_inact
, gettxseq(si)
, getrxseq(si)
);
else
printf("%s %4u %4d %3dM %4.1f %4d %6d %6d %-4.4s %-7.7s"
, ether_ntoa((const struct ether_addr*)
si->isi_macaddr)
, IEEE80211_AID(si->isi_associd)
, ieee80211_mhz2ieee(si->isi_freq,
si->isi_flags)
, si->isi_txmbps/2
, si->isi_rssi/2.
, si->isi_inact
, gettxseq(si)
, getrxseq(si)
, getcaps(si->isi_capinfo)
, getflags(si->isi_state)
);
printies(cp + si->isi_ie_off, si->isi_ie_len, 24);
printmimo(&si->isi_mimo);
printf("\n");
cp += si->isi_len, len -= si->isi_len;
} while (len >= sizeof(struct ieee80211req_sta_info));
}
static const char *
mesh_linkstate_string(uint8_t state)
{
#define N(a) (sizeof(a) / sizeof(a[0]))
static const char *state_names[] = {
[0] = "IDLE",
[1] = "OPEN-TX",
[2] = "OPEN-RX",
[3] = "CONF-RX",
[4] = "ESTAB",
[5] = "HOLDING",
};
if (state >= N(state_names)) {
static char buf[10];
snprintf(buf, sizeof(buf), "#%u", state);
return buf;
} else
return state_names[state];
#undef N
}
static const char *
get_chaninfo(const struct ieee80211_channel *c, int precise,
char buf[], size_t bsize)
{
buf[0] = '\0';
if (IEEE80211_IS_CHAN_FHSS(c))
strlcat(buf, " FHSS", bsize);
if (IEEE80211_IS_CHAN_A(c))
strlcat(buf, " 11a", bsize);
else if (IEEE80211_IS_CHAN_ANYG(c))
strlcat(buf, " 11g", bsize);
else if (IEEE80211_IS_CHAN_B(c))
strlcat(buf, " 11b", bsize);
if (IEEE80211_IS_CHAN_HALF(c))
strlcat(buf, "/10MHz", bsize);
if (IEEE80211_IS_CHAN_QUARTER(c))
strlcat(buf, "/5MHz", bsize);
if (IEEE80211_IS_CHAN_TURBO(c))
strlcat(buf, " Turbo", bsize);
if (precise) {
if (IEEE80211_IS_CHAN_HT20(c))
strlcat(buf, " ht/20", bsize);
else if (IEEE80211_IS_CHAN_HT40D(c))
strlcat(buf, " ht/40-", bsize);
else if (IEEE80211_IS_CHAN_HT40U(c))
strlcat(buf, " ht/40+", bsize);
} else {
if (IEEE80211_IS_CHAN_HT(c))
strlcat(buf, " ht", bsize);
}
return buf;
}
static void
print_chaninfo(const struct ieee80211_channel *c, int verb)
{
char buf[14];
if (verb)
printf("Channel %3u : %u%c%c%c%c%c MHz%-14.14s",
ieee80211_mhz2ieee(c->ic_freq, c->ic_flags), c->ic_freq,
IEEE80211_IS_CHAN_PASSIVE(c) ? '*' : ' ',
IEEE80211_IS_CHAN_DFS(c) ? 'D' : ' ',
IEEE80211_IS_CHAN_RADAR(c) ? 'R' : ' ',
IEEE80211_IS_CHAN_CWINT(c) ? 'I' : ' ',
IEEE80211_IS_CHAN_CACDONE(c) ? 'C' : ' ',
get_chaninfo(c, verb, buf, sizeof(buf)));
else
printf("Channel %3u : %u%c MHz%-14.14s",
ieee80211_mhz2ieee(c->ic_freq, c->ic_flags), c->ic_freq,
IEEE80211_IS_CHAN_PASSIVE(c) ? '*' : ' ',
get_chaninfo(c, verb, buf, sizeof(buf)));
}
static int
chanpref(const struct ieee80211_channel *c)
{
if (IEEE80211_IS_CHAN_HT40(c))
return 40;
if (IEEE80211_IS_CHAN_HT20(c))
return 30;
if (IEEE80211_IS_CHAN_HALF(c))
return 10;
if (IEEE80211_IS_CHAN_QUARTER(c))
return 5;
if (IEEE80211_IS_CHAN_TURBO(c))
return 25;
if (IEEE80211_IS_CHAN_A(c))
return 20;
if (IEEE80211_IS_CHAN_G(c))
return 20;
if (IEEE80211_IS_CHAN_B(c))
return 15;
if (IEEE80211_IS_CHAN_PUREG(c))
return 15;
return 0;
}
static void
print_channels(int s, const struct ieee80211req_chaninfo *chans,
int allchans, int verb)
{
struct ieee80211req_chaninfo *achans;
uint8_t reported[IEEE80211_CHAN_BYTES];
const struct ieee80211_channel *c;
int i, half;
achans = malloc(IEEE80211_CHANINFO_SPACE(chans));
if (achans == NULL)
errx(1, "no space for active channel list");
achans->ic_nchans = 0;
memset(reported, 0, sizeof(reported));
if (!allchans) {
struct ieee80211req_chanlist active;
if (get80211(s, IEEE80211_IOC_CHANLIST, &active, sizeof(active)) < 0)
errx(1, "unable to get active channel list");
for (i = 0; i < chans->ic_nchans; i++) {
c = &chans->ic_chans[i];
if (!isset(active.ic_channels, c->ic_ieee))
continue;
/*
* Suppress compatible duplicates unless
* verbose. The kernel gives us it's
* complete channel list which has separate
* entries for 11g/11b and 11a/turbo.
*/
if (isset(reported, c->ic_ieee) && !verb) {
/* XXX we assume duplicates are adjacent */
achans->ic_chans[achans->ic_nchans-1] = *c;
} else {
achans->ic_chans[achans->ic_nchans++] = *c;
setbit(reported, c->ic_ieee);
}
}
} else {
for (i = 0; i < chans->ic_nchans; i++) {
c = &chans->ic_chans[i];
/* suppress duplicates as above */
if (isset(reported, c->ic_ieee) && !verb) {
/* XXX we assume duplicates are adjacent */
struct ieee80211_channel *a =
&achans->ic_chans[achans->ic_nchans-1];
if (chanpref(c) > chanpref(a))
*a = *c;
} else {
achans->ic_chans[achans->ic_nchans++] = *c;
setbit(reported, c->ic_ieee);
}
}
}
half = achans->ic_nchans / 2;
if (achans->ic_nchans % 2)
half++;
for (i = 0; i < achans->ic_nchans / 2; i++) {
print_chaninfo(&achans->ic_chans[i], verb);
print_chaninfo(&achans->ic_chans[half+i], verb);
printf("\n");
}
if (achans->ic_nchans % 2) {
print_chaninfo(&achans->ic_chans[i], verb);
printf("\n");
}
free(achans);
}
static void
list_channels(int s, int allchans)
{
getchaninfo(s);
print_channels(s, chaninfo, allchans, verbose);
}
static void
print_txpow(const struct ieee80211_channel *c)
{
printf("Channel %3u : %u MHz %3.1f reg %2d ",
c->ic_ieee, c->ic_freq,
c->ic_maxpower/2., c->ic_maxregpower);
}
static void
print_txpow_verbose(const struct ieee80211_channel *c)
{
print_chaninfo(c, 1);
printf("min %4.1f dBm max %3.1f dBm reg %2d dBm",
c->ic_minpower/2., c->ic_maxpower/2., c->ic_maxregpower);
/* indicate where regulatory cap limits power use */
if (c->ic_maxpower > 2*c->ic_maxregpower)
printf(" <");
}
static void
list_txpow(int s)
{
struct ieee80211req_chaninfo *achans;
uint8_t reported[IEEE80211_CHAN_BYTES];
struct ieee80211_channel *c, *prev;
int i, half;
getchaninfo(s);
achans = malloc(IEEE80211_CHANINFO_SPACE(chaninfo));
if (achans == NULL)
errx(1, "no space for active channel list");
achans->ic_nchans = 0;
memset(reported, 0, sizeof(reported));
for (i = 0; i < chaninfo->ic_nchans; i++) {
c = &chaninfo->ic_chans[i];
/* suppress duplicates as above */
if (isset(reported, c->ic_ieee) && !verbose) {
/* XXX we assume duplicates are adjacent */
prev = &achans->ic_chans[achans->ic_nchans-1];
/* display highest power on channel */
if (c->ic_maxpower > prev->ic_maxpower)
*prev = *c;
} else {
achans->ic_chans[achans->ic_nchans++] = *c;
setbit(reported, c->ic_ieee);
}
}
if (!verbose) {
half = achans->ic_nchans / 2;
if (achans->ic_nchans % 2)
half++;
for (i = 0; i < achans->ic_nchans / 2; i++) {
print_txpow(&achans->ic_chans[i]);
print_txpow(&achans->ic_chans[half+i]);
printf("\n");
}
if (achans->ic_nchans % 2) {
print_txpow(&achans->ic_chans[i]);
printf("\n");
}
} else {
for (i = 0; i < achans->ic_nchans; i++) {
print_txpow_verbose(&achans->ic_chans[i]);
printf("\n");
}
}
free(achans);
}
static void
list_keys(int s)
{
}
#define IEEE80211_C_BITS \
"\20\1STA\002803ENCAP\7FF\10TURBOP\11IBSS\12PMGT" \
"\13HOSTAP\14AHDEMO\15SWRETRY\16TXPMGT\17SHSLOT\20SHPREAMBLE" \
"\21MONITOR\22DFS\23MBSS\30WPA1\31WPA2\32BURST\33WME\34WDS\36BGSCAN" \
"\37TXFRAG\40TDMA"
static void
list_capabilities(int s)
{
struct ieee80211_devcaps_req *dc;
if (verbose)
dc = malloc(IEEE80211_DEVCAPS_SIZE(MAXCHAN));
else
dc = malloc(IEEE80211_DEVCAPS_SIZE(1));
if (dc == NULL)
errx(1, "no space for device capabilities");
dc->dc_chaninfo.ic_nchans = verbose ? MAXCHAN : 1;
getdevcaps(s, dc);
printb("drivercaps", dc->dc_drivercaps, IEEE80211_C_BITS);
if (dc->dc_cryptocaps != 0 || verbose) {
putchar('\n');
printb("cryptocaps", dc->dc_cryptocaps, IEEE80211_CRYPTO_BITS);
}
if (dc->dc_htcaps != 0 || verbose) {
putchar('\n');
printb("htcaps", dc->dc_htcaps, IEEE80211_HTCAP_BITS);
}
putchar('\n');
if (verbose) {
chaninfo = &dc->dc_chaninfo; /* XXX */
print_channels(s, &dc->dc_chaninfo, 1/*allchans*/, verbose);
}
free(dc);
}
static int
get80211wme(int s, int param, int ac, int *val)
{
struct ieee80211req ireq;
(void) memset(&ireq, 0, sizeof(ireq));
(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
ireq.i_type = param;
ireq.i_len = ac;
if (ioctl(s, SIOCG80211, &ireq) < 0) {
warn("cannot get WME parameter %d, ac %d%s",
param, ac & IEEE80211_WMEPARAM_VAL,
ac & IEEE80211_WMEPARAM_BSS ? " (BSS)" : "");
return -1;
}
*val = ireq.i_val;
return 0;
}
static void
list_wme_aci(int s, const char *tag, int ac)
{
int val;
printf("\t%s", tag);
/* show WME BSS parameters */
if (get80211wme(s, IEEE80211_IOC_WME_CWMIN, ac, &val) != -1)
printf(" cwmin %2u", val);
if (get80211wme(s, IEEE80211_IOC_WME_CWMAX, ac, &val) != -1)
printf(" cwmax %2u", val);
if (get80211wme(s, IEEE80211_IOC_WME_AIFS, ac, &val) != -1)
printf(" aifs %2u", val);
if (get80211wme(s, IEEE80211_IOC_WME_TXOPLIMIT, ac, &val) != -1)
printf(" txopLimit %3u", val);
if (get80211wme(s, IEEE80211_IOC_WME_ACM, ac, &val) != -1) {
if (val)
printf(" acm");
else if (verbose)
printf(" -acm");
}
/* !BSS only */
if ((ac & IEEE80211_WMEPARAM_BSS) == 0) {
if (get80211wme(s, IEEE80211_IOC_WME_ACKPOLICY, ac, &val) != -1) {
if (!val)
printf(" -ack");
else if (verbose)
printf(" ack");
}
}
printf("\n");
}
static void
list_wme(int s)
{
static const char *acnames[] = { "AC_BE", "AC_BK", "AC_VI", "AC_VO" };
int ac;
if (verbose) {
/* display both BSS and local settings */
for (ac = WME_AC_BE; ac <= WME_AC_VO; ac++) {
again:
if (ac & IEEE80211_WMEPARAM_BSS)
list_wme_aci(s, " ", ac);
else
list_wme_aci(s, acnames[ac], ac);
if ((ac & IEEE80211_WMEPARAM_BSS) == 0) {
ac |= IEEE80211_WMEPARAM_BSS;
goto again;
} else
ac &= ~IEEE80211_WMEPARAM_BSS;
}
} else {
/* display only channel settings */
for (ac = WME_AC_BE; ac <= WME_AC_VO; ac++)
list_wme_aci(s, acnames[ac], ac);
}
}
static void
list_roam(int s)
{
const struct ieee80211_roamparam *rp;
int mode;
getroam(s);
for (mode = IEEE80211_MODE_11A; mode < IEEE80211_MODE_MAX; mode++) {
rp = &roamparams.params[mode];
if (rp->rssi == 0 && rp->rate == 0)
continue;
if (mode == IEEE80211_MODE_11NA || mode == IEEE80211_MODE_11NG) {
if (rp->rssi & 1)
LINE_CHECK("roam:%-7.7s rssi %2u.5dBm MCS %2u ",
modename[mode], rp->rssi/2,
rp->rate &~ IEEE80211_RATE_MCS);
else
LINE_CHECK("roam:%-7.7s rssi %4udBm MCS %2u ",
modename[mode], rp->rssi/2,
rp->rate &~ IEEE80211_RATE_MCS);
} else {
if (rp->rssi & 1)
LINE_CHECK("roam:%-7.7s rssi %2u.5dBm rate %2u Mb/s",
modename[mode], rp->rssi/2, rp->rate/2);
else
LINE_CHECK("roam:%-7.7s rssi %4udBm rate %2u Mb/s",
modename[mode], rp->rssi/2, rp->rate/2);
}
}
}
static void
list_txparams(int s)
{
const struct ieee80211_txparam *tp;
int mode;
gettxparams(s);
for (mode = IEEE80211_MODE_11A; mode < IEEE80211_MODE_MAX; mode++) {
tp = &txparams.params[mode];
if (tp->mgmtrate == 0 && tp->mcastrate == 0)
continue;
if (mode == IEEE80211_MODE_11NA || mode == IEEE80211_MODE_11NG) {
if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
LINE_CHECK("%-7.7s ucast NONE mgmt %2u MCS "
"mcast %2u MCS maxretry %u",
modename[mode],
tp->mgmtrate &~ IEEE80211_RATE_MCS,
tp->mcastrate &~ IEEE80211_RATE_MCS,
tp->maxretry);
else
LINE_CHECK("%-7.7s ucast %2u MCS mgmt %2u MCS "
"mcast %2u MCS maxretry %u",
modename[mode],
tp->ucastrate &~ IEEE80211_RATE_MCS,
tp->mgmtrate &~ IEEE80211_RATE_MCS,
tp->mcastrate &~ IEEE80211_RATE_MCS,
tp->maxretry);
} else {
if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
LINE_CHECK("%-7.7s ucast NONE mgmt %2u Mb/s "
"mcast %2u Mb/s maxretry %u",
modename[mode],
tp->mgmtrate/2,
tp->mcastrate/2, tp->maxretry);
else
LINE_CHECK("%-7.7s ucast %2u Mb/s mgmt %2u Mb/s "
"mcast %2u Mb/s maxretry %u",
modename[mode],
tp->ucastrate/2, tp->mgmtrate/2,
tp->mcastrate/2, tp->maxretry);
}
}
}
static void
printpolicy(int policy)
{
switch (policy) {
case IEEE80211_MACCMD_POLICY_OPEN:
printf("policy: open\n");
break;
case IEEE80211_MACCMD_POLICY_ALLOW:
printf("policy: allow\n");
break;
case IEEE80211_MACCMD_POLICY_DENY:
printf("policy: deny\n");
break;
case IEEE80211_MACCMD_POLICY_RADIUS:
printf("policy: radius\n");
break;
default:
printf("policy: unknown (%u)\n", policy);
break;
}
}
static void
list_mac(int s)
{
struct ieee80211req ireq;
struct ieee80211req_maclist *acllist;
int i, nacls, policy, len;
uint8_t *data;
char c;
(void) memset(&ireq, 0, sizeof(ireq));
(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name)); /* XXX ?? */
ireq.i_type = IEEE80211_IOC_MACCMD;
ireq.i_val = IEEE80211_MACCMD_POLICY;
if (ioctl(s, SIOCG80211, &ireq) < 0) {
if (errno == EINVAL) {
printf("No acl policy loaded\n");
return;
}
err(1, "unable to get mac policy");
}
policy = ireq.i_val;
if (policy == IEEE80211_MACCMD_POLICY_OPEN) {
c = '*';
} else if (policy == IEEE80211_MACCMD_POLICY_ALLOW) {
c = '+';
} else if (policy == IEEE80211_MACCMD_POLICY_DENY) {
c = '-';
} else if (policy == IEEE80211_MACCMD_POLICY_RADIUS) {
c = 'r'; /* NB: should never have entries */
} else {
printf("policy: unknown (%u)\n", policy);
c = '?';
}
if (verbose || c == '?')
printpolicy(policy);
ireq.i_val = IEEE80211_MACCMD_LIST;
ireq.i_len = 0;
if (ioctl(s, SIOCG80211, &ireq) < 0)
err(1, "unable to get mac acl list size");
if (ireq.i_len == 0) { /* NB: no acls */
if (!(verbose || c == '?'))
printpolicy(policy);
return;
}
len = ireq.i_len;
data = malloc(len);
if (data == NULL)
err(1, "out of memory for acl list");
ireq.i_data = data;
if (ioctl(s, SIOCG80211, &ireq) < 0)
err(1, "unable to get mac acl list");
nacls = len / sizeof(*acllist);
acllist = (struct ieee80211req_maclist *) data;
for (i = 0; i < nacls; i++)
printf("%c%s\n", c, ether_ntoa(
(const struct ether_addr *) acllist[i].ml_macaddr));
free(data);
}
static void
print_regdomain(const struct ieee80211_regdomain *reg, int verb)
{
if ((reg->regdomain != 0 &&
reg->regdomain != reg->country) || verb) {
const struct regdomain *rd =
lib80211_regdomain_findbysku(getregdata(), reg->regdomain);
if (rd == NULL)
LINE_CHECK("regdomain %d", reg->regdomain);
else
LINE_CHECK("regdomain %s", rd->name);
}
if (reg->country != 0 || verb) {
const struct country *cc =
lib80211_country_findbycc(getregdata(), reg->country);
if (cc == NULL)
LINE_CHECK("country %d", reg->country);
else
LINE_CHECK("country %s", cc->isoname);
}
if (reg->location == 'I')
LINE_CHECK("indoor");
else if (reg->location == 'O')
LINE_CHECK("outdoor");
else if (verb)
LINE_CHECK("anywhere");
if (reg->ecm)
LINE_CHECK("ecm");
else if (verb)
LINE_CHECK("-ecm");
}
static void
list_regdomain(int s, int channelsalso)
{
getregdomain(s);
if (channelsalso) {
getchaninfo(s);
spacer = ':';
print_regdomain(®domain, 1);
LINE_BREAK();
print_channels(s, chaninfo, 1/*allchans*/, 1/*verbose*/);
} else
print_regdomain(®domain, verbose);
}
static void
list_mesh(int s)
{
struct ieee80211req ireq;
struct ieee80211req_mesh_route routes[128];
struct ieee80211req_mesh_route *rt;
(void) memset(&ireq, 0, sizeof(ireq));
(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
ireq.i_type = IEEE80211_IOC_MESH_RTCMD;
ireq.i_val = IEEE80211_MESH_RTCMD_LIST;
ireq.i_data = &routes;
ireq.i_len = sizeof(routes);
if (ioctl(s, SIOCG80211, &ireq) < 0)
err(1, "unable to get the Mesh routing table");
printf("%-17.17s %-17.17s %4s %4s %4s %6s %s\n"
, "DEST"
, "NEXT HOP"
, "HOPS"
, "METRIC"
, "LIFETIME"
, "MSEQ"
, "FLAGS");
for (rt = &routes[0]; rt - &routes[0] < ireq.i_len / sizeof(*rt); rt++){
printf("%s ",
ether_ntoa((const struct ether_addr *)rt->imr_dest));
printf("%s %4u %4u %6u %6u %c%c\n",
ether_ntoa((const struct ether_addr *)rt->imr_nexthop),
rt->imr_nhops, rt->imr_metric, rt->imr_lifetime,
rt->imr_lastmseq,
(rt->imr_flags & IEEE80211_MESHRT_FLAGS_DISCOVER) ?
'D' :
(rt->imr_flags & IEEE80211_MESHRT_FLAGS_VALID) ?
'V' : '!',
(rt->imr_flags & IEEE80211_MESHRT_FLAGS_PROXY) ?
'P' :
(rt->imr_flags & IEEE80211_MESHRT_FLAGS_GATE) ?
'G' :' ');
}
}
static
DECL_CMD_FUNC(set80211list, arg, d)
{
#define iseq(a,b) (strncasecmp(a,b,sizeof(b)-1) == 0)
LINE_INIT('\t');
if (iseq(arg, "sta"))
list_stations(s);
else if (iseq(arg, "scan") || iseq(arg, "ap"))
list_scan(s);
else if (iseq(arg, "chan") || iseq(arg, "freq"))
list_channels(s, 1);
else if (iseq(arg, "active"))
list_channels(s, 0);
else if (iseq(arg, "keys"))
list_keys(s);
else if (iseq(arg, "caps"))
list_capabilities(s);
else if (iseq(arg, "wme") || iseq(arg, "wmm"))
list_wme(s);
else if (iseq(arg, "mac"))
list_mac(s);
else if (iseq(arg, "txpow"))
list_txpow(s);
else if (iseq(arg, "roam"))
list_roam(s);
else if (iseq(arg, "txparam") || iseq(arg, "txparm"))
list_txparams(s);
else if (iseq(arg, "regdomain"))
list_regdomain(s, 1);
else if (iseq(arg, "countries"))
list_countries();
else if (iseq(arg, "mesh"))
list_mesh(s);
else
errx(1, "Don't know how to list %s for %s", arg, name);
LINE_BREAK();
#undef iseq
}
static enum ieee80211_opmode
get80211opmode(int s)
{
struct ifmediareq ifmr;
(void) memset(&ifmr, 0, sizeof(ifmr));
(void) strncpy(ifmr.ifm_name, name, sizeof(ifmr.ifm_name));
if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) >= 0) {
if (ifmr.ifm_current & IFM_IEEE80211_ADHOC) {
if (ifmr.ifm_current & IFM_FLAG0)
return IEEE80211_M_AHDEMO;
else
return IEEE80211_M_IBSS;
}
if (ifmr.ifm_current & IFM_IEEE80211_HOSTAP)
return IEEE80211_M_HOSTAP;
if (ifmr.ifm_current & IFM_IEEE80211_MONITOR)
return IEEE80211_M_MONITOR;
if (ifmr.ifm_current & IFM_IEEE80211_MBSS)
return IEEE80211_M_MBSS;
}
return IEEE80211_M_STA;
}
#if 0
static void
printcipher(int s, struct ieee80211req *ireq, int keylenop)
{
switch (ireq->i_val) {
case IEEE80211_CIPHER_WEP:
ireq->i_type = keylenop;
if (ioctl(s, SIOCG80211, ireq) != -1)
printf("WEP-%s",
ireq->i_len <= 5 ? "40" :
ireq->i_len <= 13 ? "104" : "128");
else
printf("WEP");
break;
case IEEE80211_CIPHER_TKIP:
printf("TKIP");
break;
case IEEE80211_CIPHER_AES_OCB:
printf("AES-OCB");
break;
case IEEE80211_CIPHER_AES_CCM:
printf("AES-CCM");
break;
case IEEE80211_CIPHER_CKIP:
printf("CKIP");
break;
case IEEE80211_CIPHER_NONE:
printf("NONE");
break;
default:
printf("UNKNOWN (0x%x)", ireq->i_val);
break;
}
}
#endif
static void
printkey(const struct ieee80211req_key *ik)
{
static const uint8_t zerodata[IEEE80211_KEYBUF_SIZE];
int keylen = ik->ik_keylen;
int printcontents;
printcontents = printkeys &&
(memcmp(ik->ik_keydata, zerodata, keylen) != 0 || verbose);
if (printcontents)
LINE_BREAK();
switch (ik->ik_type) {
case IEEE80211_CIPHER_WEP:
/* compatibility */
LINE_CHECK("wepkey %u:%s", ik->ik_keyix+1,
keylen <= 5 ? "40-bit" :
keylen <= 13 ? "104-bit" : "128-bit");
break;
case IEEE80211_CIPHER_TKIP:
if (keylen > 128/8)
keylen -= 128/8; /* ignore MIC for now */
LINE_CHECK("TKIP %u:%u-bit", ik->ik_keyix+1, 8*keylen);
break;
case IEEE80211_CIPHER_AES_OCB:
LINE_CHECK("AES-OCB %u:%u-bit", ik->ik_keyix+1, 8*keylen);
break;
case IEEE80211_CIPHER_AES_CCM:
LINE_CHECK("AES-CCM %u:%u-bit", ik->ik_keyix+1, 8*keylen);
break;
case IEEE80211_CIPHER_CKIP:
LINE_CHECK("CKIP %u:%u-bit", ik->ik_keyix+1, 8*keylen);
break;
case IEEE80211_CIPHER_NONE:
LINE_CHECK("NULL %u:%u-bit", ik->ik_keyix+1, 8*keylen);
break;
default:
LINE_CHECK("UNKNOWN (0x%x) %u:%u-bit",
ik->ik_type, ik->ik_keyix+1, 8*keylen);
break;
}
if (printcontents) {
int i;
printf(" <");
for (i = 0; i < keylen; i++)
printf("%02x", ik->ik_keydata[i]);
printf(">");
if (ik->ik_type != IEEE80211_CIPHER_WEP &&
(ik->ik_keyrsc != 0 || verbose))
printf(" rsc %ju", (uintmax_t)ik->ik_keyrsc);
if (ik->ik_type != IEEE80211_CIPHER_WEP &&
(ik->ik_keytsc != 0 || verbose))
printf(" tsc %ju", (uintmax_t)ik->ik_keytsc);
if (ik->ik_flags != 0 && verbose) {
const char *sep = " ";
if (ik->ik_flags & IEEE80211_KEY_XMIT)
printf("%stx", sep), sep = "+";
if (ik->ik_flags & IEEE80211_KEY_RECV)
printf("%srx", sep), sep = "+";
if (ik->ik_flags & IEEE80211_KEY_DEFAULT)
printf("%sdef", sep), sep = "+";
}
LINE_BREAK();
}
}
static void
printrate(const char *tag, int v, int defrate, int defmcs)
{
if ((v & IEEE80211_RATE_MCS) == 0) {
if (v != defrate) {
if (v & 1)
LINE_CHECK("%s %d.5", tag, v/2);
else
LINE_CHECK("%s %d", tag, v/2);
}
} else {
if (v != defmcs)
LINE_CHECK("%s %d", tag, v &~ 0x80);
}
}
static int
getid(int s, int ix, void *data, size_t len, int *plen, int mesh)
{
struct ieee80211req ireq;
(void) memset(&ireq, 0, sizeof(ireq));
(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
ireq.i_type = (!mesh) ? IEEE80211_IOC_SSID : IEEE80211_IOC_MESH_ID;
ireq.i_val = ix;
ireq.i_data = data;
ireq.i_len = len;
if (ioctl(s, SIOCG80211, &ireq) < 0)
return -1;
*plen = ireq.i_len;
return 0;
}
static void
ieee80211_status(int s)
{
static const uint8_t zerobssid[IEEE80211_ADDR_LEN];
enum ieee80211_opmode opmode = get80211opmode(s);
int i, num, wpa, wme, bgscan, bgscaninterval, val, len, wepmode;
uint8_t data[32];
const struct ieee80211_channel *c;
const struct ieee80211_roamparam *rp;
const struct ieee80211_txparam *tp;
if (getid(s, -1, data, sizeof(data), &len, 0) < 0) {
/* If we can't get the SSID, this isn't an 802.11 device. */
return;
}
/*
* Invalidate cached state so printing status for multiple
* if's doesn't reuse the first interfaces' cached state.
*/
gotcurchan = 0;
gotroam = 0;
gottxparams = 0;
gothtconf = 0;
gotregdomain = 0;
printf("\t");
if (opmode == IEEE80211_M_MBSS) {
printf("meshid ");
getid(s, 0, data, sizeof(data), &len, 1);
print_string(data, len);
} else {
if (get80211val(s, IEEE80211_IOC_NUMSSIDS, &num) < 0)
num = 0;
printf("ssid ");
if (num > 1) {
for (i = 0; i < num; i++) {
if (getid(s, i, data, sizeof(data), &len, 0) >= 0 && len > 0) {
printf(" %d:", i + 1);
print_string(data, len);
}
}
} else
print_string(data, len);
}
c = getcurchan(s);
if (c->ic_freq != IEEE80211_CHAN_ANY) {
char buf[14];
printf(" channel %d (%u MHz%s)", c->ic_ieee, c->ic_freq,
get_chaninfo(c, 1, buf, sizeof(buf)));
} else if (verbose)
printf(" channel UNDEF");
if (get80211(s, IEEE80211_IOC_BSSID, data, IEEE80211_ADDR_LEN) >= 0 &&
(memcmp(data, zerobssid, sizeof(zerobssid)) != 0 || verbose))
printf(" bssid %s", ether_ntoa((struct ether_addr *)data));
if (get80211len(s, IEEE80211_IOC_STATIONNAME, data, sizeof(data), &len) != -1) {
printf("\n\tstationname ");
print_string(data, len);
}
spacer = ' '; /* force first break */
LINE_BREAK();
list_regdomain(s, 0);
wpa = 0;
if (get80211val(s, IEEE80211_IOC_AUTHMODE, &val) != -1) {
switch (val) {
case IEEE80211_AUTH_NONE:
LINE_CHECK("authmode NONE");
break;
case IEEE80211_AUTH_OPEN:
LINE_CHECK("authmode OPEN");
break;
case IEEE80211_AUTH_SHARED:
LINE_CHECK("authmode SHARED");
break;
case IEEE80211_AUTH_8021X:
LINE_CHECK("authmode 802.1x");
break;
case IEEE80211_AUTH_WPA:
if (get80211val(s, IEEE80211_IOC_WPA, &wpa) < 0)
wpa = 1; /* default to WPA1 */
switch (wpa) {
case 2:
LINE_CHECK("authmode WPA2/802.11i");
break;
case 3:
LINE_CHECK("authmode WPA1+WPA2/802.11i");
break;
default:
LINE_CHECK("authmode WPA");
break;
}
break;
case IEEE80211_AUTH_AUTO:
LINE_CHECK("authmode AUTO");
break;
default:
LINE_CHECK("authmode UNKNOWN (0x%x)", val);
break;
}
}
if (wpa || verbose) {
if (get80211val(s, IEEE80211_IOC_WPS, &val) != -1) {
if (val)
LINE_CHECK("wps");
else if (verbose)
LINE_CHECK("-wps");
}
if (get80211val(s, IEEE80211_IOC_TSN, &val) != -1) {
if (val)
LINE_CHECK("tsn");
else if (verbose)
LINE_CHECK("-tsn");
}
if (ioctl(s, IEEE80211_IOC_COUNTERMEASURES, &val) != -1) {
if (val)
LINE_CHECK("countermeasures");
else if (verbose)
LINE_CHECK("-countermeasures");
}
#if 0
/* XXX not interesting with WPA done in user space */
ireq.i_type = IEEE80211_IOC_KEYMGTALGS;
if (ioctl(s, SIOCG80211, &ireq) != -1) {
}
ireq.i_type = IEEE80211_IOC_MCASTCIPHER;
if (ioctl(s, SIOCG80211, &ireq) != -1) {
LINE_CHECK("mcastcipher ");
printcipher(s, &ireq, IEEE80211_IOC_MCASTKEYLEN);
spacer = ' ';
}
ireq.i_type = IEEE80211_IOC_UCASTCIPHER;
if (ioctl(s, SIOCG80211, &ireq) != -1) {
LINE_CHECK("ucastcipher ");
printcipher(s, &ireq, IEEE80211_IOC_UCASTKEYLEN);
}
if (wpa & 2) {
ireq.i_type = IEEE80211_IOC_RSNCAPS;
if (ioctl(s, SIOCG80211, &ireq) != -1) {
LINE_CHECK("RSN caps 0x%x", ireq.i_val);
spacer = ' ';
}
}
ireq.i_type = IEEE80211_IOC_UCASTCIPHERS;
if (ioctl(s, SIOCG80211, &ireq) != -1) {
}
#endif
}
if (get80211val(s, IEEE80211_IOC_WEP, &wepmode) != -1 &&
wepmode != IEEE80211_WEP_NOSUP) {
switch (wepmode) {
case IEEE80211_WEP_OFF:
LINE_CHECK("privacy OFF");
break;
case IEEE80211_WEP_ON:
LINE_CHECK("privacy ON");
break;
case IEEE80211_WEP_MIXED:
LINE_CHECK("privacy MIXED");
break;
default:
LINE_CHECK("privacy UNKNOWN (0x%x)", wepmode);
break;
}
/*
* If we get here then we've got WEP support so we need
* to print WEP status.
*/
if (get80211val(s, IEEE80211_IOC_WEPTXKEY, &val) < 0) {
warn("WEP support, but no tx key!");
goto end;
}
if (val != -1)
LINE_CHECK("deftxkey %d", val+1);
else if (wepmode != IEEE80211_WEP_OFF || verbose)
LINE_CHECK("deftxkey UNDEF");
if (get80211val(s, IEEE80211_IOC_NUMWEPKEYS, &num) < 0) {
warn("WEP support, but no NUMWEPKEYS support!");
goto end;
}
for (i = 0; i < num; i++) {
struct ieee80211req_key ik;
memset(&ik, 0, sizeof(ik));
ik.ik_keyix = i;
if (get80211(s, IEEE80211_IOC_WPAKEY, &ik, sizeof(ik)) < 0) {
warn("WEP support, but can get keys!");
goto end;
}
if (ik.ik_keylen != 0) {
if (verbose)
LINE_BREAK();
printkey(&ik);
}
}
end:
;
}
if (get80211val(s, IEEE80211_IOC_POWERSAVE, &val) != -1 &&
val != IEEE80211_POWERSAVE_NOSUP ) {
if (val != IEEE80211_POWERSAVE_OFF || verbose) {
switch (val) {
case IEEE80211_POWERSAVE_OFF:
LINE_CHECK("powersavemode OFF");
break;
case IEEE80211_POWERSAVE_CAM:
LINE_CHECK("powersavemode CAM");
break;
case IEEE80211_POWERSAVE_PSP:
LINE_CHECK("powersavemode PSP");
break;
case IEEE80211_POWERSAVE_PSP_CAM:
LINE_CHECK("powersavemode PSP-CAM");
break;
}
if (get80211val(s, IEEE80211_IOC_POWERSAVESLEEP, &val) != -1)
LINE_CHECK("powersavesleep %d", val);
}
}
if (get80211val(s, IEEE80211_IOC_TXPOWER, &val) != -1) {
if (val & 1)
LINE_CHECK("txpower %d.5", val/2);
else
LINE_CHECK("txpower %d", val/2);
}
if (verbose) {
if (get80211val(s, IEEE80211_IOC_TXPOWMAX, &val) != -1)
LINE_CHECK("txpowmax %.1f", val/2.);
}
if (get80211val(s, IEEE80211_IOC_DOTD, &val) != -1) {
if (val)
LINE_CHECK("dotd");
else if (verbose)
LINE_CHECK("-dotd");
}
if (get80211val(s, IEEE80211_IOC_RTSTHRESHOLD, &val) != -1) {
if (val != IEEE80211_RTS_MAX || verbose)
LINE_CHECK("rtsthreshold %d", val);
}
if (get80211val(s, IEEE80211_IOC_FRAGTHRESHOLD, &val) != -1) {
if (val != IEEE80211_FRAG_MAX || verbose)
LINE_CHECK("fragthreshold %d", val);
}
if (opmode == IEEE80211_M_STA || verbose) {
if (get80211val(s, IEEE80211_IOC_BMISSTHRESHOLD, &val) != -1) {
if (val != IEEE80211_HWBMISS_MAX || verbose)
LINE_CHECK("bmiss %d", val);
}
}
if (!verbose) {
gettxparams(s);
tp = &txparams.params[chan2mode(c)];
printrate("ucastrate", tp->ucastrate,
IEEE80211_FIXED_RATE_NONE, IEEE80211_FIXED_RATE_NONE);
printrate("mcastrate", tp->mcastrate, 2*1,
IEEE80211_RATE_MCS|0);
printrate("mgmtrate", tp->mgmtrate, 2*1,
IEEE80211_RATE_MCS|0);
if (tp->maxretry != 6) /* XXX */
LINE_CHECK("maxretry %d", tp->maxretry);
} else {
LINE_BREAK();
list_txparams(s);
}
bgscaninterval = -1;
(void) get80211val(s, IEEE80211_IOC_BGSCAN_INTERVAL, &bgscaninterval);
if (get80211val(s, IEEE80211_IOC_SCANVALID, &val) != -1) {
if (val != bgscaninterval || verbose)
LINE_CHECK("scanvalid %u", val);
}
bgscan = 0;
if (get80211val(s, IEEE80211_IOC_BGSCAN, &bgscan) != -1) {
if (bgscan)
LINE_CHECK("bgscan");
else if (verbose)
LINE_CHECK("-bgscan");
}
if (bgscan || verbose) {
if (bgscaninterval != -1)
LINE_CHECK("bgscanintvl %u", bgscaninterval);
if (get80211val(s, IEEE80211_IOC_BGSCAN_IDLE, &val) != -1)
LINE_CHECK("bgscanidle %u", val);
if (!verbose) {
getroam(s);
rp = &roamparams.params[chan2mode(c)];
if (rp->rssi & 1)
LINE_CHECK("roam:rssi %u.5", rp->rssi/2);
else
LINE_CHECK("roam:rssi %u", rp->rssi/2);
LINE_CHECK("roam:rate %u", rp->rate/2);
} else {
LINE_BREAK();
list_roam(s);
LINE_BREAK();
}
}
if (IEEE80211_IS_CHAN_ANYG(c) || verbose) {
if (get80211val(s, IEEE80211_IOC_PUREG, &val) != -1) {
if (val)
LINE_CHECK("pureg");
else if (verbose)
LINE_CHECK("-pureg");
}
if (get80211val(s, IEEE80211_IOC_PROTMODE, &val) != -1) {
switch (val) {
case IEEE80211_PROTMODE_OFF:
LINE_CHECK("protmode OFF");
break;
case IEEE80211_PROTMODE_CTS:
LINE_CHECK("protmode CTS");
break;
case IEEE80211_PROTMODE_RTSCTS:
LINE_CHECK("protmode RTSCTS");
break;
default:
LINE_CHECK("protmode UNKNOWN (0x%x)", val);
break;
}
}
}
if (IEEE80211_IS_CHAN_HT(c) || verbose) {
gethtconf(s);
switch (htconf & 3) {
case 0:
case 2:
LINE_CHECK("-ht");
break;
case 1:
LINE_CHECK("ht20");
break;
case 3:
if (verbose)
LINE_CHECK("ht");
break;
}
if (get80211val(s, IEEE80211_IOC_HTCOMPAT, &val) != -1) {
if (!val)
LINE_CHECK("-htcompat");
else if (verbose)
LINE_CHECK("htcompat");
}
if (get80211val(s, IEEE80211_IOC_AMPDU, &val) != -1) {
switch (val) {
case 0:
LINE_CHECK("-ampdu");
break;
case 1:
LINE_CHECK("ampdutx -ampdurx");
break;
case 2:
LINE_CHECK("-ampdutx ampdurx");
break;
case 3:
if (verbose)
LINE_CHECK("ampdu");
break;
}
}
if (get80211val(s, IEEE80211_IOC_AMPDU_LIMIT, &val) != -1) {
switch (val) {
case IEEE80211_HTCAP_MAXRXAMPDU_8K:
LINE_CHECK("ampdulimit 8k");
break;
case IEEE80211_HTCAP_MAXRXAMPDU_16K:
LINE_CHECK("ampdulimit 16k");
break;
case IEEE80211_HTCAP_MAXRXAMPDU_32K:
LINE_CHECK("ampdulimit 32k");
break;
case IEEE80211_HTCAP_MAXRXAMPDU_64K:
LINE_CHECK("ampdulimit 64k");
break;
}
}
if (get80211val(s, IEEE80211_IOC_AMPDU_DENSITY, &val) != -1) {
switch (val) {
case IEEE80211_HTCAP_MPDUDENSITY_NA:
if (verbose)
LINE_CHECK("ampdudensity NA");
break;
case IEEE80211_HTCAP_MPDUDENSITY_025:
LINE_CHECK("ampdudensity .25");
break;
case IEEE80211_HTCAP_MPDUDENSITY_05:
LINE_CHECK("ampdudensity .5");
break;
case IEEE80211_HTCAP_MPDUDENSITY_1:
LINE_CHECK("ampdudensity 1");
break;
case IEEE80211_HTCAP_MPDUDENSITY_2:
LINE_CHECK("ampdudensity 2");
break;
case IEEE80211_HTCAP_MPDUDENSITY_4:
LINE_CHECK("ampdudensity 4");
break;
case IEEE80211_HTCAP_MPDUDENSITY_8:
LINE_CHECK("ampdudensity 8");
break;
case IEEE80211_HTCAP_MPDUDENSITY_16:
LINE_CHECK("ampdudensity 16");
break;
}
}
if (get80211val(s, IEEE80211_IOC_AMSDU, &val) != -1) {
switch (val) {
case 0:
LINE_CHECK("-amsdu");
break;
case 1:
LINE_CHECK("amsdutx -amsdurx");
break;
case 2:
LINE_CHECK("-amsdutx amsdurx");
break;
case 3:
if (verbose)
LINE_CHECK("amsdu");
break;
}
}
/* XXX amsdu limit */
if (get80211val(s, IEEE80211_IOC_SHORTGI, &val) != -1) {
if (val)
LINE_CHECK("shortgi");
else if (verbose)
LINE_CHECK("-shortgi");
}
if (get80211val(s, IEEE80211_IOC_HTPROTMODE, &val) != -1) {
if (val == IEEE80211_PROTMODE_OFF)
LINE_CHECK("htprotmode OFF");
else if (val != IEEE80211_PROTMODE_RTSCTS)
LINE_CHECK("htprotmode UNKNOWN (0x%x)", val);
else if (verbose)
LINE_CHECK("htprotmode RTSCTS");
}
if (get80211val(s, IEEE80211_IOC_PUREN, &val) != -1) {
if (val)
LINE_CHECK("puren");
else if (verbose)
LINE_CHECK("-puren");
}
if (get80211val(s, IEEE80211_IOC_SMPS, &val) != -1) {
if (val == IEEE80211_HTCAP_SMPS_DYNAMIC)
LINE_CHECK("smpsdyn");
else if (val == IEEE80211_HTCAP_SMPS_ENA)
LINE_CHECK("smps");
else if (verbose)
LINE_CHECK("-smps");
}
if (get80211val(s, IEEE80211_IOC_RIFS, &val) != -1) {
if (val)
LINE_CHECK("rifs");
else if (verbose)
LINE_CHECK("-rifs");
}
}
if (get80211val(s, IEEE80211_IOC_WME, &wme) != -1) {
if (wme)
LINE_CHECK("wme");
else if (verbose)
LINE_CHECK("-wme");
} else
wme = 0;
if (get80211val(s, IEEE80211_IOC_BURST, &val) != -1) {
if (val)
LINE_CHECK("burst");
else if (verbose)
LINE_CHECK("-burst");
}
if (get80211val(s, IEEE80211_IOC_FF, &val) != -1) {
if (val)
LINE_CHECK("ff");
else if (verbose)
LINE_CHECK("-ff");
}
if (get80211val(s, IEEE80211_IOC_TURBOP, &val) != -1) {
if (val)
LINE_CHECK("dturbo");
else if (verbose)
LINE_CHECK("-dturbo");
}
if (get80211val(s, IEEE80211_IOC_DWDS, &val) != -1) {
if (val)
LINE_CHECK("dwds");
else if (verbose)
LINE_CHECK("-dwds");
}
if (opmode == IEEE80211_M_HOSTAP) {
if (get80211val(s, IEEE80211_IOC_HIDESSID, &val) != -1) {
if (val)
LINE_CHECK("hidessid");
else if (verbose)
LINE_CHECK("-hidessid");
}
if (get80211val(s, IEEE80211_IOC_APBRIDGE, &val) != -1) {
if (!val)
LINE_CHECK("-apbridge");
else if (verbose)
LINE_CHECK("apbridge");
}
if (get80211val(s, IEEE80211_IOC_DTIM_PERIOD, &val) != -1)
LINE_CHECK("dtimperiod %u", val);
if (get80211val(s, IEEE80211_IOC_DOTH, &val) != -1) {
if (!val)
LINE_CHECK("-doth");
else if (verbose)
LINE_CHECK("doth");
}
if (get80211val(s, IEEE80211_IOC_DFS, &val) != -1) {
if (!val)
LINE_CHECK("-dfs");
else if (verbose)
LINE_CHECK("dfs");
}
if (get80211val(s, IEEE80211_IOC_INACTIVITY, &val) != -1) {
if (!val)
LINE_CHECK("-inact");
else if (verbose)
LINE_CHECK("inact");
}
} else {
if (get80211val(s, IEEE80211_IOC_ROAMING, &val) != -1) {
if (val != IEEE80211_ROAMING_AUTO || verbose) {
switch (val) {
case IEEE80211_ROAMING_DEVICE:
LINE_CHECK("roaming DEVICE");
break;
case IEEE80211_ROAMING_AUTO:
LINE_CHECK("roaming AUTO");
break;
case IEEE80211_ROAMING_MANUAL:
LINE_CHECK("roaming MANUAL");
break;
default:
LINE_CHECK("roaming UNKNOWN (0x%x)",
val);
break;
}
}
}
}
if (opmode == IEEE80211_M_AHDEMO) {
if (get80211val(s, IEEE80211_IOC_TDMA_SLOT, &val) != -1)
LINE_CHECK("tdmaslot %u", val);
if (get80211val(s, IEEE80211_IOC_TDMA_SLOTCNT, &val) != -1)
LINE_CHECK("tdmaslotcnt %u", val);
if (get80211val(s, IEEE80211_IOC_TDMA_SLOTLEN, &val) != -1)
LINE_CHECK("tdmaslotlen %u", val);
if (get80211val(s, IEEE80211_IOC_TDMA_BINTERVAL, &val) != -1)
LINE_CHECK("tdmabintval %u", val);
} else if (get80211val(s, IEEE80211_IOC_BEACON_INTERVAL, &val) != -1) {
/* XXX default define not visible */
if (val != 100 || verbose)
LINE_CHECK("bintval %u", val);
}
if (wme && verbose) {
LINE_BREAK();
list_wme(s);
}
if (opmode == IEEE80211_M_MBSS) {
if (get80211val(s, IEEE80211_IOC_MESH_TTL, &val) != -1) {
LINE_CHECK("meshttl %u", val);
}
if (get80211val(s, IEEE80211_IOC_MESH_AP, &val) != -1) {
if (val)
LINE_CHECK("meshpeering");
else
LINE_CHECK("-meshpeering");
}
if (get80211val(s, IEEE80211_IOC_MESH_FWRD, &val) != -1) {
if (val)
LINE_CHECK("meshforward");
else
LINE_CHECK("-meshforward");
}
if (get80211val(s, IEEE80211_IOC_MESH_GATE, &val) != -1) {
if (val)
LINE_CHECK("meshgate");
else
LINE_CHECK("-meshgate");
}
if (get80211len(s, IEEE80211_IOC_MESH_PR_METRIC, data, 12,
&len) != -1) {
data[len] = '\0';
LINE_CHECK("meshmetric %s", data);
}
if (get80211len(s, IEEE80211_IOC_MESH_PR_PATH, data, 12,
&len) != -1) {
data[len] = '\0';
LINE_CHECK("meshpath %s", data);
}
if (get80211val(s, IEEE80211_IOC_HWMP_ROOTMODE, &val) != -1) {
switch (val) {
case IEEE80211_HWMP_ROOTMODE_DISABLED:
LINE_CHECK("hwmprootmode DISABLED");
break;
case IEEE80211_HWMP_ROOTMODE_NORMAL:
LINE_CHECK("hwmprootmode NORMAL");
break;
case IEEE80211_HWMP_ROOTMODE_PROACTIVE:
LINE_CHECK("hwmprootmode PROACTIVE");
break;
case IEEE80211_HWMP_ROOTMODE_RANN:
LINE_CHECK("hwmprootmode RANN");
break;
default:
LINE_CHECK("hwmprootmode UNKNOWN(%d)", val);
break;
}
}
if (get80211val(s, IEEE80211_IOC_HWMP_MAXHOPS, &val) != -1) {
LINE_CHECK("hwmpmaxhops %u", val);
}
}
LINE_BREAK();
}
static int
get80211(int s, int type, void *data, int len)
{
struct ieee80211req ireq;
(void) memset(&ireq, 0, sizeof(ireq));
(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
ireq.i_type = type;
ireq.i_data = data;
ireq.i_len = len;
return ioctl(s, SIOCG80211, &ireq);
}
static int
get80211len(int s, int type, void *data, int len, int *plen)
{
struct ieee80211req ireq;
(void) memset(&ireq, 0, sizeof(ireq));
(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
ireq.i_type = type;
ireq.i_len = len;
assert(ireq.i_len == len); /* NB: check for 16-bit truncation */
ireq.i_data = data;
if (ioctl(s, SIOCG80211, &ireq) < 0)
return -1;
*plen = ireq.i_len;
return 0;
}
static int
get80211val(int s, int type, int *val)
{
struct ieee80211req ireq;
(void) memset(&ireq, 0, sizeof(ireq));
(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
ireq.i_type = type;
if (ioctl(s, SIOCG80211, &ireq) < 0)
return -1;
*val = ireq.i_val;
return 0;
}
static void
set80211(int s, int type, int val, int len, void *data)
{
struct ieee80211req ireq;
(void) memset(&ireq, 0, sizeof(ireq));
(void) strncpy(ireq.i_name, name, sizeof(ireq.i_name));
ireq.i_type = type;
ireq.i_val = val;
ireq.i_len = len;
assert(ireq.i_len == len); /* NB: check for 16-bit truncation */
ireq.i_data = data;
if (ioctl(s, SIOCS80211, &ireq) < 0)
err(1, "SIOCS80211");
}
static const char *
get_string(const char *val, const char *sep, u_int8_t *buf, int *lenp)
{
int len;
int hexstr;
u_int8_t *p;
len = *lenp;
p = buf;
hexstr = (val[0] == '0' && tolower((u_char)val[1]) == 'x');
if (hexstr)
val += 2;
for (;;) {
if (*val == '\0')
break;
if (sep != NULL && strchr(sep, *val) != NULL) {
val++;
break;
}
if (hexstr) {
if (!isxdigit((u_char)val[0])) {
warnx("bad hexadecimal digits");
return NULL;
}
if (!isxdigit((u_char)val[1])) {
warnx("odd count hexadecimal digits");
return NULL;
}
}
if (p >= buf + len) {
if (hexstr)
warnx("hexadecimal digits too long");
else
warnx("string too long");
return NULL;
}
if (hexstr) {
#define tohex(x) (isdigit(x) ? (x) - '0' : tolower(x) - 'a' + 10)
*p++ = (tohex((u_char)val[0]) << 4) |
tohex((u_char)val[1]);
#undef tohex
val += 2;
} else
*p++ = *val++;
}
len = p - buf;
/* The string "-" is treated as the empty string. */
if (!hexstr && len == 1 && buf[0] == '-') {
len = 0;
memset(buf, 0, *lenp);
} else if (len < *lenp)
memset(p, 0, *lenp - len);
*lenp = len;
return val;
}
static void
print_string(const u_int8_t *buf, int len)
{
int i;
int hasspc;
i = 0;
hasspc = 0;
for (; i < len; i++) {
if (!isprint(buf[i]) && buf[i] != '\0')
break;
if (isspace(buf[i]))
hasspc++;
}
if (i == len) {
if (hasspc || len == 0 || buf[0] == '\0')
printf("\"%.*s\"", len, buf);
else
printf("%.*s", len, buf);
} else {
printf("0x");
for (i = 0; i < len; i++)
printf("%02x", buf[i]);
}
}
/*
* Virtual AP cloning support.
*/
static struct ieee80211_clone_params params = {
.icp_opmode = IEEE80211_M_STA, /* default to station mode */
};
static void
wlan_create(int s, struct ifreq *ifr)
{
static const uint8_t zerobssid[IEEE80211_ADDR_LEN];
if (params.icp_parent[0] == '\0')
errx(1, "must specify a parent device (wlandev) when creating "
"a wlan device");
if (params.icp_opmode == IEEE80211_M_WDS &&
memcmp(params.icp_bssid, zerobssid, sizeof(zerobssid)) == 0)
errx(1, "no bssid specified for WDS (use wlanbssid)");
ifr->ifr_data = (caddr_t) ¶ms;
if (ioctl(s, SIOCIFCREATE2, ifr) < 0)
err(1, "SIOCIFCREATE2");
}
static
DECL_CMD_FUNC(set80211clone_wlandev, arg, d)
{
strlcpy(params.icp_parent, arg, IFNAMSIZ);
}
static
DECL_CMD_FUNC(set80211clone_wlanbssid, arg, d)
{
const struct ether_addr *ea;
ea = ether_aton(arg);
if (ea == NULL)
errx(1, "%s: cannot parse bssid", arg);
memcpy(params.icp_bssid, ea->octet, IEEE80211_ADDR_LEN);
}
static
DECL_CMD_FUNC(set80211clone_wlanaddr, arg, d)
{
const struct ether_addr *ea;
ea = ether_aton(arg);
if (ea == NULL)
errx(1, "%s: cannot parse address", arg);
memcpy(params.icp_macaddr, ea->octet, IEEE80211_ADDR_LEN);
params.icp_flags |= IEEE80211_CLONE_MACADDR;
}
static
DECL_CMD_FUNC(set80211clone_wlanmode, arg, d)
{
#define iseq(a,b) (strncasecmp(a,b,sizeof(b)-1) == 0)
if (iseq(arg, "sta"))
params.icp_opmode = IEEE80211_M_STA;
else if (iseq(arg, "ahdemo") || iseq(arg, "adhoc-demo"))
params.icp_opmode = IEEE80211_M_AHDEMO;
else if (iseq(arg, "ibss") || iseq(arg, "adhoc"))
params.icp_opmode = IEEE80211_M_IBSS;
else if (iseq(arg, "ap") || iseq(arg, "host"))
params.icp_opmode = IEEE80211_M_HOSTAP;
else if (iseq(arg, "wds"))
params.icp_opmode = IEEE80211_M_WDS;
else if (iseq(arg, "monitor"))
params.icp_opmode = IEEE80211_M_MONITOR;
else if (iseq(arg, "tdma")) {
params.icp_opmode = IEEE80211_M_AHDEMO;
params.icp_flags |= IEEE80211_CLONE_TDMA;
} else if (iseq(arg, "mesh") || iseq(arg, "mp")) /* mesh point */
params.icp_opmode = IEEE80211_M_MBSS;
else
errx(1, "Don't know to create %s for %s", arg, name);
#undef iseq
}
static void
set80211clone_beacons(const char *val, int d, int s, const struct afswtch *rafp)
{
/* NB: inverted sense */
if (d)
params.icp_flags &= ~IEEE80211_CLONE_NOBEACONS;
else
params.icp_flags |= IEEE80211_CLONE_NOBEACONS;
}
static void
set80211clone_bssid(const char *val, int d, int s, const struct afswtch *rafp)
{
if (d)
params.icp_flags |= IEEE80211_CLONE_BSSID;
else
params.icp_flags &= ~IEEE80211_CLONE_BSSID;
}
static void
set80211clone_wdslegacy(const char *val, int d, int s, const struct afswtch *rafp)
{
if (d)
params.icp_flags |= IEEE80211_CLONE_WDSLEGACY;
else
params.icp_flags &= ~IEEE80211_CLONE_WDSLEGACY;
}
static struct cmd ieee80211_cmds[] = {
DEF_CMD_ARG("ssid", set80211ssid),
DEF_CMD_ARG("nwid", set80211ssid),
DEF_CMD_ARG("meshid", set80211meshid),
DEF_CMD_ARG("stationname", set80211stationname),
DEF_CMD_ARG("station", set80211stationname), /* BSD/OS */
DEF_CMD_ARG("channel", set80211channel),
DEF_CMD_ARG("authmode", set80211authmode),
DEF_CMD_ARG("powersavemode", set80211powersavemode),
DEF_CMD("powersave", 1, set80211powersave),
DEF_CMD("-powersave", 0, set80211powersave),
DEF_CMD_ARG("powersavesleep", set80211powersavesleep),
DEF_CMD_ARG("wepmode", set80211wepmode),
DEF_CMD("wep", 1, set80211wep),
DEF_CMD("-wep", 0, set80211wep),
DEF_CMD_ARG("deftxkey", set80211weptxkey),
DEF_CMD_ARG("weptxkey", set80211weptxkey),
DEF_CMD_ARG("wepkey", set80211wepkey),
DEF_CMD_ARG("nwkey", set80211nwkey), /* NetBSD */
DEF_CMD("-nwkey", 0, set80211wep), /* NetBSD */
DEF_CMD_ARG("rtsthreshold", set80211rtsthreshold),
DEF_CMD_ARG("protmode", set80211protmode),
DEF_CMD_ARG("txpower", set80211txpower),
DEF_CMD_ARG("roaming", set80211roaming),
DEF_CMD("wme", 1, set80211wme),
DEF_CMD("-wme", 0, set80211wme),
DEF_CMD("wmm", 1, set80211wme),
DEF_CMD("-wmm", 0, set80211wme),
DEF_CMD("hidessid", 1, set80211hidessid),
DEF_CMD("-hidessid", 0, set80211hidessid),
DEF_CMD("apbridge", 1, set80211apbridge),
DEF_CMD("-apbridge", 0, set80211apbridge),
DEF_CMD_ARG("chanlist", set80211chanlist),
DEF_CMD_ARG("bssid", set80211bssid),
DEF_CMD_ARG("ap", set80211bssid),
DEF_CMD("scan", 0, set80211scan),
DEF_CMD_ARG("list", set80211list),
DEF_CMD_ARG2("cwmin", set80211cwmin),
DEF_CMD_ARG2("cwmax", set80211cwmax),
DEF_CMD_ARG2("aifs", set80211aifs),
DEF_CMD_ARG2("txoplimit", set80211txoplimit),
DEF_CMD_ARG("acm", set80211acm),
DEF_CMD_ARG("-acm", set80211noacm),
DEF_CMD_ARG("ack", set80211ackpolicy),
DEF_CMD_ARG("-ack", set80211noackpolicy),
DEF_CMD_ARG2("bss:cwmin", set80211bsscwmin),
DEF_CMD_ARG2("bss:cwmax", set80211bsscwmax),
DEF_CMD_ARG2("bss:aifs", set80211bssaifs),
DEF_CMD_ARG2("bss:txoplimit", set80211bsstxoplimit),
DEF_CMD_ARG("dtimperiod", set80211dtimperiod),
DEF_CMD_ARG("bintval", set80211bintval),
DEF_CMD("mac:open", IEEE80211_MACCMD_POLICY_OPEN, set80211maccmd),
DEF_CMD("mac:allow", IEEE80211_MACCMD_POLICY_ALLOW, set80211maccmd),
DEF_CMD("mac:deny", IEEE80211_MACCMD_POLICY_DENY, set80211maccmd),
DEF_CMD("mac:radius", IEEE80211_MACCMD_POLICY_RADIUS, set80211maccmd),
DEF_CMD("mac:flush", IEEE80211_MACCMD_FLUSH, set80211maccmd),
DEF_CMD("mac:detach", IEEE80211_MACCMD_DETACH, set80211maccmd),
DEF_CMD_ARG("mac:add", set80211addmac),
DEF_CMD_ARG("mac:del", set80211delmac),
DEF_CMD_ARG("mac:kick", set80211kickmac),
DEF_CMD("pureg", 1, set80211pureg),
DEF_CMD("-pureg", 0, set80211pureg),
DEF_CMD("ff", 1, set80211fastframes),
DEF_CMD("-ff", 0, set80211fastframes),
DEF_CMD("dturbo", 1, set80211dturbo),
DEF_CMD("-dturbo", 0, set80211dturbo),
DEF_CMD("bgscan", 1, set80211bgscan),
DEF_CMD("-bgscan", 0, set80211bgscan),
DEF_CMD_ARG("bgscanidle", set80211bgscanidle),
DEF_CMD_ARG("bgscanintvl", set80211bgscanintvl),
DEF_CMD_ARG("scanvalid", set80211scanvalid),
DEF_CMD("quiet", 1, set80211quiet),
DEF_CMD("-quiet", 0, set80211quiet),
DEF_CMD_ARG("quiet_count", set80211quietcount),
DEF_CMD_ARG("quiet_period", set80211quietperiod),
DEF_CMD_ARG("quiet_dur", set80211quietduration),
DEF_CMD_ARG("quiet_offset", set80211quietoffset),
DEF_CMD_ARG("roam:rssi", set80211roamrssi),
DEF_CMD_ARG("roam:rate", set80211roamrate),
DEF_CMD_ARG("mcastrate", set80211mcastrate),
DEF_CMD_ARG("ucastrate", set80211ucastrate),
DEF_CMD_ARG("mgtrate", set80211mgtrate),
DEF_CMD_ARG("mgmtrate", set80211mgtrate),
DEF_CMD_ARG("maxretry", set80211maxretry),
DEF_CMD_ARG("fragthreshold", set80211fragthreshold),
DEF_CMD("burst", 1, set80211burst),
DEF_CMD("-burst", 0, set80211burst),
DEF_CMD_ARG("bmiss", set80211bmissthreshold),
DEF_CMD_ARG("bmissthreshold", set80211bmissthreshold),
DEF_CMD("shortgi", 1, set80211shortgi),
DEF_CMD("-shortgi", 0, set80211shortgi),
DEF_CMD("ampdurx", 2, set80211ampdu),
DEF_CMD("-ampdurx", -2, set80211ampdu),
DEF_CMD("ampdutx", 1, set80211ampdu),
DEF_CMD("-ampdutx", -1, set80211ampdu),
DEF_CMD("ampdu", 3, set80211ampdu), /* NB: tx+rx */
DEF_CMD("-ampdu", -3, set80211ampdu),
DEF_CMD_ARG("ampdulimit", set80211ampdulimit),
DEF_CMD_ARG("ampdudensity", set80211ampdudensity),
DEF_CMD("amsdurx", 2, set80211amsdu),
DEF_CMD("-amsdurx", -2, set80211amsdu),
DEF_CMD("amsdutx", 1, set80211amsdu),
DEF_CMD("-amsdutx", -1, set80211amsdu),
DEF_CMD("amsdu", 3, set80211amsdu), /* NB: tx+rx */
DEF_CMD("-amsdu", -3, set80211amsdu),
DEF_CMD_ARG("amsdulimit", set80211amsdulimit),
DEF_CMD("puren", 1, set80211puren),
DEF_CMD("-puren", 0, set80211puren),
DEF_CMD("doth", 1, set80211doth),
DEF_CMD("-doth", 0, set80211doth),
DEF_CMD("dfs", 1, set80211dfs),
DEF_CMD("-dfs", 0, set80211dfs),
DEF_CMD("htcompat", 1, set80211htcompat),
DEF_CMD("-htcompat", 0, set80211htcompat),
DEF_CMD("dwds", 1, set80211dwds),
DEF_CMD("-dwds", 0, set80211dwds),
DEF_CMD("inact", 1, set80211inact),
DEF_CMD("-inact", 0, set80211inact),
DEF_CMD("tsn", 1, set80211tsn),
DEF_CMD("-tsn", 0, set80211tsn),
DEF_CMD_ARG("regdomain", set80211regdomain),
DEF_CMD_ARG("country", set80211country),
DEF_CMD("indoor", 'I', set80211location),
DEF_CMD("-indoor", 'O', set80211location),
DEF_CMD("outdoor", 'O', set80211location),
DEF_CMD("-outdoor", 'I', set80211location),
DEF_CMD("anywhere", ' ', set80211location),
DEF_CMD("ecm", 1, set80211ecm),
DEF_CMD("-ecm", 0, set80211ecm),
DEF_CMD("dotd", 1, set80211dotd),
DEF_CMD("-dotd", 0, set80211dotd),
DEF_CMD_ARG("htprotmode", set80211htprotmode),
DEF_CMD("ht20", 1, set80211htconf),
DEF_CMD("-ht20", 0, set80211htconf),
DEF_CMD("ht40", 3, set80211htconf), /* NB: 20+40 */
DEF_CMD("-ht40", 0, set80211htconf),
DEF_CMD("ht", 3, set80211htconf), /* NB: 20+40 */
DEF_CMD("-ht", 0, set80211htconf),
DEF_CMD("rifs", 1, set80211rifs),
DEF_CMD("-rifs", 0, set80211rifs),
DEF_CMD("smps", IEEE80211_HTCAP_SMPS_ENA, set80211smps),
DEF_CMD("smpsdyn", IEEE80211_HTCAP_SMPS_DYNAMIC, set80211smps),
DEF_CMD("-smps", IEEE80211_HTCAP_SMPS_OFF, set80211smps),
/* XXX for testing */
DEF_CMD_ARG("chanswitch", set80211chanswitch),
DEF_CMD_ARG("tdmaslot", set80211tdmaslot),
DEF_CMD_ARG("tdmaslotcnt", set80211tdmaslotcnt),
DEF_CMD_ARG("tdmaslotlen", set80211tdmaslotlen),
DEF_CMD_ARG("tdmabintval", set80211tdmabintval),
DEF_CMD_ARG("meshttl", set80211meshttl),
DEF_CMD("meshforward", 1, set80211meshforward),
DEF_CMD("-meshforward", 0, set80211meshforward),
DEF_CMD("meshgate", 1, set80211meshgate),
DEF_CMD("-meshgate", 0, set80211meshgate),
DEF_CMD("meshpeering", 1, set80211meshpeering),
DEF_CMD("-meshpeering", 0, set80211meshpeering),
DEF_CMD_ARG("meshmetric", set80211meshmetric),
DEF_CMD_ARG("meshpath", set80211meshpath),
DEF_CMD("meshrt:flush", IEEE80211_MESH_RTCMD_FLUSH, set80211meshrtcmd),
DEF_CMD_ARG("meshrt:add", set80211addmeshrt),
DEF_CMD_ARG("meshrt:del", set80211delmeshrt),
DEF_CMD_ARG("hwmprootmode", set80211hwmprootmode),
DEF_CMD_ARG("hwmpmaxhops", set80211hwmpmaxhops),
/* vap cloning support */
DEF_CLONE_CMD_ARG("wlanaddr", set80211clone_wlanaddr),
DEF_CLONE_CMD_ARG("wlanbssid", set80211clone_wlanbssid),
DEF_CLONE_CMD_ARG("wlandev", set80211clone_wlandev),
DEF_CLONE_CMD_ARG("wlanmode", set80211clone_wlanmode),
DEF_CLONE_CMD("beacons", 1, set80211clone_beacons),
DEF_CLONE_CMD("-beacons", 0, set80211clone_beacons),
DEF_CLONE_CMD("bssid", 1, set80211clone_bssid),
DEF_CLONE_CMD("-bssid", 0, set80211clone_bssid),
DEF_CLONE_CMD("wdslegacy", 1, set80211clone_wdslegacy),
DEF_CLONE_CMD("-wdslegacy", 0, set80211clone_wdslegacy),
};
static struct afswtch af_ieee80211 = {
.af_name = "af_ieee80211",
.af_af = AF_UNSPEC,
.af_other_status = ieee80211_status,
};
static __constructor void
ieee80211_ctor(void)
{
#define N(a) (sizeof(a) / sizeof(a[0]))
int i;
for (i = 0; i < N(ieee80211_cmds); i++)
cmd_register(&ieee80211_cmds[i]);
af_register(&af_ieee80211);
clone_setdefcallback("wlan", wlan_create);
#undef N
}
|
jhbsz/OSI-OS
|
sbin/ifconfig/ifieee80211.c
|
C
|
bsd-3-clause
| 139,371
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/examples/menu_example.h"
#include <set>
#include "base/utf_string_conversions.h"
#include "ui/base/models/simple_menu_model.h"
#include "ui/views/controls/button/menu_button.h"
#include "ui/views/controls/button/menu_button_listener.h"
#include "ui/views/controls/menu/menu_model_adapter.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace examples {
namespace {
class ExampleMenuModel : public ui::SimpleMenuModel,
public ui::SimpleMenuModel::Delegate {
public:
ExampleMenuModel();
// Overridden from ui::SimpleMenuModel::Delegate:
virtual bool IsCommandIdChecked(int command_id) const OVERRIDE;
virtual bool IsCommandIdEnabled(int command_id) const OVERRIDE;
virtual bool GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) OVERRIDE;
virtual void ExecuteCommand(int command_id) OVERRIDE;
private:
enum GroupID {
GROUP_MAKE_DECISION,
};
enum CommandID {
COMMAND_DO_SOMETHING,
COMMAND_SELECT_ASCII,
COMMAND_SELECT_UTF8,
COMMAND_SELECT_UTF16,
COMMAND_CHECK_APPLE,
COMMAND_CHECK_ORANGE,
COMMAND_CHECK_KIWI,
COMMAND_GO_HOME,
};
scoped_ptr<ui::SimpleMenuModel> submenu_;
std::set<int> checked_fruits_;
int current_encoding_command_id_;
DISALLOW_COPY_AND_ASSIGN(ExampleMenuModel);
};
class ExampleMenuButton : public MenuButton, public MenuButtonListener {
public:
explicit ExampleMenuButton(const string16& test);
virtual ~ExampleMenuButton();
private:
// Overridden from MenuButtonListener:
virtual void OnMenuButtonClicked(View* source,
const gfx::Point& point) OVERRIDE;
ui::SimpleMenuModel* GetMenuModel();
scoped_ptr<ExampleMenuModel> menu_model_;
scoped_ptr<MenuRunner> menu_runner_;
DISALLOW_COPY_AND_ASSIGN(ExampleMenuButton);
};
// ExampleMenuModel ---------------------------------------------------------
ExampleMenuModel::ExampleMenuModel()
: ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
current_encoding_command_id_(COMMAND_SELECT_ASCII) {
AddItem(COMMAND_DO_SOMETHING, ASCIIToUTF16("Do Something"));
AddSeparator();
AddRadioItem(COMMAND_SELECT_ASCII, ASCIIToUTF16("ASCII"),
GROUP_MAKE_DECISION);
AddRadioItem(COMMAND_SELECT_UTF8, ASCIIToUTF16("UTF-8"),
GROUP_MAKE_DECISION);
AddRadioItem(COMMAND_SELECT_UTF16, ASCIIToUTF16("UTF-16"),
GROUP_MAKE_DECISION);
AddSeparator();
AddCheckItem(COMMAND_CHECK_APPLE, ASCIIToUTF16("Apple"));
AddCheckItem(COMMAND_CHECK_ORANGE, ASCIIToUTF16("Orange"));
AddCheckItem(COMMAND_CHECK_KIWI, ASCIIToUTF16("Kiwi"));
AddSeparator();
AddItem(COMMAND_GO_HOME, ASCIIToUTF16("Go Home"));
submenu_.reset(new ui::SimpleMenuModel(this));
submenu_->AddItem(COMMAND_DO_SOMETHING, ASCIIToUTF16("Do Something 2"));
AddSubMenu(0, ASCIIToUTF16("Submenu"), submenu_.get());
}
bool ExampleMenuModel::IsCommandIdChecked(int command_id) const {
// Radio items.
if (command_id == current_encoding_command_id_)
return true;
// Check items.
if (checked_fruits_.find(command_id) != checked_fruits_.end())
return true;
return false;
}
bool ExampleMenuModel::IsCommandIdEnabled(int command_id) const {
// All commands are enabled except for COMMAND_GO_HOME.
return command_id != COMMAND_GO_HOME;
}
bool ExampleMenuModel::GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) {
// We don't use this in the example.
return false;
}
void ExampleMenuModel::ExecuteCommand(int command_id) {
switch (command_id) {
case COMMAND_DO_SOMETHING: {
LOG(INFO) << "Done something";
break;
}
// Radio items.
case COMMAND_SELECT_ASCII: {
current_encoding_command_id_ = COMMAND_SELECT_ASCII;
LOG(INFO) << "Selected ASCII";
break;
}
case COMMAND_SELECT_UTF8: {
current_encoding_command_id_ = COMMAND_SELECT_UTF8;
LOG(INFO) << "Selected UTF-8";
break;
}
case COMMAND_SELECT_UTF16: {
current_encoding_command_id_ = COMMAND_SELECT_UTF16;
LOG(INFO) << "Selected UTF-16";
break;
}
// Check items.
case COMMAND_CHECK_APPLE:
case COMMAND_CHECK_ORANGE:
case COMMAND_CHECK_KIWI: {
// Print what fruit is checked.
const char* checked_fruit = "";
if (command_id == COMMAND_CHECK_APPLE)
checked_fruit = "Apple";
else if (command_id == COMMAND_CHECK_ORANGE)
checked_fruit = "Orange";
else if (command_id == COMMAND_CHECK_KIWI)
checked_fruit = "Kiwi";
// Update the check status.
std::set<int>::iterator iter = checked_fruits_.find(command_id);
if (iter == checked_fruits_.end()) {
VLOG(1) << "Checked " << checked_fruit;
checked_fruits_.insert(command_id);
} else {
VLOG(1) << "Unchecked " << checked_fruit;
checked_fruits_.erase(iter);
}
break;
}
}
}
// ExampleMenuButton -----------------------------------------------------------
ExampleMenuButton::ExampleMenuButton(const string16& test)
: ALLOW_THIS_IN_INITIALIZER_LIST(MenuButton(NULL, test, this, true)) {
}
ExampleMenuButton::~ExampleMenuButton() {
}
void ExampleMenuButton::OnMenuButtonClicked(View* source,
const gfx::Point& point) {
MenuModelAdapter menu_model_adapter(GetMenuModel());
menu_runner_.reset(new MenuRunner(menu_model_adapter.CreateMenu()));
if (menu_runner_->RunMenuAt(source->GetWidget()->GetTopLevelWidget(), this,
gfx::Rect(point, gfx::Size()), views::MenuItemView::TOPRIGHT,
views::MenuRunner::HAS_MNEMONICS) == views::MenuRunner::MENU_DELETED)
return;
}
ui::SimpleMenuModel* ExampleMenuButton::GetMenuModel() {
if (!menu_model_.get())
menu_model_.reset(new ExampleMenuModel);
return menu_model_.get();
}
} // namespace
MenuExample::MenuExample() : ExampleBase("Menu") {
}
MenuExample::~MenuExample() {
}
void MenuExample::CreateExampleView(View* container) {
// We add a button to open a menu.
ExampleMenuButton* menu_button = new ExampleMenuButton(
ASCIIToUTF16("Open a menu"));
container->SetLayoutManager(new FillLayout);
container->AddChildView(menu_button);
}
} // namespace examples
} // namespace views
|
gavinp/chromium
|
ui/views/examples/menu_example.cc
|
C++
|
bsd-3-clause
| 6,609
|
"""
====================================================
Imputing missing values before building an estimator
====================================================
Missing values can be replaced by the mean, the median or the most frequent
value using the basic :class:`sklearn.impute.SimpleImputer`.
The median is a more robust estimator for data with high magnitude variables
which could dominate results (otherwise known as a 'long tail').
Another option is the :class:`sklearn.impute.IterativeImputer`. This uses
round-robin linear regression, treating every variable as an output in
turn. The version implemented assumes Gaussian (output) variables. If your
features are obviously non-Normal, consider transforming them to look more
Normal so as to potentially improve performance.
In addition of using an imputing method, we can also keep an indication of the
missing information using :func:`sklearn.impute.MissingIndicator` which might
carry some information.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
# To use the experimental IterativeImputer, we need to explicitly ask for it:
from sklearn.experimental import enable_iterative_imputer # noqa
from sklearn.datasets import load_diabetes
from sklearn.datasets import load_boston
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import make_pipeline, make_union
from sklearn.impute import SimpleImputer, IterativeImputer, MissingIndicator
from sklearn.model_selection import cross_val_score
rng = np.random.RandomState(0)
N_SPLITS = 5
REGRESSOR = RandomForestRegressor(random_state=0)
def get_scores_for_imputer(imputer, X_missing, y_missing):
estimator = make_pipeline(
make_union(imputer, MissingIndicator(missing_values=0)),
REGRESSOR)
impute_scores = cross_val_score(estimator, X_missing, y_missing,
scoring='neg_mean_squared_error',
cv=N_SPLITS)
return impute_scores
def get_results(dataset):
X_full, y_full = dataset.data, dataset.target
n_samples = X_full.shape[0]
n_features = X_full.shape[1]
# Estimate the score on the entire dataset, with no missing values
full_scores = cross_val_score(REGRESSOR, X_full, y_full,
scoring='neg_mean_squared_error',
cv=N_SPLITS)
# Add missing values in 75% of the lines
missing_rate = 0.75
n_missing_samples = int(np.floor(n_samples * missing_rate))
missing_samples = np.hstack((np.zeros(n_samples - n_missing_samples,
dtype=np.bool),
np.ones(n_missing_samples,
dtype=np.bool)))
rng.shuffle(missing_samples)
missing_features = rng.randint(0, n_features, n_missing_samples)
X_missing = X_full.copy()
X_missing[np.where(missing_samples)[0], missing_features] = 0
y_missing = y_full.copy()
# Estimate the score after replacing missing values by 0
imputer = SimpleImputer(missing_values=0,
strategy='constant',
fill_value=0)
zero_impute_scores = get_scores_for_imputer(imputer, X_missing, y_missing)
# Estimate the score after imputation (mean strategy) of the missing values
imputer = SimpleImputer(missing_values=0, strategy="mean")
mean_impute_scores = get_scores_for_imputer(imputer, X_missing, y_missing)
# Estimate the score after iterative imputation of the missing values
imputer = IterativeImputer(missing_values=0,
random_state=0,
n_nearest_features=5,
sample_posterior=True)
iterative_impute_scores = get_scores_for_imputer(imputer,
X_missing,
y_missing)
return ((full_scores.mean(), full_scores.std()),
(zero_impute_scores.mean(), zero_impute_scores.std()),
(mean_impute_scores.mean(), mean_impute_scores.std()),
(iterative_impute_scores.mean(), iterative_impute_scores.std()))
results_diabetes = np.array(get_results(load_diabetes()))
mses_diabetes = results_diabetes[:, 0] * -1
stds_diabetes = results_diabetes[:, 1]
results_boston = np.array(get_results(load_boston()))
mses_boston = results_boston[:, 0] * -1
stds_boston = results_boston[:, 1]
n_bars = len(mses_diabetes)
xval = np.arange(n_bars)
x_labels = ['Full data',
'Zero imputation',
'Mean Imputation',
'Multivariate Imputation']
colors = ['r', 'g', 'b', 'orange']
# plot diabetes results
plt.figure(figsize=(12, 6))
ax1 = plt.subplot(121)
for j in xval:
ax1.barh(j, mses_diabetes[j], xerr=stds_diabetes[j],
color=colors[j], alpha=0.6, align='center')
ax1.set_title('Imputation Techniques with Diabetes Data')
ax1.set_xlim(left=np.min(mses_diabetes) * 0.9,
right=np.max(mses_diabetes) * 1.1)
ax1.set_yticks(xval)
ax1.set_xlabel('MSE')
ax1.invert_yaxis()
ax1.set_yticklabels(x_labels)
# plot boston results
ax2 = plt.subplot(122)
for j in xval:
ax2.barh(j, mses_boston[j], xerr=stds_boston[j],
color=colors[j], alpha=0.6, align='center')
ax2.set_title('Imputation Techniques with Boston Data')
ax2.set_yticks(xval)
ax2.set_xlabel('MSE')
ax2.invert_yaxis()
ax2.set_yticklabels([''] * n_bars)
plt.show()
|
chrsrds/scikit-learn
|
examples/impute/plot_missing_values.py
|
Python
|
bsd-3-clause
| 5,503
|
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkStreamPriv_DEFINED
#define SkStreamPriv_DEFINED
#include "include/core/SkRefCnt.h"
#include "include/core/SkStream.h"
class SkData;
/**
* Copy the provided stream to an SkData variable.
*
* Note: Assumes the stream is at the beginning. If it has a length,
* but is not at the beginning, this call will fail (return NULL).
*
* @param stream SkStream to be copied into data.
* @return The resulting SkData after the copy, nullptr on failure.
*/
sk_sp<SkData> SkCopyStreamToData(SkStream* stream);
/**
* Copies the input stream from the current position to the end.
* Does not rewind the input stream.
*/
bool SkStreamCopy(SkWStream* out, SkStream* input);
/** A SkWStream that writes all output to SkDebugf, for debugging purposes. */
class SkDebugfStream final : public SkWStream {
public:
bool write(const void* buffer, size_t size) override;
size_t bytesWritten() const override;
private:
size_t fBytesWritten = 0;
};
#endif // SkStreamPriv_DEFINED
|
google/skia
|
src/core/SkStreamPriv.h
|
C
|
bsd-3-clause
| 1,143
|
package spark.streaming.input
import spark.storage.StorageLevel
import spark.streaming.StreamingContext
import spark.streaming.DStream
import spark.streaming.dstream.KafkaInputDStream
/**
* A wrapper around StreamingContext for exposing Kafka functions. This is done in a separate
* class so that programs that don't use Kafka don't need to link against it. In Scala, an
* implicit conversion in StreamingContext allows one to call these functions.
*/
class KafkaFunctions(self: StreamingContext) {
/**
* Create an input stream that pulls messages from a Kafka Broker.
* @param zkQuorum Zookeper quorum (hostname:port,hostname:port,..).
* @param groupId The group id for this consumer.
* @param topics Map of (topic_name -> numPartitions) to consume. Each partition is consumed
* in its own thread.
* @param storageLevel Storage level to use for storing the received objects
* (default: StorageLevel.MEMORY_AND_DISK_SER_2)
*/
def kafkaStream(
zkQuorum: String,
groupId: String,
topics: Map[String, Int],
storageLevel: StorageLevel = StorageLevel.MEMORY_AND_DISK_SER_2
): DStream[String] = {
val kafkaParams = Map[String, String](
"zk.connect" -> zkQuorum, "groupid" -> groupId, "zk.connectiontimeout.ms" -> "10000")
kafkaStream[String, kafka.serializer.StringDecoder](kafkaParams, topics, storageLevel)
}
/**
* Create an input stream that pulls messages from a Kafka Broker.
* @param kafkaParams Map of kafka configuration paramaters.
* See: http://kafka.apache.org/configuration.html
* @param topics Map of (topic_name -> numPartitions) to consume. Each partition is consumed
* in its own thread.
* @param storageLevel Storage level to use for storing the received objects
*/
def kafkaStream[T: ClassManifest, D <: kafka.serializer.Decoder[_]: Manifest](
kafkaParams: Map[String, String],
topics: Map[String, Int],
storageLevel: StorageLevel
): DStream[T] = {
val inputStream = new KafkaInputDStream[T, D](self, kafkaParams, topics, storageLevel)
self.registerInputStream(inputStream)
inputStream
}
}
|
prabeesh/Spark-Kestrel
|
streaming/src/main/scala/spark/streaming/input/KafkaFunctions.scala
|
Scala
|
bsd-3-clause
| 2,212
|
import django.db.models as models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_save
class Profile(models.Model):
"""
parameters we can get from gigya:
birthMonth,isLoggedIn,city,UID,zip,birthYear,state,provider,email,
UIDSig,photoURL,timestamp,loginProviderUID,signature,isSiteUID,proxiedEmail
,thumbnailURL,nickname,firstName,loginProvider,gender,lastName,profileURL
birthDay,country,isSiteUser
One unique user can have several UID's
"""
user = models.ForeignKey(User, unique=True, null=True)
uid = models.CharField(max_length=255)
login_provider = models.CharField(max_length=150)
timestamp = models.DateTimeField(null=True,blank=True)
isLoggedIn = models.BooleanField(default=False)
birthday = models.DateField(null=True,blank=True)
city = models.CharField(max_length=150, null=True,blank=True)
state = models.CharField(max_length=150, null=True,blank=True)
zip = models.CharField(max_length=30, null=True,blank=True)
country = models.CharField(max_length=30, null=True,blank=True)
photourl = models.CharField(max_length=255, null=True,blank=True)
first_name = models.CharField(max_length=80, null=True,blank=True)
last_name = models.CharField(max_length=80, null=True,blank=True)
gender = models.CharField(max_length=2, null=True,blank=True)
profileUrl = models.CharField(max_length=2, null=True, blank=True)
def create_profile(sender, instance=None, **kwargs):
if instance is None:
return
profile, created = Profile.objects.get_or_create(user=instance)
post_save.connect(create_profile, sender=User)
|
MediaSapiens/wavesf
|
apps/externals/gigyauth/models.py
|
Python
|
bsd-3-clause
| 1,844
|
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test-order-2</title>
<style>
body {
background-color: orange;
}
</style>
<!-- proves transitive imports also execute in order, but
fails to block rendering on transitive style sheet (suggesting a bug) -->
<link rel="import" href="import.html">
</head>
<body unresolved>
</body>
</html>
|
PolymerLabs/labs
|
sjmiles/imports/test-script-order-2/test.html
|
HTML
|
bsd-3-clause
| 397
|
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/asn1"
"errors"
"io"
"math/big"
)
var errClientKeyExchange = errors.New("tls: invalid ClientKeyExchange message")
var errServerKeyExchange = errors.New("tls: invalid ServerKeyExchange message")
// rsaKeyAgreement implements the standard TLS key agreement where the client
// encrypts the pre-master secret to the server's public key.
type rsaKeyAgreement struct {
clientVersion uint16
}
func (ka *rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
// Save the client version for comparison later.
ka.clientVersion = versionToWire(clientHello.vers, clientHello.isDTLS)
if config.Bugs.RSAServerKeyExchange {
// Send an empty ServerKeyExchange message.
return &serverKeyExchangeMsg{}, nil
}
return nil, nil
}
func (ka *rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
preMasterSecret := make([]byte, 48)
_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
if err != nil {
return nil, err
}
if len(ckx.ciphertext) < 2 {
return nil, errClientKeyExchange
}
ciphertext := ckx.ciphertext
if version != VersionSSL30 {
ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1])
if ciphertextLen != len(ckx.ciphertext)-2 {
return nil, errClientKeyExchange
}
ciphertext = ckx.ciphertext[2:]
}
err = rsa.DecryptPKCS1v15SessionKey(config.rand(), cert.PrivateKey.(*rsa.PrivateKey), ciphertext, preMasterSecret)
if err != nil {
return nil, err
}
// This check should be done in constant-time, but this is a testing
// implementation. See the discussion at the end of section 7.4.7.1 of
// RFC 4346.
vers := uint16(preMasterSecret[0])<<8 | uint16(preMasterSecret[1])
if ka.clientVersion != vers {
return nil, errors.New("tls: invalid version in RSA premaster")
}
return preMasterSecret, nil
}
func (ka *rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
return errors.New("tls: unexpected ServerKeyExchange")
}
func (ka *rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
preMasterSecret := make([]byte, 48)
vers := clientHello.vers
if config.Bugs.RsaClientKeyExchangeVersion != 0 {
vers = config.Bugs.RsaClientKeyExchangeVersion
}
vers = versionToWire(vers, clientHello.isDTLS)
preMasterSecret[0] = byte(vers >> 8)
preMasterSecret[1] = byte(vers)
_, err := io.ReadFull(config.rand(), preMasterSecret[2:])
if err != nil {
return nil, nil, err
}
encrypted, err := rsa.EncryptPKCS1v15(config.rand(), cert.PublicKey.(*rsa.PublicKey), preMasterSecret)
if err != nil {
return nil, nil, err
}
ckx := new(clientKeyExchangeMsg)
if clientHello.vers != VersionSSL30 && !config.Bugs.SSL3RSAKeyExchange {
ckx.ciphertext = make([]byte, len(encrypted)+2)
ckx.ciphertext[0] = byte(len(encrypted) >> 8)
ckx.ciphertext[1] = byte(len(encrypted))
copy(ckx.ciphertext[2:], encrypted)
} else {
ckx.ciphertext = encrypted
}
return preMasterSecret, ckx, nil
}
// sha1Hash calculates a SHA1 hash over the given byte slices.
func sha1Hash(slices [][]byte) []byte {
hsha1 := sha1.New()
for _, slice := range slices {
hsha1.Write(slice)
}
return hsha1.Sum(nil)
}
// md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the
// concatenation of an MD5 and SHA1 hash.
func md5SHA1Hash(slices [][]byte) []byte {
md5sha1 := make([]byte, md5.Size+sha1.Size)
hmd5 := md5.New()
for _, slice := range slices {
hmd5.Write(slice)
}
copy(md5sha1, hmd5.Sum(nil))
copy(md5sha1[md5.Size:], sha1Hash(slices))
return md5sha1
}
// hashForServerKeyExchange hashes the given slices and returns their digest
// and the identifier of the hash function used. The hashFunc argument is only
// used for >= TLS 1.2 and precisely identifies the hash function to use.
func hashForServerKeyExchange(sigType, hashFunc uint8, version uint16, slices ...[]byte) ([]byte, crypto.Hash, error) {
if version >= VersionTLS12 {
hash, err := lookupTLSHash(hashFunc)
if err != nil {
return nil, 0, err
}
h := hash.New()
for _, slice := range slices {
h.Write(slice)
}
return h.Sum(nil), hash, nil
}
if sigType == signatureECDSA {
return sha1Hash(slices), crypto.SHA1, nil
}
return md5SHA1Hash(slices), crypto.MD5SHA1, nil
}
// pickTLS12HashForSignature returns a TLS 1.2 hash identifier for signing a
// ServerKeyExchange given the signature type being used and the client's
// advertized list of supported signature and hash combinations.
func pickTLS12HashForSignature(sigType uint8, clientSignatureAndHashes []signatureAndHash) (uint8, error) {
if len(clientSignatureAndHashes) == 0 {
// If the client didn't specify any signature_algorithms
// extension then we can assume that it supports SHA1. See
// http://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
return hashSHA1, nil
}
for _, sigAndHash := range clientSignatureAndHashes {
if sigAndHash.signature != sigType {
continue
}
switch sigAndHash.hash {
case hashSHA1, hashSHA256:
return sigAndHash.hash, nil
}
}
return 0, errors.New("tls: client doesn't support any common hash functions")
}
func curveForCurveID(id CurveID) (elliptic.Curve, bool) {
switch id {
case CurveP256:
return elliptic.P256(), true
case CurveP384:
return elliptic.P384(), true
case CurveP521:
return elliptic.P521(), true
default:
return nil, false
}
}
// keyAgreementAuthentication is a helper interface that specifies how
// to authenticate the ServerKeyExchange parameters.
type keyAgreementAuthentication interface {
signParameters(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, params []byte) (*serverKeyExchangeMsg, error)
verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, params []byte, sig []byte) error
}
// nilKeyAgreementAuthentication does not authenticate the key
// agreement parameters.
type nilKeyAgreementAuthentication struct{}
func (ka *nilKeyAgreementAuthentication) signParameters(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, params []byte) (*serverKeyExchangeMsg, error) {
skx := new(serverKeyExchangeMsg)
skx.key = params
return skx, nil
}
func (ka *nilKeyAgreementAuthentication) verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, params []byte, sig []byte) error {
return nil
}
// signedKeyAgreement signs the ServerKeyExchange parameters with the
// server's private key.
type signedKeyAgreement struct {
version uint16
sigType uint8
}
func (ka *signedKeyAgreement) signParameters(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg, params []byte) (*serverKeyExchangeMsg, error) {
var tls12HashId uint8
var err error
if ka.version >= VersionTLS12 {
if tls12HashId, err = pickTLS12HashForSignature(ka.sigType, clientHello.signatureAndHashes); err != nil {
return nil, err
}
}
digest, hashFunc, err := hashForServerKeyExchange(ka.sigType, tls12HashId, ka.version, clientHello.random, hello.random, params)
if err != nil {
return nil, err
}
if config.Bugs.InvalidSKXSignature {
digest[0] ^= 0x80
}
var sig []byte
switch ka.sigType {
case signatureECDSA:
privKey, ok := cert.PrivateKey.(*ecdsa.PrivateKey)
if !ok {
return nil, errors.New("ECDHE ECDSA requires an ECDSA server private key")
}
r, s, err := ecdsa.Sign(config.rand(), privKey, digest)
if err != nil {
return nil, errors.New("failed to sign ECDHE parameters: " + err.Error())
}
order := privKey.Curve.Params().N
r = maybeCorruptECDSAValue(r, config.Bugs.BadECDSAR, order)
s = maybeCorruptECDSAValue(s, config.Bugs.BadECDSAS, order)
sig, err = asn1.Marshal(ecdsaSignature{r, s})
case signatureRSA:
privKey, ok := cert.PrivateKey.(*rsa.PrivateKey)
if !ok {
return nil, errors.New("ECDHE RSA requires a RSA server private key")
}
sig, err = rsa.SignPKCS1v15(config.rand(), privKey, hashFunc, digest)
if err != nil {
return nil, errors.New("failed to sign ECDHE parameters: " + err.Error())
}
default:
return nil, errors.New("unknown ECDHE signature algorithm")
}
skx := new(serverKeyExchangeMsg)
if config.Bugs.UnauthenticatedECDH {
skx.key = params
} else {
sigAndHashLen := 0
if ka.version >= VersionTLS12 {
sigAndHashLen = 2
}
skx.key = make([]byte, len(params)+sigAndHashLen+2+len(sig))
copy(skx.key, params)
k := skx.key[len(params):]
if ka.version >= VersionTLS12 {
k[0] = tls12HashId
k[1] = ka.sigType
k = k[2:]
}
k[0] = byte(len(sig) >> 8)
k[1] = byte(len(sig))
copy(k[2:], sig)
}
return skx, nil
}
func (ka *signedKeyAgreement) verifyParameters(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, params []byte, sig []byte) error {
if len(sig) < 2 {
return errServerKeyExchange
}
var tls12HashId uint8
if ka.version >= VersionTLS12 {
// handle SignatureAndHashAlgorithm
var sigAndHash []uint8
sigAndHash, sig = sig[:2], sig[2:]
if sigAndHash[1] != ka.sigType {
return errServerKeyExchange
}
tls12HashId = sigAndHash[0]
if len(sig) < 2 {
return errServerKeyExchange
}
if !isSupportedSignatureAndHash(signatureAndHash{ka.sigType, tls12HashId}, config.signatureAndHashesForClient()) {
return errors.New("tls: unsupported hash function for ServerKeyExchange")
}
}
sigLen := int(sig[0])<<8 | int(sig[1])
if sigLen+2 != len(sig) {
return errServerKeyExchange
}
sig = sig[2:]
digest, hashFunc, err := hashForServerKeyExchange(ka.sigType, tls12HashId, ka.version, clientHello.random, serverHello.random, params)
if err != nil {
return err
}
switch ka.sigType {
case signatureECDSA:
pubKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
if !ok {
return errors.New("ECDHE ECDSA requires a ECDSA server public key")
}
ecdsaSig := new(ecdsaSignature)
if _, err := asn1.Unmarshal(sig, ecdsaSig); err != nil {
return err
}
if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
return errors.New("ECDSA signature contained zero or negative values")
}
if !ecdsa.Verify(pubKey, digest, ecdsaSig.R, ecdsaSig.S) {
return errors.New("ECDSA verification failure")
}
case signatureRSA:
pubKey, ok := cert.PublicKey.(*rsa.PublicKey)
if !ok {
return errors.New("ECDHE RSA requires a RSA server public key")
}
if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, digest, sig); err != nil {
return err
}
default:
return errors.New("unknown ECDHE signature algorithm")
}
return nil
}
// ecdheRSAKeyAgreement implements a TLS key agreement where the server
// generates a ephemeral EC public/private key pair and signs it. The
// pre-master secret is then calculated using ECDH. The signature may
// either be ECDSA or RSA.
type ecdheKeyAgreement struct {
auth keyAgreementAuthentication
privateKey []byte
curve elliptic.Curve
x, y *big.Int
}
func maybeCorruptECDSAValue(n *big.Int, typeOfCorruption BadValue, limit *big.Int) *big.Int {
switch typeOfCorruption {
case BadValueNone:
return n
case BadValueNegative:
return new(big.Int).Neg(n)
case BadValueZero:
return big.NewInt(0)
case BadValueLimit:
return limit
case BadValueLarge:
bad := new(big.Int).Set(limit)
return bad.Lsh(bad, 20)
default:
panic("unknown BadValue type")
}
}
func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
var curveid CurveID
preferredCurves := config.curvePreferences()
NextCandidate:
for _, candidate := range preferredCurves {
for _, c := range clientHello.supportedCurves {
if candidate == c {
curveid = c
break NextCandidate
}
}
}
if curveid == 0 {
return nil, errors.New("tls: no supported elliptic curves offered")
}
var ok bool
if ka.curve, ok = curveForCurveID(curveid); !ok {
return nil, errors.New("tls: preferredCurves includes unsupported curve")
}
var x, y *big.Int
var err error
ka.privateKey, x, y, err = elliptic.GenerateKey(ka.curve, config.rand())
if err != nil {
return nil, err
}
ecdhePublic := elliptic.Marshal(ka.curve, x, y)
// http://tools.ietf.org/html/rfc4492#section-5.4
serverECDHParams := make([]byte, 1+2+1+len(ecdhePublic))
serverECDHParams[0] = 3 // named curve
serverECDHParams[1] = byte(curveid >> 8)
serverECDHParams[2] = byte(curveid)
if config.Bugs.InvalidSKXCurve {
serverECDHParams[2] ^= 0xff
}
serverECDHParams[3] = byte(len(ecdhePublic))
copy(serverECDHParams[4:], ecdhePublic)
return ka.auth.signParameters(config, cert, clientHello, hello, serverECDHParams)
}
func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 {
return nil, errClientKeyExchange
}
x, y := elliptic.Unmarshal(ka.curve, ckx.ciphertext[1:])
if x == nil {
return nil, errClientKeyExchange
}
x, _ = ka.curve.ScalarMult(x, y, ka.privateKey)
preMasterSecret := make([]byte, (ka.curve.Params().BitSize+7)>>3)
xBytes := x.Bytes()
copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
return preMasterSecret, nil
}
func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
if len(skx.key) < 4 {
return errServerKeyExchange
}
if skx.key[0] != 3 { // named curve
return errors.New("tls: server selected unsupported curve")
}
curveid := CurveID(skx.key[1])<<8 | CurveID(skx.key[2])
var ok bool
if ka.curve, ok = curveForCurveID(curveid); !ok {
return errors.New("tls: server selected unsupported curve")
}
publicLen := int(skx.key[3])
if publicLen+4 > len(skx.key) {
return errServerKeyExchange
}
ka.x, ka.y = elliptic.Unmarshal(ka.curve, skx.key[4:4+publicLen])
if ka.x == nil {
return errServerKeyExchange
}
serverECDHParams := skx.key[:4+publicLen]
sig := skx.key[4+publicLen:]
return ka.auth.verifyParameters(config, clientHello, serverHello, cert, serverECDHParams, sig)
}
func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
if ka.curve == nil {
return nil, nil, errors.New("missing ServerKeyExchange message")
}
priv, mx, my, err := elliptic.GenerateKey(ka.curve, config.rand())
if err != nil {
return nil, nil, err
}
x, _ := ka.curve.ScalarMult(ka.x, ka.y, priv)
preMasterSecret := make([]byte, (ka.curve.Params().BitSize+7)>>3)
xBytes := x.Bytes()
copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes)
serialized := elliptic.Marshal(ka.curve, mx, my)
ckx := new(clientKeyExchangeMsg)
ckx.ciphertext = make([]byte, 1+len(serialized))
ckx.ciphertext[0] = byte(len(serialized))
copy(ckx.ciphertext[1:], serialized)
return preMasterSecret, ckx, nil
}
// dheRSAKeyAgreement implements a TLS key agreement where the server generates
// an ephemeral Diffie-Hellman public/private key pair and signs it. The
// pre-master secret is then calculated using Diffie-Hellman.
type dheKeyAgreement struct {
auth keyAgreementAuthentication
p, g *big.Int
yTheirs *big.Int
xOurs *big.Int
}
func (ka *dheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
// 2048-bit MODP Group with 256-bit Prime Order Subgroup (RFC
// 5114, Section 2.3)
ka.p, _ = new(big.Int).SetString("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597", 16)
ka.g, _ = new(big.Int).SetString("3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659", 16)
q, _ := new(big.Int).SetString("8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F5FBD3", 16)
var err error
ka.xOurs, err = rand.Int(config.rand(), q)
if err != nil {
return nil, err
}
yOurs := new(big.Int).Exp(ka.g, ka.xOurs, ka.p)
// http://tools.ietf.org/html/rfc5246#section-7.4.3
pBytes := ka.p.Bytes()
gBytes := ka.g.Bytes()
yBytes := yOurs.Bytes()
serverDHParams := make([]byte, 0, 2+len(pBytes)+2+len(gBytes)+2+len(yBytes))
serverDHParams = append(serverDHParams, byte(len(pBytes)>>8), byte(len(pBytes)))
serverDHParams = append(serverDHParams, pBytes...)
serverDHParams = append(serverDHParams, byte(len(gBytes)>>8), byte(len(gBytes)))
serverDHParams = append(serverDHParams, gBytes...)
serverDHParams = append(serverDHParams, byte(len(yBytes)>>8), byte(len(yBytes)))
serverDHParams = append(serverDHParams, yBytes...)
return ka.auth.signParameters(config, cert, clientHello, hello, serverDHParams)
}
func (ka *dheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
if len(ckx.ciphertext) < 2 {
return nil, errClientKeyExchange
}
yLen := (int(ckx.ciphertext[0]) << 8) | int(ckx.ciphertext[1])
if yLen != len(ckx.ciphertext)-2 {
return nil, errClientKeyExchange
}
yTheirs := new(big.Int).SetBytes(ckx.ciphertext[2:])
if yTheirs.Sign() <= 0 || yTheirs.Cmp(ka.p) >= 0 {
return nil, errClientKeyExchange
}
return new(big.Int).Exp(yTheirs, ka.xOurs, ka.p).Bytes(), nil
}
func (ka *dheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
// Read dh_p
k := skx.key
if len(k) < 2 {
return errServerKeyExchange
}
pLen := (int(k[0]) << 8) | int(k[1])
k = k[2:]
if len(k) < pLen {
return errServerKeyExchange
}
ka.p = new(big.Int).SetBytes(k[:pLen])
k = k[pLen:]
// Read dh_g
if len(k) < 2 {
return errServerKeyExchange
}
gLen := (int(k[0]) << 8) | int(k[1])
k = k[2:]
if len(k) < gLen {
return errServerKeyExchange
}
ka.g = new(big.Int).SetBytes(k[:gLen])
k = k[gLen:]
// Read dh_Ys
if len(k) < 2 {
return errServerKeyExchange
}
yLen := (int(k[0]) << 8) | int(k[1])
k = k[2:]
if len(k) < yLen {
return errServerKeyExchange
}
ka.yTheirs = new(big.Int).SetBytes(k[:yLen])
k = k[yLen:]
if ka.yTheirs.Sign() <= 0 || ka.yTheirs.Cmp(ka.p) >= 0 {
return errServerKeyExchange
}
sig := k
serverDHParams := skx.key[:len(skx.key)-len(sig)]
return ka.auth.verifyParameters(config, clientHello, serverHello, cert, serverDHParams, sig)
}
func (ka *dheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
if ka.p == nil || ka.g == nil || ka.yTheirs == nil {
return nil, nil, errors.New("missing ServerKeyExchange message")
}
xOurs, err := rand.Int(config.rand(), ka.p)
if err != nil {
return nil, nil, err
}
preMasterSecret := new(big.Int).Exp(ka.yTheirs, xOurs, ka.p).Bytes()
yOurs := new(big.Int).Exp(ka.g, xOurs, ka.p)
yBytes := yOurs.Bytes()
ckx := new(clientKeyExchangeMsg)
ckx.ciphertext = make([]byte, 2+len(yBytes))
ckx.ciphertext[0] = byte(len(yBytes) >> 8)
ckx.ciphertext[1] = byte(len(yBytes))
copy(ckx.ciphertext[2:], yBytes)
return preMasterSecret, ckx, nil
}
// nilKeyAgreement is a fake key agreement used to implement the plain PSK key
// exchange.
type nilKeyAgreement struct{}
func (ka *nilKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
return nil, nil
}
func (ka *nilKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
if len(ckx.ciphertext) != 0 {
return nil, errClientKeyExchange
}
// Although in plain PSK, otherSecret is all zeros, the base key
// agreement does not access to the length of the pre-shared
// key. pskKeyAgreement instead interprets nil to mean to use all zeros
// of the appropriate length.
return nil, nil
}
func (ka *nilKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
if len(skx.key) != 0 {
return errServerKeyExchange
}
return nil
}
func (ka *nilKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
// Although in plain PSK, otherSecret is all zeros, the base key
// agreement does not access to the length of the pre-shared
// key. pskKeyAgreement instead interprets nil to mean to use all zeros
// of the appropriate length.
return nil, &clientKeyExchangeMsg{}, nil
}
// makePSKPremaster formats a PSK pre-master secret based on otherSecret from
// the base key exchange and psk.
func makePSKPremaster(otherSecret, psk []byte) []byte {
out := make([]byte, 0, 2+len(otherSecret)+2+len(psk))
out = append(out, byte(len(otherSecret)>>8), byte(len(otherSecret)))
out = append(out, otherSecret...)
out = append(out, byte(len(psk)>>8), byte(len(psk)))
out = append(out, psk...)
return out
}
// pskKeyAgreement implements the PSK key agreement.
type pskKeyAgreement struct {
base keyAgreement
identityHint string
}
func (ka *pskKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) {
// Assemble the identity hint.
bytes := make([]byte, 2+len(config.PreSharedKeyIdentity))
bytes[0] = byte(len(config.PreSharedKeyIdentity) >> 8)
bytes[1] = byte(len(config.PreSharedKeyIdentity))
copy(bytes[2:], []byte(config.PreSharedKeyIdentity))
// If there is one, append the base key agreement's
// ServerKeyExchange.
baseSkx, err := ka.base.generateServerKeyExchange(config, cert, clientHello, hello)
if err != nil {
return nil, err
}
if baseSkx != nil {
bytes = append(bytes, baseSkx.key...)
} else if config.PreSharedKeyIdentity == "" {
// ServerKeyExchange is optional if the identity hint is empty
// and there would otherwise be no ServerKeyExchange.
return nil, nil
}
skx := new(serverKeyExchangeMsg)
skx.key = bytes
return skx, nil
}
func (ka *pskKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) {
// First, process the PSK identity.
if len(ckx.ciphertext) < 2 {
return nil, errClientKeyExchange
}
identityLen := (int(ckx.ciphertext[0]) << 8) | int(ckx.ciphertext[1])
if 2+identityLen > len(ckx.ciphertext) {
return nil, errClientKeyExchange
}
identity := string(ckx.ciphertext[2 : 2+identityLen])
if identity != config.PreSharedKeyIdentity {
return nil, errors.New("tls: unexpected identity")
}
if config.PreSharedKey == nil {
return nil, errors.New("tls: pre-shared key not configured")
}
// Process the remainder of the ClientKeyExchange to compute the base
// pre-master secret.
newCkx := new(clientKeyExchangeMsg)
newCkx.ciphertext = ckx.ciphertext[2+identityLen:]
otherSecret, err := ka.base.processClientKeyExchange(config, cert, newCkx, version)
if err != nil {
return nil, err
}
if otherSecret == nil {
// Special-case for the plain PSK key exchanges.
otherSecret = make([]byte, len(config.PreSharedKey))
}
return makePSKPremaster(otherSecret, config.PreSharedKey), nil
}
func (ka *pskKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error {
if len(skx.key) < 2 {
return errServerKeyExchange
}
identityLen := (int(skx.key[0]) << 8) | int(skx.key[1])
if 2+identityLen > len(skx.key) {
return errServerKeyExchange
}
ka.identityHint = string(skx.key[2 : 2+identityLen])
// Process the remainder of the ServerKeyExchange.
newSkx := new(serverKeyExchangeMsg)
newSkx.key = skx.key[2+identityLen:]
return ka.base.processServerKeyExchange(config, clientHello, serverHello, cert, newSkx)
}
func (ka *pskKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) {
// The server only sends an identity hint but, for purposes of
// test code, the server always sends the hint and it is
// required to match.
if ka.identityHint != config.PreSharedKeyIdentity {
return nil, nil, errors.New("tls: unexpected identity")
}
// Serialize the identity.
bytes := make([]byte, 2+len(config.PreSharedKeyIdentity))
bytes[0] = byte(len(config.PreSharedKeyIdentity) >> 8)
bytes[1] = byte(len(config.PreSharedKeyIdentity))
copy(bytes[2:], []byte(config.PreSharedKeyIdentity))
// Append the base key exchange's ClientKeyExchange.
otherSecret, baseCkx, err := ka.base.generateClientKeyExchange(config, clientHello, cert)
if err != nil {
return nil, nil, err
}
ckx := new(clientKeyExchangeMsg)
ckx.ciphertext = append(bytes, baseCkx.ciphertext...)
if config.PreSharedKey == nil {
return nil, nil, errors.New("tls: pre-shared key not configured")
}
if otherSecret == nil {
otherSecret = make([]byte, len(config.PreSharedKey))
}
return makePSKPremaster(otherSecret, config.PreSharedKey), ckx, nil
}
|
CTSRD-SOAAP/chromium-42.0.2311.135
|
third_party/boringssl/src/ssl/test/runner/key_agreement.go
|
GO
|
bsd-3-clause
| 26,755
|
//*****************************************************************************
//
// fontcm24b.c - Font definition for the 24 point Cm bold font.
//
// Copyright (c) 2008-2010 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 6288 of the Stellaris Graphics Library.
//
//*****************************************************************************
//*****************************************************************************
//
// This file is generated by ftrasterize; DO NOT EDIT BY HAND!
//
//*****************************************************************************
#include "grlib.h"
//*****************************************************************************
//
// Details of this font:
// Style: cm
// Size: 24 point
// Bold: yes
// Italic: no
// Memory usage: 3044 bytes
//
//*****************************************************************************
//*****************************************************************************
//
// The compressed data for the 24 point Cm bold font.
//
//*****************************************************************************
static const unsigned char g_pucCm24bData[2841] =
{
5, 10, 0, 31, 32, 22, 6, 114, 52, 36, 36, 36,
36, 50, 66, 66, 66, 66, 66, 66, 162, 52, 36, 50,
240, 240, 144, 24, 12, 240, 162, 66, 52, 36, 36, 36,
51, 51, 81, 81, 81, 81, 65, 81, 81, 81, 65, 81,
0, 21, 64, 50, 19, 0, 5, 97, 65, 209, 65, 194,
65, 194, 50, 193, 66, 193, 65, 194, 65, 194, 50, 111,
2, 129, 65, 194, 50, 194, 50, 193, 65, 143, 2, 98,
50, 193, 66, 193, 65, 194, 65, 194, 50, 193, 66, 193,
65, 209, 65, 240, 224, 47, 12, 65, 177, 150, 82, 17,
34, 50, 33, 50, 34, 33, 35, 34, 33, 35, 35, 17,
34, 53, 134, 104, 102, 113, 20, 35, 17, 35, 35, 17,
50, 35, 17, 50, 34, 33, 49, 66, 17, 34, 86, 129,
177, 0, 6, 112, 62, 20, 35, 161, 82, 34, 114, 82,
50, 67, 83, 49, 23, 83, 49, 82, 99, 49, 81, 115,
49, 66, 115, 49, 50, 146, 49, 34, 162, 33, 50, 194,
50, 240, 34, 53, 162, 50, 49, 130, 51, 49, 114, 67,
49, 114, 67, 49, 98, 83, 49, 82, 99, 49, 82, 114,
33, 82, 148, 0, 12, 112, 46, 19, 240, 147, 227, 33,
210, 49, 195, 49, 195, 49, 195, 33, 211, 33, 213, 70,
83, 113, 132, 97, 117, 81, 114, 20, 50, 99, 36, 33,
115, 51, 17, 131, 68, 131, 83, 65, 51, 69, 49, 85,
68, 0, 14, 96, 13, 6, 210, 52, 36, 51, 81, 81,
65, 81, 65, 0, 11, 28, 8, 81, 98, 82, 83, 82,
83, 83, 82, 83, 83, 83, 83, 83, 83, 83, 83, 83,
98, 99, 83, 98, 99, 98, 114, 113, 32, 28, 8, 1,
114, 114, 99, 98, 99, 83, 98, 99, 83, 83, 83, 83,
83, 83, 83, 83, 82, 83, 83, 82, 83, 82, 82, 97,
112, 27, 11, 51, 131, 131, 82, 19, 18, 35, 17, 19,
55, 85, 67, 17, 19, 34, 33, 34, 33, 35, 33, 83,
131, 0, 18, 64, 38, 17, 0, 9, 49, 240, 17, 240,
17, 240, 17, 240, 17, 240, 17, 240, 17, 240, 17, 159,
145, 240, 17, 240, 17, 240, 17, 240, 17, 240, 17, 240,
17, 240, 17, 0, 9, 80, 14, 6, 0, 11, 50, 52,
36, 51, 81, 81, 65, 81, 65, 160, 9, 8, 0, 13,
6, 38, 0, 10, 32, 11, 6, 0, 11, 50, 52, 36,
50, 240, 240, 144, 28, 11, 129, 146, 145, 161, 146, 146,
145, 146, 146, 145, 146, 146, 145, 146, 146, 145, 146, 146,
145, 146, 146, 145, 161, 146, 145, 160, 37, 12, 240, 240,
148, 114, 35, 66, 66, 66, 67, 35, 67, 35, 67, 35,
67, 35, 67, 35, 67, 35, 67, 35, 67, 35, 67, 35,
67, 50, 66, 82, 34, 116, 0, 9, 80, 23, 11, 240,
240, 114, 86, 131, 131, 131, 131, 131, 131, 131, 131, 131,
131, 131, 131, 131, 89, 0, 8, 64, 30, 11, 240, 240,
85, 81, 51, 51, 51, 35, 51, 35, 51, 131, 130, 131,
130, 130, 130, 49, 81, 65, 65, 81, 56, 41, 40, 0,
8, 80, 32, 12, 240, 240, 148, 98, 51, 67, 35, 67,
35, 67, 35, 147, 131, 115, 195, 148, 50, 52, 36, 36,
36, 36, 35, 51, 66, 36, 85, 0, 9, 80, 28, 13,
0, 5, 98, 178, 163, 148, 148, 129, 19, 113, 35, 113,
35, 97, 51, 81, 67, 81, 67, 75, 131, 163, 163, 135,
0, 10, 31, 11, 240, 240, 65, 81, 71, 70, 84, 113,
161, 161, 20, 82, 50, 65, 66, 147, 131, 35, 51, 35,
51, 35, 51, 49, 51, 84, 0, 8, 112, 35, 12, 240,
240, 165, 98, 49, 82, 50, 66, 66, 66, 147, 147, 20,
68, 35, 51, 67, 35, 67, 35, 67, 35, 67, 50, 67,
50, 66, 82, 50, 100, 0, 9, 80, 25, 12, 240, 240,
106, 41, 56, 65, 82, 65, 81, 161, 162, 161, 162, 162,
162, 147, 147, 147, 147, 147, 0, 9, 112, 34, 13, 240,
240, 197, 114, 50, 82, 82, 66, 82, 67, 66, 69, 18,
102, 134, 104, 67, 22, 35, 68, 35, 83, 35, 83, 35,
82, 67, 51, 101, 0, 10, 48, 35, 12, 240, 240, 148,
99, 35, 66, 66, 51, 67, 35, 67, 35, 67, 35, 67,
35, 67, 51, 36, 68, 19, 147, 146, 66, 66, 66, 65,
81, 50, 116, 0, 9, 96, 16, 6, 0, 6, 18, 52,
36, 50, 240, 114, 52, 36, 50, 240, 240, 144, 19, 6,
0, 6, 18, 52, 36, 50, 240, 114, 52, 36, 51, 81,
81, 65, 81, 65, 160, 22, 6, 240, 240, 114, 52, 36,
50, 240, 18, 66, 66, 66, 66, 66, 52, 36, 36, 36,
36, 50, 144, 13, 18, 0, 22, 79, 1, 0, 9, 47,
1, 0, 20, 64, 27, 11, 0, 8, 83, 116, 116, 131,
240, 240, 17, 161, 161, 161, 145, 146, 131, 115, 51, 35,
51, 35, 51, 35, 65, 85, 240, 26, 11, 240, 149, 66,
67, 35, 51, 35, 51, 131, 115, 130, 130, 145, 161, 161,
161, 240, 83, 116, 116, 131, 0, 8, 112, 59, 18, 240,
240, 182, 162, 98, 113, 146, 82, 52, 50, 65, 35, 34,
49, 49, 50, 67, 33, 33, 35, 67, 33, 33, 35, 67,
33, 33, 35, 67, 33, 33, 35, 67, 33, 33, 35, 67,
33, 34, 35, 51, 33, 49, 35, 36, 17, 66, 52, 20,
82, 240, 34, 115, 136, 0, 14, 16, 36, 18, 240, 240,
210, 240, 18, 240, 19, 228, 228, 229, 193, 35, 193, 35,
178, 36, 161, 67, 161, 67, 154, 129, 99, 129, 99, 114,
100, 97, 131, 69, 71, 0, 13, 96, 38, 17, 240, 240,
76, 115, 83, 99, 99, 83, 99, 83, 99, 83, 99, 83,
98, 99, 83, 105, 131, 83, 99, 99, 83, 100, 67, 100,
67, 100, 67, 99, 83, 84, 60, 0, 13, 48, 35, 17,
240, 240, 165, 49, 99, 68, 68, 99, 52, 130, 51, 146,
36, 161, 36, 212, 212, 212, 212, 212, 161, 51, 161, 52,
129, 84, 113, 100, 66, 165, 0, 13, 64, 39, 19, 240,
240, 140, 147, 84, 115, 115, 99, 116, 83, 131, 83, 132,
67, 132, 67, 132, 67, 132, 67, 132, 67, 132, 67, 132,
67, 131, 83, 116, 83, 115, 99, 84, 92, 0, 15, 16,
41, 16, 240, 240, 44, 99, 82, 99, 98, 83, 98, 83,
113, 83, 49, 49, 83, 49, 147, 34, 151, 147, 34, 147,
49, 50, 67, 49, 49, 83, 113, 83, 113, 83, 98, 83,
83, 61, 0, 12, 48, 34, 15, 240, 252, 83, 82, 83,
97, 83, 97, 83, 98, 67, 49, 49, 67, 49, 131, 34,
135, 131, 34, 131, 49, 131, 49, 131, 195, 195, 195, 168,
0, 12, 16, 37, 19, 240, 240, 230, 33, 131, 68, 100,
99, 84, 130, 83, 161, 68, 161, 68, 244, 244, 244, 244,
88, 36, 131, 83, 131, 99, 115, 100, 99, 131, 68, 165,
49, 0, 14, 96, 40, 18, 240, 240, 103, 39, 67, 99,
99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
108, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 71, 39, 0, 13, 96, 22, 9, 240, 55,
67, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 71, 0, 7, 27, 13, 240, 232, 131, 163,
163, 163, 163, 163, 163, 163, 163, 163, 163, 82, 51, 68,
35, 68, 35, 82, 35, 117, 0, 10, 64, 40, 18, 240,
240, 103, 69, 67, 114, 99, 98, 115, 82, 131, 66, 147,
50, 163, 34, 179, 19, 184, 164, 20, 147, 51, 147, 52,
131, 67, 131, 68, 115, 84, 99, 99, 71, 39, 0, 13,
96, 29, 14, 240, 216, 131, 179, 179, 179, 179, 179, 179,
179, 179, 179, 97, 67, 97, 67, 82, 67, 82, 67, 81,
83, 51, 59, 0, 10, 112, 66, 23, 0, 5, 102, 150,
68, 148, 100, 129, 19, 97, 19, 113, 19, 97, 19, 113,
19, 97, 34, 97, 35, 97, 35, 81, 35, 97, 35, 81,
35, 97, 51, 49, 51, 97, 51, 49, 51, 97, 51, 33,
67, 97, 67, 17, 67, 97, 67, 17, 67, 97, 83, 83,
97, 83, 83, 97, 82, 99, 69, 65, 71, 0, 17, 64,
48, 18, 240, 240, 101, 101, 68, 113, 101, 97, 97, 19,
97, 97, 35, 81, 97, 36, 65, 97, 52, 49, 97, 67,
49, 97, 68, 33, 97, 84, 17, 97, 99, 17, 97, 101,
97, 116, 97, 131, 97, 131, 97, 146, 69, 129, 0, 14,
39, 18, 240, 240, 182, 163, 67, 115, 99, 84, 100, 67,
131, 52, 132, 36, 132, 36, 132, 36, 132, 36, 132, 36,
132, 36, 132, 51, 131, 68, 100, 83, 99, 115, 67, 166,
0, 14, 48, 31, 16, 240, 240, 43, 115, 68, 83, 84,
67, 84, 67, 84, 67, 84, 67, 83, 83, 68, 89, 115,
211, 211, 211, 211, 211, 211, 183, 0, 13, 16, 48, 18,
240, 240, 182, 163, 67, 115, 99, 84, 100, 67, 131, 52,
132, 36, 132, 36, 132, 36, 132, 36, 132, 36, 132, 36,
132, 51, 131, 68, 35, 20, 83, 17, 33, 19, 116, 50,
183, 49, 194, 49, 198, 198, 212, 227, 240, 112, 41, 20,
240, 240, 171, 179, 83, 147, 99, 131, 100, 115, 100, 115,
100, 115, 99, 131, 83, 153, 179, 68, 147, 83, 147, 84,
131, 84, 131, 84, 131, 84, 49, 67, 85, 33, 40, 69,
0, 15, 48, 36, 14, 240, 240, 21, 33, 67, 67, 66,
98, 51, 98, 51, 113, 52, 97, 55, 137, 105, 119, 165,
33, 131, 34, 115, 34, 115, 35, 98, 52, 67, 50, 37,
0, 11, 16, 36, 17, 240, 240, 93, 66, 51, 50, 65,
67, 65, 50, 67, 66, 34, 67, 66, 34, 67, 81, 33,
83, 81, 131, 227, 227, 227, 227, 227, 227, 227, 227, 185,
0, 13, 48, 40, 18, 240, 240, 103, 69, 67, 129, 99,
129, 99, 129, 99, 129, 99, 129, 99, 129, 99, 129, 99,
129, 99, 129, 99, 129, 99, 129, 99, 129, 99, 129, 115,
97, 147, 65, 197, 0, 14, 48, 37, 19, 240, 240, 135,
70, 67, 130, 100, 113, 116, 98, 131, 97, 148, 81, 148,
66, 163, 65, 180, 49, 195, 33, 212, 17, 214, 228, 244,
244, 240, 18, 240, 34, 0, 15, 64, 57, 26, 0, 6,
72, 23, 53, 68, 83, 113, 115, 84, 97, 116, 83, 82,
116, 83, 81, 147, 69, 65, 148, 49, 19, 50, 148, 49,
19, 49, 179, 34, 20, 33, 180, 17, 51, 33, 180, 17,
51, 17, 213, 53, 212, 84, 212, 83, 243, 83, 242, 114,
242, 113, 0, 20, 80, 37, 18, 240, 240, 104, 22, 84,
82, 132, 50, 148, 49, 180, 18, 195, 17, 213, 228, 228,
229, 209, 19, 193, 36, 162, 51, 161, 68, 130, 84, 113,
100, 70, 55, 0, 13, 96, 38, 19, 240, 240, 136, 69,
68, 114, 116, 97, 132, 82, 148, 65, 164, 50, 180, 33,
196, 17, 229, 243, 240, 19, 240, 19, 240, 19, 240, 19,
240, 19, 240, 19, 231, 0, 15, 16, 34, 14, 240, 220,
35, 84, 34, 84, 50, 84, 49, 84, 65, 83, 164, 163,
164, 163, 164, 65, 83, 81, 68, 81, 52, 97, 51, 98,
36, 83, 44, 0, 10, 96, 27, 5, 83, 33, 65, 65,
65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
65, 65, 65, 65, 65, 65, 65, 67, 32, 22, 12, 240,
177, 81, 65, 81, 65, 81, 81, 81, 83, 51, 52, 36,
36, 36, 50, 66, 0, 22, 112, 27, 5, 83, 65, 65,
65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
65, 65, 65, 65, 65, 65, 65, 65, 35, 32, 12, 8,
240, 65, 99, 66, 18, 33, 65, 0, 19, 32, 9, 6,
210, 52, 36, 50, 0, 14, 80, 13, 6, 225, 65, 65,
81, 83, 52, 36, 50, 0, 11, 80, 25, 13, 0, 13,
37, 114, 35, 98, 51, 163, 118, 83, 35, 67, 51, 67,
51, 67, 51, 67, 36, 99, 36, 0, 10, 34, 14, 240,
213, 179, 179, 179, 179, 179, 179, 19, 116, 35, 83, 66,
83, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 66,
84, 35, 82, 35, 0, 11, 16, 23, 11, 0, 11, 53,
67, 35, 50, 51, 35, 65, 51, 131, 131, 131, 146, 81,
51, 49, 100, 0, 8, 96, 34, 14, 240, 240, 68, 179,
179, 179, 179, 179, 119, 83, 36, 82, 67, 67, 67, 67,
67, 67, 67, 67, 67, 67, 67, 82, 67, 83, 36, 115,
21, 0, 10, 96, 24, 12, 0, 12, 53, 83, 35, 66,
67, 35, 67, 35, 67, 42, 35, 147, 162, 97, 51, 50,
101, 0, 9, 64, 26, 11, 240, 180, 98, 19, 67, 19,
67, 33, 83, 131, 118, 99, 131, 131, 131, 131, 131, 131,
131, 131, 102, 0, 8, 112, 33, 13, 0, 13, 37, 19,
50, 50, 18, 35, 51, 67, 51, 67, 51, 82, 50, 102,
113, 178, 200, 104, 50, 99, 34, 114, 34, 99, 50, 67,
86, 240, 48, 35, 16, 240, 240, 37, 211, 211, 211, 211,
211, 211, 36, 115, 17, 35, 100, 51, 99, 67, 99, 67,
99, 67, 99, 67, 99, 67, 99, 67, 99, 67, 78, 0,
12, 32, 22, 8, 240, 50, 84, 68, 82, 240, 85, 83,
83, 83, 83, 83, 83, 83, 83, 83, 54, 0, 6, 32,
28, 10, 240, 147, 116, 100, 99, 240, 181, 115, 115, 115,
115, 115, 115, 115, 115, 115, 115, 115, 35, 35, 35, 35,
35, 19, 69, 224, 31, 15, 240, 245, 195, 195, 195, 195,
195, 195, 37, 83, 50, 115, 34, 131, 18, 150, 150, 147,
19, 131, 35, 115, 35, 115, 51, 77, 0, 11, 64, 22,
9, 240, 53, 99, 99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 71, 0, 7, 39, 22, 0,
22, 5, 36, 36, 117, 36, 35, 100, 52, 35, 99, 67,
51, 99, 67, 51, 99, 67, 51, 99, 67, 51, 99, 67,
51, 99, 67, 51, 99, 67, 51, 77, 22, 0, 16, 96,
28, 16, 0, 16, 5, 36, 117, 35, 100, 51, 99, 67,
99, 67, 99, 67, 99, 67, 99, 67, 99, 67, 99, 67,
78, 0, 12, 32, 27, 12, 0, 12, 52, 99, 35, 66,
66, 51, 67, 35, 67, 35, 67, 35, 67, 35, 67, 50,
66, 67, 35, 100, 0, 9, 80, 33, 14, 0, 14, 5,
20, 100, 35, 83, 67, 67, 67, 67, 67, 67, 67, 67,
67, 67, 67, 67, 66, 84, 35, 83, 19, 115, 179, 179,
179, 150, 240, 112, 34, 15, 0, 15, 52, 34, 98, 49,
18, 83, 67, 67, 83, 67, 83, 67, 83, 67, 83, 67,
83, 83, 67, 83, 52, 116, 19, 195, 195, 195, 195, 167,
240, 32, 21, 12, 0, 12, 5, 19, 84, 19, 67, 35,
67, 147, 147, 147, 147, 147, 147, 119, 0, 9, 80, 22,
10, 0, 10, 37, 65, 50, 50, 65, 51, 118, 86, 116,
33, 82, 34, 66, 35, 49, 54, 0, 8, 27, 10, 240,
240, 65, 145, 130, 130, 115, 88, 67, 115, 115, 115, 115,
115, 33, 67, 33, 67, 33, 67, 33, 84, 0, 7, 112,
29, 16, 0, 16, 5, 37, 99, 67, 99, 67, 99, 67,
99, 67, 99, 67, 99, 67, 99, 67, 99, 67, 99, 52,
117, 21, 0, 12, 32, 24, 13, 0, 13, 5, 36, 51,
65, 98, 65, 99, 34, 99, 33, 130, 33, 133, 132, 163,
162, 193, 0, 10, 80, 35, 19, 0, 19, 11, 36, 67,
50, 65, 99, 50, 65, 115, 35, 34, 115, 20, 33, 131,
17, 18, 33, 148, 21, 148, 35, 163, 51, 178, 51, 178,
65, 0, 15, 16, 26, 14, 0, 14, 21, 21, 67, 50,
115, 18, 146, 17, 164, 179, 179, 161, 19, 130, 35, 113,
66, 69, 37, 0, 10, 96, 31, 14, 0, 14, 6, 36,
67, 65, 99, 65, 115, 33, 131, 33, 131, 33, 148, 164,
179, 178, 194, 193, 145, 49, 131, 18, 131, 17, 163, 240,
144, 25, 11, 0, 11, 9, 34, 67, 34, 51, 49, 51,
131, 115, 115, 49, 67, 49, 51, 50, 35, 66, 41, 0,
8, 64, 8, 14, 0, 21, 12, 0, 21, 32, 9, 26,
0, 39, 15, 9, 0, 39, 32, 15, 9, 162, 34, 35,
19, 35, 19, 34, 34, 49, 49, 0, 21, 112, 11, 10,
240, 100, 33, 54, 49, 51, 0, 25, 48,
};
//*****************************************************************************
//
// The font definition for the 24 point Cm bold font.
//
//*****************************************************************************
const tFont g_sFontCm24b =
{
//
// The format of the font.
//
FONT_FMT_PIXEL_RLE,
//
// The maximum width of the font.
//
23,
//
// The height of the font.
//
25,
//
// The baseline of the font.
//
19,
//
// The offset to each character in the font.
//
{
0, 5, 27, 51, 101, 148, 210, 256,
269, 297, 325, 352, 390, 404, 413, 424,
452, 489, 512, 542, 574, 602, 633, 668,
693, 727, 762, 778, 797, 819, 832, 859,
885, 944, 980, 1018, 1053, 1092, 1133, 1167,
1204, 1244, 1266, 1293, 1333, 1362, 1428, 1476,
1515, 1546, 1594, 1635, 1671, 1707, 1747, 1784,
1841, 1878, 1916, 1950, 1977, 1999, 2026, 2038,
2047, 2060, 2085, 2119, 2142, 2176, 2200, 2226,
2259, 2294, 2316, 2344, 2375, 2397, 2436, 2464,
2491, 2524, 2558, 2579, 2601, 2628, 2657, 2681,
2716, 2742, 2773, 2798, 2806, 2815, 2830,
},
//
// A pointer to the actual font data
//
g_pucCm24bData
};
|
vastsoun/bbmc-starterware
|
grlib/fonts/fontcm24b.c
|
C
|
bsd-3-clause
| 18,429
|
package muduorpc
import (
"bufio"
"fmt"
"io"
"net/rpc"
"strings"
"code.google.com/p/goprotobuf/proto"
)
type ClientCodec struct {
conn io.ReadWriteCloser
r io.Reader
payload []byte
}
func (c *ClientCodec) WriteRequest(r *rpc.Request, body interface{}) error {
msg := new(RpcMessage)
msg.Type = MessageType_REQUEST.Enum()
msg.Id = &r.Seq
last_dot := strings.LastIndex(r.ServiceMethod, ".")
if last_dot < 0 {
panic(fmt.Sprintf("Invalid ServiceMethod '%s'", r.ServiceMethod))
}
service := r.ServiceMethod[:last_dot]
msg.Service = &service
method := r.ServiceMethod[last_dot+1:]
msg.Method = &method
pb, ok := body.(proto.Message)
if !ok {
return fmt.Errorf("not a protobuf Message")
}
b, err := proto.Marshal(pb)
if err != nil {
return err
}
msg.Request = b
return Send(c.conn, msg)
}
func (c *ClientCodec) ReadResponseHeader(r *rpc.Response) (err error) {
if c.payload != nil {
panic("payload is not nil")
}
var msg *RpcMessage
msg, err = Decode(c.r)
if err != nil {
return
}
if *msg.Type != *MessageType_RESPONSE.Enum() {
err = fmt.Errorf("Wrong message type.")
return
}
r.Seq = *msg.Id
c.payload = msg.Response
return nil
}
// FIXME: merge dup code with ServerCodec.ReadRequestBody()
func (c *ClientCodec) ReadResponseBody(body interface{}) (err error) {
if c.payload == nil {
panic("payload is nil")
}
msg, ok := body.(proto.Message)
if !ok {
return fmt.Errorf("body is not a protobuf Message")
}
err = proto.Unmarshal(c.payload, msg)
if err != nil {
return
}
c.payload = nil
return
}
func (c *ClientCodec) Close() error {
return c.conn.Close()
}
func NewClientCodec(conn io.ReadWriteCloser) *ClientCodec {
codec := new(ClientCodec)
codec.conn = conn
codec.r = bufio.NewReader(conn)
return codec
}
|
SuperMXC/muduo-protorpc
|
go/muduorpc/client.go
|
GO
|
bsd-3-clause
| 1,799
|
/*
* Android SDK for Matomo
*
* @link https://github.com/matomo-org/matomo-android-sdk
* @license https://github.com/matomo-org/matomo-sdk-android/blob/master/LICENSE BSD-3 Clause
*/
package org.matomo.sdk.extra;
import org.json.JSONArray;
import org.matomo.sdk.tools.CurrencyFormatter;
import java.util.HashMap;
import java.util.Map;
public class EcommerceItems {
private final Map<String, JSONArray> mItems = new HashMap<>();
/**
* Adds a product into the ecommerce order. Must be called for each product in the order.
* If the same sku is used twice, the first item is overwritten.
*/
public void addItem(Item item) {
mItems.put(item.mSku, item.toJson());
}
public static class Item {
private final String mSku;
private String mCategory;
private Integer mPrice;
private Integer mQuantity;
private String mName;
/**
* If the same sku is used twice, the first item is overwritten.
*
* @param sku Unique identifier for the product
*/
public Item(String sku) {
mSku = sku;
}
/**
* @param name Product name
*/
public Item name(String name) {
mName = name;
return this;
}
/**
* @param category Product category
*/
public Item category(String category) {
mCategory = category;
return this;
}
/**
* @param price Price of the product in cents
*/
public Item price(int price) {
mPrice = price;
return this;
}
/**
* @param quantity Quantity
*/
public Item quantity(int quantity) {
mQuantity = quantity;
return this;
}
public String getSku() {
return mSku;
}
public String getCategory() {
return mCategory;
}
public Integer getPrice() {
return mPrice;
}
public Integer getQuantity() {
return mQuantity;
}
public String getName() {
return mName;
}
protected JSONArray toJson() {
JSONArray item = new JSONArray();
item.put(mSku);
if (mName != null) item.put(mName);
if (mCategory != null) item.put(mCategory);
if (mPrice != null) item.put(CurrencyFormatter.priceString(mPrice));
if (mQuantity != null) item.put(String.valueOf(mQuantity));
return item;
}
}
/**
* Remove a product from an ecommerce order.
*
* @param sku unique identifier for the product
*/
public void remove(String sku) {
mItems.remove(sku);
}
public void remove(Item item) {
mItems.remove(item.mSku);
}
/**
* Clears all items from the ecommerce order
*/
public void clear() {
mItems.clear();
}
public String toJson() {
JSONArray jsonItems = new JSONArray();
for (JSONArray item : mItems.values()) {
jsonItems.put(item);
}
return jsonItems.toString();
}
}
|
piwik/piwik-sdk-android
|
tracker/src/main/java/org/matomo/sdk/extra/EcommerceItems.java
|
Java
|
bsd-3-clause
| 3,240
|
--+ holdcas on;
set names utf8;
create table t1 (s1 string collate utf8_en_cs);
create index i_t1_f_s1 on t1(locate('İ',s1));
insert into t1 values ('İacb');
insert into t1 values ('aİbc');
insert into t1 values ('accİ');
-- index scan
select /* +recompile */ s1 from t1 where locate('İ',s1) > 1 order by 1;
set names iso88591;
-- no index scan
select /* +recompile */ s1 from t1 where locate('İ',s1) > 1 order by 1;
-- force index scan
select /* +recompile */ s1 from t1 where locate(_utf8'İ',s1) > 1 order by 1;
drop table t1;
-- other non-binary collation in SET NAMES does not change the constant printing (only charset introducer is printed)
set names utf8 collate utf8_en_cs;
create table t1 (s1 string collate utf8_en_cs);
create index i_t1_f_s1 on t1(locate('İ',s1));
insert into t1 values ('İacb');
insert into t1 values ('aİbc');
insert into t1 values ('accİ');
-- index scan
select /* +recompile */ s1 from t1 where locate('İ',s1) > 1 order by 1;
set names iso88591;
-- no index scan
select /* +recompile */ s1 from t1 where locate('İ',s1) > 1 order by 1;
-- force index scan
select /* +recompile */ s1 from t1 where locate(_utf8'İ',s1) > 1 order by 1;
drop table t1;
set names iso88591;
commit;
--+ holdcas off;
|
CUBRID/cubrid-testcases
|
sql/_23_apricot_qa/_03_i18n/en_US/_13_issues/cases/bug_bts_7835_04_function_index.sql
|
SQL
|
bsd-3-clause
| 1,254
|
{-# LANGUAGE Rank2Types #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Choose.ST
-- Copyright : Copyright (c) , Patrick Perry <patperry@stanford.edu>
-- License : BSD3
-- Maintainer : Patrick Perry <patperry@stanford.edu>
-- Stability : experimental
--
-- Mutable combinations in the 'ST' monad.
module Data.Choose.ST (
-- * Combinations
STChoose,
runSTChoose,
-- * Overloaded mutable combination interface
module Data.Choose.MChoose
) where
import Control.Monad.ST
import Data.Choose.Base( Choose, STChoose, unsafeFreezeSTChoose )
import Data.Choose.MChoose
-- | A safe way to create and work with a mutable combination before returning
-- an immutable one for later perusal. This function avoids copying the
-- combination before returning it - it uses unsafeFreeze internally, but this
-- wrapper is a safe interface to that function.
runSTChoose :: (forall s. ST s (STChoose s)) -> Choose
runSTChoose c = runST (c >>= unsafeFreezeSTChoose)
{-# INLINE runSTChoose #-}
|
patperry/permutation
|
lib/Data/Choose/ST.hs
|
Haskell
|
bsd-3-clause
| 1,074
|
---
layout: redirect
newurl: http://pmem.io/libpmemobj-cpp/master/doxygen/make__persistent__array_8hpp.html
---
|
janekmi/janekmi.github.io
|
nvml/cpp_obj/master/cpp_html/make__persistent__array_8hpp.md
|
Markdown
|
bsd-3-clause
| 112
|
# Jovyan
The theme for the [Jupyter blog](http://blog.jupyter.org/).
## Install Instructions
1. Clone this repository into the `/content/themes/` directory in your Ghost instance.
2. Restart the Ghost instance.
3. Go to `Settings`.
4. Select the `Jovyan` theme.
|
jupyter/jupyter-blog-theme
|
README.md
|
Markdown
|
bsd-3-clause
| 265
|
<?php
require_once($basepath . "ImageManager/ImageManagerPlugin.php");
// * * * * ImageManager config
// General options
$mcImageManagerConfig['general.theme'] = "im";
$mcImageManagerConfig['general.tools'] = "createdir,upload,refresh,addfavorite,removefavorite,insert,delete,edit,preview"; // "filemanager" button if you have "filemanager.urlprefix" configured.
$mcImageManagerConfig['general.disabled_tools'] = "";
$mcImageManagerConfig['general.user_friendly_paths'] = true;
$mcImageManagerConfig['general.encrypt_paths'] = true;
$mcImageManagerConfig['general.plugins'] = "History,Favorites"; // comma seperated
$mcImageManagerConfig['general.demo'] = false;
$mcImageManagerConfig['general.debug'] = false;
$mcImageManagerConfig['general.error_log'] = "";
$mcImageManagerConfig['general.language'] = "en"; // en, sv
$mcImageManagerConfig['general.remember_last_path'] = false;
$mcImageManagerConfig['general.allow_export'] = "demo,tools,disabled_tools,debug,plugins";
$mcImageManagerConfig['general.allow_override'] = "*";
// Preview options
$mcImageManagerConfig['preview.wwwroot'] = ''; // absolute or relative from this script path, try to leave blank system figures it out.
$mcImageManagerConfig['preview.urlprefix'] = "{proto}://{host}/"; // domain name
$mcImageManagerConfig['preview.urlsuffix'] = "";
$mcImageManagerConfig['preview.allow_export'] = "urlprefix,urlsuffix";
$mcImageManagerConfig['preview.allow_override'] = "*";
// Create directory options
$mcImageManagerConfig['createdir.include_directory_pattern'] = '';
$mcImageManagerConfig['createdir.exclude_directory_pattern'] = '/[^a-z0-9_]/';
$mcImageManagerConfig['createdir.allow_override'] = "*";
// General filesystem options
$mcImageManagerConfig['filesystem'] = "Moxiecode_LocalFileImpl";
$mcImageManagerConfig['filesystem.path'] = ''; // absolute or relative from this script path, optional.
$mcImageManagerConfig['filesystem.rootpath'] = 'files'; // absolute or relative from this script path, required.
$mcImageManagerConfig['filesystem.datefmt'] = "Y-m-d H:i";
$mcImageManagerConfig['filesystem.include_directory_pattern'] = '';
$mcImageManagerConfig['filesystem.exclude_directory_pattern'] = '/^mcith$/i';
$mcImageManagerConfig['filesystem.invalid_directory_name_msg'] = "";
$mcImageManagerConfig['filesystem.include_file_pattern'] = '';
$mcImageManagerConfig['filesystem.exclude_file_pattern'] = '/([^a-zA-Z0-9_\-\.]|^mcic_)/i';
$mcImageManagerConfig['filesystem.invalid_file_name_msg'] = "";
$mcImageManagerConfig['filesystem.extensions'] = "gif,jpg,png,bmp,swf,dcr,mov,qt,ram,rm,avi,mpg,mpeg,asf,flv";
$mcImageManagerConfig['filesystem.readable'] = true;
$mcImageManagerConfig['filesystem.writable'] = true;
$mcImageManagerConfig['filesystem.delete_recursive'] = false;
$mcImageManagerConfig['filesystem.directory_templates'] = '${rootpath}/templates/directory,${rootpath}/templates/another_directory';
$mcImageManagerConfig['filesystem.force_directory_template'] = false;
$mcImageManagerConfig['filesystem.list_directories'] = false;
$mcImageManagerConfig['filesystem.clean_names'] = true;
$mcImageManagerConfig['filesystem.delete_format_images'] = true;
$mcImageManagerConfig['filesystem.allow_export'] = "extensions,readable,writable,directory_templates,force_directory_template,clean_names";
$mcImageManagerConfig['filesystem.allow_override'] = "*";
// Thumbnail options
$mcImageManagerConfig['thumbnail'] = "ImageToolsGD";
$mcImageManagerConfig['thumbnail.enabled'] = true; // false default, verify that you have GD on your server
$mcImageManagerConfig['thumbnail.auto_generate'] = true; // only if above is set to true
$mcImageManagerConfig['thumbnail.use_exif'] = false; // use exif th if avalible
$mcImageManagerConfig['thumbnail.insert'] = true;
$mcImageManagerConfig['thumbnail.width'] = "90"; // px
$mcImageManagerConfig['thumbnail.height'] = "90"; // px
$mcImageManagerConfig['thumbnail.max_width'] = ""; // px (will not generate thumbnail if larger than this size)
$mcImageManagerConfig['thumbnail.max_height'] = ""; // px (will not generate thumbnail if larger than this size)
$mcImageManagerConfig['thumbnail.scale_mode'] = "percentage"; // percentage,resize
$mcImageManagerConfig['thumbnail.folder'] = "mcith"; // required, exclude this folder with file pattern '/^mcith$/i' if you don't want it to show
$mcImageManagerConfig['thumbnail.prefix'] = "mcith_"; //
$mcImageManagerConfig['thumbnail.delete'] = true; // delete th when original is deleted
$mcImageManagerConfig['thumbnail.jpeg_quality'] = 75; // quality of th image, note that this is not checked against when regenerating ths.
$mcImageManagerConfig['thumbnail.allow_export'] = "width,height,insert";
$mcImageManagerConfig['thumbnail.allow_override'] = "*";
// Upload options
$mcImageManagerConfig['upload.maxsize'] = "10MB";
$mcImageManagerConfig['upload.overwrite'] = false;
$mcImageManagerConfig['upload.include_file_pattern'] = '';
$mcImageManagerConfig['upload.exclude_file_pattern'] = '';
$mcImageManagerConfig['upload.invalid_file_name_msg'] = "";
$mcImageManagerConfig['upload.extensions'] = "gif,jpg,jpeg,png";
$mcImageManagerConfig['upload.create_thumbnail'] = true; // true/false, create thumbnail on upload
$mcImageManagerConfig['upload.autoresize'] = false; // Force max width/height, IM will rescale uploaded images.
$mcImageManagerConfig['upload.autoresize_jpeg_quality'] = 75; // Force max width/height, IM will rescale uploaded images.
$mcImageManagerConfig['upload.max_width'] = "800"; // Only if force_width_height is true
$mcImageManagerConfig['upload.max_height'] = "600"; // Only if force_width_height is true
$mcImageManagerConfig['upload.multiple_upload'] = true;
$mcImageManagerConfig['upload.chunk_size'] = '1mb';
$mcImageManagerConfig['upload.format'] = "";
$mcImageManagerConfig['upload.allow_export'] = "maxsize,multiple_upload,chunk_size,overwrite,extensions";
$mcImageManagerConfig['upload.allow_override'] = "*";
// Edit image options
$mcImageManagerConfig['edit.jpeg_quality'] = "90";
$mcImageManagerConfig['edit.format'] = "";
// // Authenication
// $mcImageManagerConfig['authenticator'] = "SessionAuthenticator";
// $mcImageManagerConfig['authenticator.login_page'] = "";
// $mcImageManagerConfig['authenticator.allow_override'] = "*";
// // SessionAuthenticator
// $mcImageManagerConfig['SessionAuthenticator.logged_in_key'] = "isLoggedIn";
// $mcImageManagerConfig['SessionAuthenticator.groups_key'] = "groups";
// $mcImageManagerConfig['SessionAuthenticator.user_key'] = "user";
// $mcImageManagerConfig['SessionAuthenticator.path_key'] = "mc_path";
// $mcImageManagerConfig['SessionAuthenticator.rootpath_key'] = "mc_rootpath";
// $mcImageManagerConfig['SessionAuthenticator.config_prefix'] = "imagemanager";
// // ExternalAuthenticator config
// $mcImageManagerConfig['ExternalAuthenticator.external_auth_url'] = "auth_example.jsp";
// $mcImageManagerConfig['ExternalAuthenticator.secret_key'] = "someSecretKey";
// Local filesystem options
$mcImageManagerConfig['filesystem.local.file_mask'] = "0777"; // 0777 for full access
$mcImageManagerConfig['filesystem.local.directory_mask'] = "0777"; // 0777 for full access
$mcImageManagerConfig['filesystem.local.file_template'] = '${rootpath}/templates/file.htm'; // not yet implemented, always forced
$mcImageManagerConfig['filesystem.local.access_file_name'] = "mc_access";
$mcImageManagerConfig['filesystem.local.allow_override'] = "*";
// Stream options
$mcImageManagerConfig['stream.mimefile'] = "mime.types";
$mcImageManagerConfig['stream.include_file_pattern'] = '';
$mcImageManagerConfig['stream.exclude_file_pattern'] = '/\.php$|\.shtm$/i';
$mcImageManagerConfig['stream.extensions'] = "*";
$mcImageManagerConfig['stream.allow_override'] = "*";
// Filemanager configuration
$mcImageManagerConfig['filemanager.urlprefix'] = "../../../filemanager/?type=fm"; // need to add "filemanager" button to tools as well.
$mcImageManagerConfig['filemanager.allow_override'] = "*";
$mcImageManagerConfig['filemanager.allow_export'] = "urlprefix";
// Logging options
$mcImageManagerConfig['log.enabled'] = false;
$mcImageManagerConfig['log.level'] = "error"; // debug|warn|error
$mcImageManagerConfig['log.path'] = "logs";
$mcImageManagerConfig['log.filename'] = "{level}.log";
$mcImageManagerConfig['log.format'] = "[{time}] [{level}] {message}";
$mcImageManagerConfig['log.max_size'] = "100k";
$mcImageManagerConfig['log.max_files'] = "10";
// Custom plugin options.
$mcImageManagerConfig['favorites.max'] = 20; // 10 is default.
$mcImageManagerConfig['history.max'] = 20; // 10 is default.
?>
|
chicuongit913/zend_kacana
|
zend2test/public/js/tinymce/plugins/imagemanager/config.php
|
PHP
|
bsd-3-clause
| 8,822
|
/* Generated By:JavaCC: Do not edit this line. ProbeParserTokenManager.java */
package avrora.test.probes;
import java.io.IOException;
import java.io.PrintStream;
public class ProbeParserTokenManager implements ProbeParserConstants
{
public PrintStream debugStream = System.out;
public void setDebugStream(PrintStream ds) { debugStream = ds; }
private int jjStopStringLiteralDfa_0(int pos, long active0)
{
switch (pos)
{
case 0:
if ((active0 & 0x3fc000L) != 0L)
{
jjmatchedKind = 26;
return 6;
}
return -1;
case 1:
if ((active0 & 0x3fc000L) != 0L)
{
jjmatchedKind = 26;
jjmatchedPos = 1;
return 6;
}
return -1;
case 2:
if ((active0 & 0x3fc000L) != 0L)
{
jjmatchedKind = 26;
jjmatchedPos = 2;
return 6;
}
return -1;
case 3:
if ((active0 & 0x20000L) != 0L)
return 6;
if ((active0 & 0x3dc000L) != 0L)
{
jjmatchedKind = 26;
jjmatchedPos = 3;
return 6;
}
return -1;
case 4:
if ((active0 & 0x1c000L) != 0L)
return 6;
if ((active0 & 0x3c0000L) != 0L)
{
jjmatchedKind = 26;
jjmatchedPos = 4;
return 6;
}
return -1;
case 5:
if ((active0 & 0x100000L) != 0L)
{
jjmatchedKind = 26;
jjmatchedPos = 5;
return 6;
}
if ((active0 & 0x2c0000L) != 0L)
return 6;
return -1;
default :
return -1;
}
}
private int jjStartNfa_0(int pos, long active0)
{
return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1);
}
private int jjStopAtPos(int pos, int kind)
{
jjmatchedKind = kind;
jjmatchedPos = pos;
return pos + 1;
}
private int jjStartNfaWithStates_0(int pos, int kind, int state)
{
jjmatchedKind = kind;
jjmatchedPos = pos;
try { curChar = input_stream.readChar(); }
catch(IOException e) { return pos + 1; }
return jjMoveNfa_0(state, pos + 1);
}
private int jjMoveStringLiteralDfa0_0()
{
switch(curChar)
{
case 35:
return jjStopAtPos(0, 6);
case 59:
return jjStopAtPos(0, 24);
case 97:
return jjMoveStringLiteralDfa1_0(0x100000L);
case 101:
return jjMoveStringLiteralDfa1_0(0x8000L);
case 105:
return jjMoveStringLiteralDfa1_0(0x40000L);
case 109:
return jjMoveStringLiteralDfa1_0(0x20000L);
case 112:
return jjMoveStringLiteralDfa1_0(0x4000L);
case 114:
return jjMoveStringLiteralDfa1_0(0x280000L);
case 119:
return jjMoveStringLiteralDfa1_0(0x10000L);
case 123:
return jjStopAtPos(0, 22);
case 124:
return jjStopAtPos(0, 25);
case 125:
return jjStopAtPos(0, 23);
default :
return jjMoveNfa_0(0, 0);
}
}
private int jjMoveStringLiteralDfa1_0(long active0)
{
try { curChar = input_stream.readChar(); }
catch(IOException e) {
jjStopStringLiteralDfa_0(0, active0);
return 1;
}
switch(curChar)
{
case 97:
return jjMoveStringLiteralDfa2_0(active0, 0x30000L);
case 100:
return jjMoveStringLiteralDfa2_0(active0, 0x100000L);
case 101:
return jjMoveStringLiteralDfa2_0(active0, 0x280000L);
case 110:
return jjMoveStringLiteralDfa2_0(active0, 0x40000L);
case 114:
return jjMoveStringLiteralDfa2_0(active0, 0x4000L);
case 118:
return jjMoveStringLiteralDfa2_0(active0, 0x8000L);
default :
break;
}
return jjStartNfa_0(0, active0);
}
private int jjMoveStringLiteralDfa2_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(0, old0);
try { curChar = input_stream.readChar(); }
catch(IOException e) {
jjStopStringLiteralDfa_0(1, active0);
return 2;
}
switch(curChar)
{
case 101:
return jjMoveStringLiteralDfa3_0(active0, 0x8000L);
case 105:
return jjMoveStringLiteralDfa3_0(active0, 0x20000L);
case 109:
return jjMoveStringLiteralDfa3_0(active0, 0x80000L);
case 111:
return jjMoveStringLiteralDfa3_0(active0, 0x4000L);
case 115:
return jjMoveStringLiteralDfa3_0(active0, 0x240000L);
case 116:
return jjMoveStringLiteralDfa3_0(active0, 0x10000L);
case 118:
return jjMoveStringLiteralDfa3_0(active0, 0x100000L);
default :
break;
}
return jjStartNfa_0(1, active0);
}
private int jjMoveStringLiteralDfa3_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(1, old0);
try { curChar = input_stream.readChar(); }
catch(IOException e) {
jjStopStringLiteralDfa_0(2, active0);
return 3;
}
switch(curChar)
{
case 97:
return jjMoveStringLiteralDfa4_0(active0, 0x100000L);
case 98:
return jjMoveStringLiteralDfa4_0(active0, 0x4000L);
case 99:
return jjMoveStringLiteralDfa4_0(active0, 0x10000L);
case 101:
return jjMoveStringLiteralDfa4_0(active0, 0x40000L);
case 110:
if ((active0 & 0x20000L) != 0L)
return jjStartNfaWithStates_0(3, 17, 6);
return jjMoveStringLiteralDfa4_0(active0, 0x8000L);
case 111:
return jjMoveStringLiteralDfa4_0(active0, 0x80000L);
case 117:
return jjMoveStringLiteralDfa4_0(active0, 0x200000L);
default :
break;
}
return jjStartNfa_0(2, active0);
}
private int jjMoveStringLiteralDfa4_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(2, old0);
try { curChar = input_stream.readChar(); }
catch(IOException e) {
jjStopStringLiteralDfa_0(3, active0);
return 4;
}
switch(curChar)
{
case 101:
if ((active0 & 0x4000L) != 0L)
return jjStartNfaWithStates_0(4, 14, 6);
break;
case 104:
if ((active0 & 0x10000L) != 0L)
return jjStartNfaWithStates_0(4, 16, 6);
break;
case 108:
return jjMoveStringLiteralDfa5_0(active0, 0x200000L);
case 110:
return jjMoveStringLiteralDfa5_0(active0, 0x100000L);
case 114:
return jjMoveStringLiteralDfa5_0(active0, 0x40000L);
case 116:
if ((active0 & 0x8000L) != 0L)
return jjStartNfaWithStates_0(4, 15, 6);
break;
case 118:
return jjMoveStringLiteralDfa5_0(active0, 0x80000L);
default :
break;
}
return jjStartNfa_0(3, active0);
}
private int jjMoveStringLiteralDfa5_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(3, old0);
try { curChar = input_stream.readChar(); }
catch(IOException e) {
jjStopStringLiteralDfa_0(4, active0);
return 5;
}
switch(curChar)
{
case 99:
return jjMoveStringLiteralDfa6_0(active0, 0x100000L);
case 101:
if ((active0 & 0x80000L) != 0L)
return jjStartNfaWithStates_0(5, 19, 6);
break;
case 116:
if ((active0 & 0x40000L) != 0L)
return jjStartNfaWithStates_0(5, 18, 6);
else if ((active0 & 0x200000L) != 0L)
return jjStartNfaWithStates_0(5, 21, 6);
break;
default :
break;
}
return jjStartNfa_0(4, active0);
}
private int jjMoveStringLiteralDfa6_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(4, old0);
try { curChar = input_stream.readChar(); }
catch(IOException e) {
jjStopStringLiteralDfa_0(5, active0);
return 6;
}
switch(curChar)
{
case 101:
if ((active0 & 0x100000L) != 0L)
return jjStartNfaWithStates_0(6, 20, 6);
break;
default :
break;
}
return jjStartNfa_0(5, active0);
}
private void jjCheckNAdd(int state)
{
if (jjrounds[state] != jjround)
{
jjstateSet[jjnewStateCnt++] = state;
jjrounds[state] = jjround;
}
}
private void jjAddStates(int start, int end)
{
do {
jjstateSet[jjnewStateCnt++] = jjnextStates[start];
} while (start++ != end);
}
private void jjCheckNAddTwoStates(int state1, int state2)
{
jjCheckNAdd(state1);
jjCheckNAdd(state2);
}
private void jjCheckNAddStates(int start, int end)
{
do {
jjCheckNAdd(jjnextStates[start]);
} while (start++ != end);
}
private int jjMoveNfa_0(int startState, int curPos)
{
int startsAt = 0;
jjnewStateCnt = 12;
int i = 1;
jjstateSet[0] = startState;
int kind = 0x7fffffff;
while (true) {
if (++jjround == 0x7fffffff) ReInitRounds();
if (curChar < 64) {
long l = 1L << curChar;
do {
switch (jjstateSet[--i]) {
case 0:
if ((0x3fe000000000000L & l) != 0L) {
if (kind > 9) kind = 9;
jjCheckNAdd(2);
} else if (curChar == 48) {
if (kind > 9) kind = 9;
jjCheckNAddStates(0, 2);
} else if (curChar == 36) jjCheckNAdd(4);
else if (curChar == 45) jjstateSet[jjnewStateCnt++] = 1;
break;
case 1:
if ((0x3fe000000000000L & l) == 0L) break;
if (kind > 9) kind = 9;
jjCheckNAdd(2);
break;
case 2:
if ((0x3ff000000000000L & l) == 0L) break;
if (kind > 9) kind = 9;
jjCheckNAdd(2);
break;
case 3:
if (curChar == 36) jjCheckNAdd(4);
break;
case 4:
if ((0x3ff000000000000L & l) == 0L) break;
if (kind > 9) kind = 9;
jjCheckNAdd(4);
break;
case 6:
if ((0x3ff400000000000L & l) == 0L) break;
if (kind > 26) kind = 26;
jjstateSet[jjnewStateCnt++] = 6;
break;
case 7:
if (curChar != 48) break;
if (kind > 9) kind = 9;
jjCheckNAddStates(0, 2);
break;
case 10:
if ((0x3000000000000L & l) == 0L) break;
if (kind > 9) kind = 9;
jjstateSet[jjnewStateCnt++] = 10;
break;
case 11:
if ((0xff000000000000L & l) == 0L) break;
if (kind > 9) kind = 9;
jjCheckNAdd(11);
break;
default :
break;
}
} while (i != startsAt);
} else if (curChar < 128) {
long l = 1L << (curChar & 077);
do {
switch (jjstateSet[--i]) {
case 0:
case 6:
if ((0x7fffffe87fffffeL & l) == 0L) break;
if (kind > 26) kind = 26;
jjCheckNAdd(6);
break;
case 4:
if ((0x7e0000007eL & l) == 0L) break;
if (kind > 9) kind = 9;
jjCheckNAdd(4);
break;
case 8:
if ((0x100000001000000L & l) != 0L) jjCheckNAdd(4);
break;
case 9:
if ((0x400000004L & l) != 0L) jjstateSet[jjnewStateCnt++] = 10;
break;
default :
break;
}
} while (i != startsAt);
} else {
do {
switch (jjstateSet[--i]) {
default :
break;
}
} while (i != startsAt);
}
if (kind != 0x7fffffff) {
jjmatchedKind = kind;
jjmatchedPos = curPos;
kind = 0x7fffffff;
}
++curPos;
if ((i = jjnewStateCnt) == (startsAt = 12 - (jjnewStateCnt = startsAt))) return curPos;
try {
curChar = input_stream.readChar();
} catch (IOException e) {
return curPos;
}
}
}
private int jjMoveStringLiteralDfa0_1()
{
return jjMoveNfa_1(0, 0);
}
private int jjMoveNfa_1(int startState, int curPos)
{
int startsAt = 0;
jjnewStateCnt = 3;
int i = 1;
jjstateSet[0] = startState;
int kind = 0x7fffffff;
while (true) {
if (++jjround == 0x7fffffff) ReInitRounds();
if (curChar < 64) {
long l = 1L << curChar;
do {
switch (jjstateSet[--i]) {
case 0:
if ((0x2400L & l) != 0L) {
if (kind > 7) kind = 7;
}
if (curChar == 13) jjstateSet[jjnewStateCnt++] = 1;
break;
case 1:
if (curChar == 10 && kind > 7) kind = 7;
break;
case 2:
if (curChar == 13) jjstateSet[jjnewStateCnt++] = 1;
break;
default :
break;
}
} while (i != startsAt);
} else {
do {
switch (jjstateSet[--i]) {
default :
break;
}
} while (i != startsAt);
}
if (kind != 0x7fffffff) {
jjmatchedKind = kind;
jjmatchedPos = curPos;
kind = 0x7fffffff;
}
++curPos;
if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt))) return curPos;
try {
curChar = input_stream.readChar();
} catch (IOException e) {
return curPos;
}
}
}
static final int[] jjnextStates = {
8, 9, 11,
};
public static final String[] jjstrLiteralImages = {
"", null, null, null, null, null, null, null, null, null, null, null, null,
null, "\160\162\157\142\145", "\145\166\145\156\164", "\167\141\164\143\150",
"\155\141\151\156", "\151\156\163\145\162\164", "\162\145\155\157\166\145",
"\141\144\166\141\156\143\145", "\162\145\163\165\154\164", "\173", "\175", "\73", "\174", null, null, null, };
public static final String[] lexStateNames = {
"DEFAULT",
"IN_SINGLE_LINE_COMMENT",
};
public static final int[] jjnewLexState = {
-1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1,
};
static final long[] jjtoToken = {
0x7ffc201L,
};
static final long[] jjtoSkip = {
0xbeL,
};
static final long[] jjtoSpecial = {
0x80L,
};
static final long[] jjtoMore = {
0x140L,
};
protected SimpleCharStream input_stream;
private final int[] jjrounds = new int[12];
private final int[] jjstateSet = new int[24];
StringBuffer image;
int jjimageLen;
int lengthOfMatch;
protected char curChar;
public ProbeParserTokenManager(SimpleCharStream stream)
{
if (SimpleCharStream.staticFlag)
throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");
input_stream = stream;
}
public ProbeParserTokenManager(SimpleCharStream stream, int lexState)
{
this(stream);
SwitchTo(lexState);
}
public void ReInit(SimpleCharStream stream)
{
jjmatchedPos = jjnewStateCnt = 0;
curLexState = defaultLexState;
input_stream = stream;
ReInitRounds();
}
private void ReInitRounds()
{
int i;
jjround = 0x80000001;
for (i = 12; i-- > 0;)
jjrounds[i] = 0x80000000;
}
public void ReInit(SimpleCharStream stream, int lexState)
{
ReInit(stream);
SwitchTo(lexState);
}
public void SwitchTo(int lexState)
{
if (lexState >= 2 || lexState < 0)
throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". LegacyState unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);
else
curLexState = lexState;
}
protected Token jjFillToken()
{
Token t = Token.newToken(jjmatchedKind);
t.kind = jjmatchedKind;
String im = jjstrLiteralImages[jjmatchedKind];
t.image = (im == null) ? input_stream.GetImage() : im;
t.beginLine = input_stream.getBeginLine();
t.beginColumn = input_stream.getBeginColumn();
t.endLine = input_stream.getEndLine();
t.endColumn = input_stream.getEndColumn();
return t;
}
int curLexState = 0;
int defaultLexState = 0;
int jjnewStateCnt;
int jjround;
int jjmatchedPos;
int jjmatchedKind;
public Token getNextToken()
{
Token specialToken = null;
Token matchedToken;
int curPos = 0;
EOFLoop :
while (true) {
try {
curChar = input_stream.BeginToken();
} catch (IOException e) {
jjmatchedKind = 0;
matchedToken = jjFillToken();
matchedToken.specialToken = specialToken;
return matchedToken;
}
image = null;
jjimageLen = 0;
while (true) {
switch (curLexState) {
case 0:
try {
input_stream.backup(0);
while (curChar <= 32 && (0x100003600L & (1L << curChar)) != 0L)
curChar = input_stream.BeginToken();
} catch (IOException e1) {
continue EOFLoop;
}
jjmatchedKind = 0x7fffffff;
jjmatchedPos = 0;
curPos = jjMoveStringLiteralDfa0_0();
break;
case 1:
jjmatchedKind = 0x7fffffff;
jjmatchedPos = 0;
curPos = jjMoveStringLiteralDfa0_1();
if (jjmatchedPos == 0 && jjmatchedKind > 8) {
jjmatchedKind = 8;
}
break;
}
if (jjmatchedKind != 0x7fffffff) {
if (jjmatchedPos + 1 < curPos) input_stream.backup(curPos - jjmatchedPos - 1);
if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) {
matchedToken = jjFillToken();
matchedToken.specialToken = specialToken;
if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind];
return matchedToken;
} else if ((jjtoSkip[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) {
if ((jjtoSpecial[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) {
matchedToken = jjFillToken();
if (specialToken == null) specialToken = matchedToken;
else {
matchedToken.specialToken = specialToken;
specialToken = (specialToken.next = matchedToken);
}
SkipLexicalActions(matchedToken);
} else SkipLexicalActions(null);
if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind];
continue EOFLoop;
}
jjimageLen += jjmatchedPos + 1;
if (jjnewLexState[jjmatchedKind] != -1) curLexState = jjnewLexState[jjmatchedKind];
curPos = 0;
jjmatchedKind = 0x7fffffff;
try {
curChar = input_stream.readChar();
continue;
} catch (IOException e1) {
}
}
int error_line = input_stream.getEndLine();
int error_column = input_stream.getEndColumn();
String error_after = null;
boolean EOFSeen = false;
try {
input_stream.readChar();
input_stream.backup(1);
} catch (IOException e1) {
EOFSeen = true;
error_after = curPos <= 1 ? "" : input_stream.GetImage();
if (curChar == '\n' || curChar == '\r') {
error_line++;
error_column = 0;
} else error_column++;
}
if (!EOFSeen) {
input_stream.backup(1);
error_after = curPos <= 1 ? "" : input_stream.GetImage();
}
throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);
}
}
}
void SkipLexicalActions(Token matchedToken)
{
switch(jjmatchedKind)
{
default :
break;
}
}
}
|
aurelf/avrora
|
src/avrora/test/probes/ProbeParserTokenManager.java
|
Java
|
bsd-3-clause
| 21,622
|
/* getbbent.c - subroutines for accessing the BBoards file */
#ifndef lint
static char ident[] = "@(#)$Id: getbbent.c,v 1.14 1992/12/15 00:20:22 jromine Exp $";
#endif /* lint */
/* LINTLIBRARY */
#include "bboards.h"
#ifndef MMDFONLY
#include "../h/strings.h"
#include <sys/types.h>
#else /* MMDFONLY */
#include "util.h"
#include "mmdf.h"
#include "strings.h"
#endif /* MMDFONLY */
#include <ctype.h>
#include <pwd.h>
#include <grp.h>
#include <stdio.h>
#include <sys/stat.h>
#ifndef MMDFONLY
#define NOTOK (-1)
#define OK 0
#endif /* not MMDFONLY */
#define MaxBBAka 100
#define MaxBBLdr 100
#define MaxBBDist 100
#define NCOLON 9 /* currently 10 fields per entry */
#define COLON ':'
#define COMMA ','
#define NEWLINE '\n'
#define ARCHIVE "archive"
#define CNTFILE ".cnt"
#define DSTFILE ".dist"
#define MAPFILE ".map"
/* */
static int BBuid = -1;
static unsigned int BBflags = SB_NULL;
static char BBName[BUFSIZ] = BBOARDS;
static char BBDir[BUFSIZ] = "";
static char BBData[BUFSIZ] = "";
static FILE *BBfile = NULL;
static struct bboard BB;
static struct bboard *bb = &BB;
static int BBload = 1;
static char BBFile[BUFSIZ];
static char BBArchive[BUFSIZ];
static char BBInfo[BUFSIZ];
static char BBMap[BUFSIZ];
static char *BBAkas[MaxBBAka];
static char *BBLeaders[MaxBBLdr];
static char *BBDists[MaxBBDist];
static char BBAddr[BUFSIZ];
static char BBRequest[BUFSIZ];
static char BBDate[BUFSIZ];
static char BBErrors[BUFSIZ];
#ifdef MMDFONLY
extern LLog *logptr;
#endif /* MMDFONLY */
static char *bbskip (), *getcpy ();
#if defined(__STDC__) && defined(SVR4)
#include <crypt.h>
#endif
#if defined(UNISTD) || defined(_AIX)
#include <unistd.h>
#else
#ifndef __STDC__
char *crypt (), *getpass ();
struct group *getgrnam ();
#ifdef SYS5
struct passwd *getpwnam (), *getpwuid ();
#endif
#endif /* !__STDC__ */
#endif /* _AIX */
static int setpwaux(), getbbitem(), bblose();
static void BBread();
#ifdef UCL
int called_bbc = 0;
char *bbs[101];
#endif
/* */
int setbbfile (file, f)
register char *file;
register int f;
{
if (BBuid == -1)
return setbbinfo (BBOARDS, file, f);
(void) strcpy (BBData, file);
BBflags = SB_NULL;
(void) endbbent ();
return setbbent (f);
}
/* */
int setbbinfo (user, file, f)
register char *user,
*file;
register int f;
{
register struct passwd *pw;
if ((pw = getpwnam (user)) == NULL) {
(void) sprintf (BBErrors, "unknown user: %s", user);
return 0;
}
return setpwinfo (pw, file, f);
}
int setpwinfo (pw, file, f)
register struct passwd *pw;
register char *file;
register int f;
{
if (!setpwaux (pw, file))
return 0;
BBflags = SB_NULL;
(void) endbbent ();
return setbbent (f);
}
/* */
static int setbbaux (name, file)
register char *name,
*file;
{
register struct passwd *pw;
if ((pw = getpwnam (name)) == NULL) {
(void) sprintf (BBErrors, "unknown user: %s", name);
return 0;
}
return setpwaux (pw, file);
}
static int setpwaux (pw, file)
register struct passwd *pw;
register char *file;
{
(void) strcpy (BBName, pw -> pw_name);
BBuid = pw -> pw_uid;
(void) strcpy (BBDir, pw -> pw_dir);
(void) sprintf (BBData, "%s/%s",
*file != '/' ? BBDir : "",
*file != '/' ? file : file + 1);
BBflags = SB_NULL;
return 1;
}
/* */
int setbbent (f)
register int f;
{
if (BBfile == NULL) {
if (BBuid == -1 && !setbbaux (BBOARDS, BBDB))
return 0;
if ((BBfile = fopen (BBData, "r")) == NULL) {
(void) sprintf (BBErrors, "unable to open: %s", BBData);
return 0;
}
}
else
rewind (BBfile);
BBflags |= f;
return (BBfile != NULL);
}
int endbbent () {
if (BBfile != NULL && !(BBflags & SB_STAY)) {
(void) fclose (BBfile);
BBfile = NULL;
}
return 1;
}
long getbbtime () {
struct stat st;
if (BBfile == NULL) {
if (BBuid == -1 && !setbbaux (BBOARDS, BBDB))
return 0;
if (stat (BBData, &st) == NOTOK) {
(void) sprintf (BBErrors, "unable to stat: %s", BBData);
return 0;
}
}
else
if (fstat (fileno (BBfile), &st) == NOTOK) {
(void) sprintf (BBErrors, "unable to fstat: %s", BBData);
return 0;
}
return ((long) st.st_mtime);
}
/* */
struct bboard *getbbent () {
register int count;
register char *p,
*q,
*r,
*d,
*f,
**s;
static char line[BUFSIZ];
if (BBfile == NULL && !setbbent (SB_NULL))
return NULL;
retry: ;
if ((p = fgets (line, sizeof line, BBfile)) == NULL)
return NULL;
for (q = p, count = 0; *q != 0 && *q != NEWLINE; q++)
if (*q == COLON)
count++;
if (count != NCOLON) {
#ifdef MMDFONLY
if (q = index (p, NEWLINE))
*q = 0;
ll_log (logptr, LLOGTMP, "bad entry in %s: %s", BBData, p);
#endif /* MMDFONLY */
goto retry;
}
bb -> bb_name = p;
p = q = bbskip (p, COLON);
p = bb -> bb_file = bbskip (p, COLON);
bb -> bb_archive = bb -> bb_info = bb -> bb_map = "";
p = bb -> bb_passwd = bbskip (p, COLON);
p = r = bbskip (p, COLON);
p = bb -> bb_addr = bbskip (p, COLON);
p = bb -> bb_request = bbskip (p, COLON);
p = bb -> bb_relay = bbskip (p, COLON);
p = d = bbskip (p, COLON);
p = f = bbskip (p, COLON);
(void) bbskip (p, NEWLINE);
s = bb -> bb_aka = BBAkas;
while (*q) {
*s++ = q;
q = bbskip (q, COMMA);
}
*s = 0;
s = bb -> bb_leader = BBLeaders;
if (*r == 0) {
if (!(BBflags & SB_FAST)) {
*s++ = BBName;
*s = 0;
}
}
else {
while (*r) {
*s++ = r;
r = bbskip (r, COMMA);
}
*s = 0;
}
s = bb -> bb_dist = BBDists;
while (*d) {
*s++ = d;
d = bbskip (d, COMMA);
}
*s = 0;
if (*f)
(void) sscanf (f, "%o", &bb -> bb_flags);
else
bb -> bb_flags = BB_NULL;
bb -> bb_count = bb -> bb_maxima = 0;
bb -> bb_date = NULL;
bb -> bb_next = bb -> bb_link = bb -> bb_chain = NULL;
#ifdef UCL
/*
* Only do a BBread on bboards that the user has expressed an
* interest in, if we were called by bbc.
*/
if (BBload) {
register char **ap, *cp;
register int bbp;
if (called_bbc == 0)
BBread();
else {
for (bbp = 0; cp = bbs[bbp]; bbp++) {
if (!strcmp(bb->bb_name, cp)) {
BBread();
break;
}
for (ap = bb->bb_aka; *ap; ap++)
if (!strcmp(*ap, cp)) {
BBread();
break;
}
}
}
}
#else
if (BBload)
BBread ();
#endif
return bb;
}
/* */
struct bboard *getbbnam (name)
register char *name;
{
register struct bboard *b = NULL;
if (!setbbent (SB_NULL))
return NULL;
BBload = 0;
while ((b = getbbent ()) && strcmp (name, b -> bb_name))
continue;
BBload = 1;
(void) endbbent ();
if (b != NULL)
BBread ();
return b;
}
struct bboard *getbbaka (aka)
register char *aka;
{
register char **ap;
register struct bboard *b = NULL;
if (!setbbent (SB_NULL))
return NULL;
BBload = 0;
while ((b = getbbent ()) != NULL)
for (ap = b -> bb_aka; *ap; ap++)
if (strcmp (aka, *ap) == 0)
goto hit;
hit: ;
BBload = 1;
(void) endbbent ();
if (b != NULL)
BBread ();
return b;
}
/* */
static void BBread ()
{
register int i;
register char *cp,
*dp,
*p,
*r;
char prf[BUFSIZ];
static char line[BUFSIZ];
register FILE * info;
if (BBflags & SB_FAST)
return;
p = index (bb -> bb_request, '@');
r = index (bb -> bb_addr, '@');
BBRequest[0] = 0;
if (*bb -> bb_request == '-')
if (p == NULL && r && *r == '@')
(void) sprintf (BBRequest, "%s%s%s",
bb -> bb_name, bb -> bb_request, r);
else
(void) sprintf (BBRequest, "%s%s",
bb -> bb_name, bb -> bb_request);
else
if (p == NULL && r && *r == '@' && *bb -> bb_request)
(void) sprintf (BBRequest, "%s%s", bb -> bb_request, r);
if (BBRequest[0])
bb -> bb_request = BBRequest;
else
if (*bb -> bb_request == 0)
bb -> bb_request = *bb -> bb_addr ? bb -> bb_addr
: bb -> bb_leader[0];
if (*bb -> bb_addr == '@') {
(void) sprintf (BBAddr, "%s%s", bb -> bb_name, bb -> bb_addr);
bb -> bb_addr = BBAddr;
}
else
if (*bb -> bb_addr == 0)
bb -> bb_addr = bb -> bb_name;
if (*bb -> bb_file == 0)
return;
if (*bb -> bb_file != '/') {
(void) sprintf (BBFile, "%s/%s", BBDir, bb -> bb_file);
bb -> bb_file = BBFile;
}
if ((cp = rindex (bb -> bb_file, '/')) == NULL || *++cp == 0)
(void) strcpy (prf, ""), cp = bb -> bb_file;
else
(void) sprintf (prf, "%.*s", cp - bb -> bb_file, bb -> bb_file);
if ((dp = index (cp, '.')) == NULL)
dp = cp + strlen (cp);
(void) sprintf (BBArchive, "%s%s/%s", prf, ARCHIVE, cp);
bb -> bb_archive = BBArchive;
(void) sprintf (BBInfo, "%s.%.*s%s", prf, dp - cp, cp, CNTFILE);
bb -> bb_info = BBInfo;
(void) sprintf (BBMap, "%s.%.*s%s", prf, dp - cp, cp, MAPFILE);
bb -> bb_map = BBMap;
if ((info = fopen (bb -> bb_info, "r")) == NULL)
return;
if (fgets (line, sizeof line, info) && (i = atoi (line)) > 0)
bb -> bb_maxima = (unsigned) i;
if (!feof (info) && fgets (line, sizeof line, info)) {
(void) strcpy (BBDate, line);
if (cp = index (BBDate, NEWLINE))
*cp = 0;
bb -> bb_date = BBDate;
}
(void) fclose (info);
}
/* */
int ldrbb (b)
register struct bboard *b;
{
register char *p,
**q,
**r;
static int uid = 0,
gid = 0;
static char username[10] = "";
register struct passwd *pw;
register struct group *gr;
if (b == NULL)
return 0;
if (BBuid == -1 && !setbbaux (BBOARDS, BBDB))
return 0;
if (username[0] == 0) {
if ((pw = getpwuid (uid = getuid ())) == NULL)
return 0;
gid = getgid ();
(void) strcpy (username, pw -> pw_name);
}
if (uid == BBuid)
return 1;
q = b -> bb_leader;
while (p = *q++)
if (*p == '=') {
if ((gr = getgrnam (++p)) == NULL)
continue;
if (gid == gr -> gr_gid)
return 1;
r = gr -> gr_mem;
while (p = *r++)
if (strcmp (username, p) == 0)
return 1;
}
else
if (strcmp (username, p) == 0)
return 1;
return 0;
}
/* */
int ldrchk (b)
register struct bboard *b;
{
if (b == NULL)
return 0;
if (*b -> bb_passwd == 0)
return 1;
if (strcmp (b -> bb_passwd,
crypt (getpass ("Password: "), b -> bb_passwd)) == 0)
return 1;
fprintf (stderr, "Sorry\n");
return 0;
}
/* */
struct bboard *getbbcpy (bp)
register struct bboard *bp;
{
register char **p,
**q;
register struct bboard *b;
if (bp == NULL)
return NULL;
b = (struct bboard *) malloc ((unsigned) sizeof *b);
if (b == NULL)
return NULL;
b -> bb_name = getcpy (bp -> bb_name);
b -> bb_file = getcpy (bp -> bb_file);
b -> bb_archive = getcpy (bp -> bb_archive);
b -> bb_info = getcpy (bp -> bb_info);
b -> bb_map = getcpy (bp -> bb_map);
b -> bb_passwd = getcpy (bp -> bb_passwd);
b -> bb_flags = bp -> bb_flags;
b -> bb_count = bp -> bb_count;
b -> bb_maxima = bp -> bb_maxima;
b -> bb_date = getcpy (bp -> bb_date);
b -> bb_addr = getcpy (bp -> bb_addr);
b -> bb_request = getcpy (bp -> bb_request);
b -> bb_relay = getcpy (bp -> bb_relay);
for (p = bp -> bb_aka; *p; p++)
continue;
b -> bb_aka =
q = (char **) calloc ((unsigned) (p - bp -> bb_aka + 1), sizeof *q);
if (q == NULL)
return NULL;
for (p = bp -> bb_aka; *p; *q++ = getcpy (*p++))
continue;
*q = NULL;
for (p = bp -> bb_leader; *p; p++)
continue;
b -> bb_leader =
q = (char **) calloc ((unsigned) (p - bp -> bb_leader + 1), sizeof *q);
if (q == NULL)
return NULL;
for (p = bp -> bb_leader; *p; *q++ = getcpy (*p++))
continue;
*q = NULL;
for (p = bp -> bb_dist; *p; p++)
continue;
b -> bb_dist =
q = (char **) calloc ((unsigned) (p - bp -> bb_dist + 1), sizeof *q);
if (q == NULL)
return NULL;
for (p = bp -> bb_dist; *p; *q++ = getcpy (*p++))
continue;
*q = NULL;
b -> bb_next = bp -> bb_next;
b -> bb_link = bp -> bb_link;
b -> bb_chain = bp -> bb_chain;
return b;
}
/* */
int getbbdist (bb, action)
register struct bboard *bb;
register int (*action) ();
{
register int result;
register char **dp;
BBErrors[0] = 0;
for (dp = bb -> bb_dist; *dp; dp++)
if (result = getbbitem (bb, *dp, action))
return result;
return result;
}
char *getbberr () {
return (BBErrors[0] ? BBErrors : NULL);
}
/* */
static int getbbitem (bb, item, action)
register struct bboard *bb;
register char *item;
register int (*action) ();
{
register int result;
register char *cp,
*dp,
*hp,
*np;
char mbox[BUFSIZ],
buffer[BUFSIZ],
file[BUFSIZ],
host[BUFSIZ],
prf[BUFSIZ];
register FILE *fp;
switch (*item) {
case '*':
switch (*++item) {
case '/':
hp = item;
break;
case 0:
if ((cp = rindex (bb -> bb_file, '/')) == NULL || *++cp == 0)
(void) strcpy (prf, ""), cp = bb -> bb_file;
else
(void) sprintf (prf, "%.*s", cp - bb -> bb_file, bb -> bb_file);
if ((dp = index (cp, '.')) == NULL)
dp = cp + strlen (cp);
(void) sprintf (file, "%s.%.*s%s", prf, dp - cp, cp, DSTFILE);
hp = file;
break;
default:
(void) sprintf (file, "%s/%s", BBDir, item);
hp = file;
break;
}
if ((fp = fopen (hp, "r")) == NULL)
return bblose ("unable to read file %s", hp);
while (fgets (buffer, sizeof buffer, fp)) {
if (np = index (buffer, '\n'))
*np = 0;
if (result = getbbitem (bb, buffer, action)) {
(void) fclose (fp);
(void) bblose ("error with file %s, item %s", hp, buffer);
return result;
}
}
(void) fclose (fp);
return OK;
default:
if (hp = rindex (item, '@')) {
*hp++ = 0;
(void) strcpy (mbox, item);
(void) strcpy (host, hp);
*--hp = '@';
}
else {
(void) sprintf (mbox, "%s%s", DISTADR, bb -> bb_name);
(void) strcpy (host, item);
}
if (result = (*action) (mbox, host))
(void) bblose ("action (%s, %s) returned 0%o", mbox, host, result);
return result;
}
}
/* */
/* VARARGS1 */
static int bblose (fmt, a, b, c)
char *fmt,
*a,
*b,
*c;
{
if (BBErrors[0] == 0)
(void) sprintf (BBErrors, fmt, a, b, c);
return NOTOK;
}
/* */
void make_lower (s1, s2)
register char *s1,
*s2;
{
if (s1 == NULL || s2 == NULL)
return;
for (; *s2; s2++)
*s1++ = isupper (*s2) ? tolower (*s2) : *s2;
*s1 = 0;
}
/* */
static char *bbskip (p, c)
register char *p,
c;
{
if (p == NULL)
return NULL;
while (*p && *p != c)
p++;
if (*p)
*p++ = 0;
return p;
}
static char *getcpy (s)
register char *s;
{
register char *p;
if (s == NULL)
return NULL;
if (p = malloc ((unsigned) (strlen (s) + 1)))
(void) strcpy (p, s);
return p;
}
|
dscho/nmh
|
docs/historical/mh-6.8.5/zotnet/bboards/getbbent.c
|
C
|
bsd-3-clause
| 15,191
|
define([
"./ObservablePath",
"./BindingSourceList",
"./BindingTarget",
"./Each",
"./schedule",
"./computed",
"./wrapper"
], 1);
|
asudoh/liaison
|
tests/allNode.js
|
JavaScript
|
bsd-3-clause
| 135
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/ime/linux/fake_input_method_context.h"
namespace ui {
FakeInputMethodContext::FakeInputMethodContext() {}
// Overriden from ui::LinuxInputMethodContext
bool FakeInputMethodContext::DispatchKeyEvent(
const ui::KeyEvent& /* key_event */) {
return false;
}
bool FakeInputMethodContext::IsPeekKeyEvent(const ui::KeyEvent& key_event) {
return false;
}
void FakeInputMethodContext::Reset() {
}
void FakeInputMethodContext::Focus() {
}
void FakeInputMethodContext::Blur() {
}
void FakeInputMethodContext::SetCursorLocation(const gfx::Rect& rect) {
}
void FakeInputMethodContext::SetSurroundingText(
const std::u16string& text,
const gfx::Range& selection_range) {}
} // namespace ui
|
scheib/chromium
|
ui/base/ime/linux/fake_input_method_context.cc
|
C++
|
bsd-3-clause
| 888
|
/*
* Copyright (c) 2009-2015, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.patientdiscovery.response;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import org.hl7.v3.PRPAIN201306UV02;
import org.hl7.v3.ProxyPRPAIN201305UVProxySecuredRequestType;
/**
*
* @author dunnek
*/
public class ResponseParams {
public ProxyPRPAIN201305UVProxySecuredRequestType origRequest;
public PRPAIN201306UV02 response;
// public WebServiceContext context;
public AssertionType assertion;
}
|
beiyuxinke/CONNECT
|
Product/Production/Services/PatientDiscoveryCore/src/main/java/gov/hhs/fha/nhinc/patientdiscovery/response/ResponseParams.java
|
Java
|
bsd-3-clause
| 2,132
|
/* $NetBSD: modify_c.c,v 1.1.1.2 2014/04/24 12:45:49 pettai Exp $ */
/*
* Copyright (c) 1997 - 1999 Kungliga Tekniska Högskolan
* (Royal Institute of Technology, Stockholm, Sweden).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "kadm5_locl.h"
__RCSID("NetBSD");
kadm5_ret_t
kadm5_c_modify_principal(void *server_handle,
kadm5_principal_ent_t princ,
uint32_t mask)
{
kadm5_client_context *context = server_handle;
kadm5_ret_t ret;
krb5_storage *sp;
unsigned char buf[1024];
int32_t tmp;
krb5_data reply;
ret = _kadm5_connect(server_handle);
if(ret)
return ret;
sp = krb5_storage_from_mem(buf, sizeof(buf));
if (sp == NULL) {
krb5_clear_error_message(context->context);
return ENOMEM;
}
krb5_store_int32(sp, kadm_modify);
kadm5_store_principal_ent(sp, princ);
krb5_store_int32(sp, mask);
ret = _kadm5_client_send(context, sp);
krb5_storage_free(sp);
if(ret)
return ret;
ret = _kadm5_client_recv(context, &reply);
if(ret)
return ret;
sp = krb5_storage_from_data (&reply);
if (sp == NULL) {
krb5_clear_error_message(context->context);
krb5_data_free (&reply);
return ENOMEM;
}
krb5_ret_int32(sp, &tmp);
krb5_clear_error_message(context->context);
krb5_storage_free(sp);
krb5_data_free (&reply);
return tmp;
}
|
GaloisInc/hacrypto
|
src/C/NetBSD-7.0/crypto/external/bsd/heimdal/dist/lib/kadm5/modify_c.c
|
C
|
bsd-3-clause
| 2,831
|
package com.oracle.xmlns.apps.crmcommon.salesparties.salespartiesservice.types;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import com.oracle.xmlns.apps.crmcommon.salesparties.salespartiesservice.SalesAccountResource;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="result" type="{http://xmlns.oracle.com/apps/crmCommon/salesParties/salesPartiesService/}SalesAccountResource" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"result"
})
@XmlRootElement(name = "findSalesAccountResourceAsyncResponse")
public class FindSalesAccountResourceAsyncResponse {
protected List<SalesAccountResource> result;
/**
* Gets the value of the result property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the result property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getResult().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SalesAccountResource }
*
*
*/
public List<SalesAccountResource> getResult() {
if (result == null) {
result = new ArrayList<SalesAccountResource>();
}
return this.result;
}
}
|
dushmis/Oracle-Cloud
|
PaaS_SaaS_Accelerator_RESTFulFacade/FusionProxy_SalesPartyService/src/com/oracle/xmlns/apps/crmcommon/salesparties/salespartiesservice/types/FindSalesAccountResourceAsyncResponse.java
|
Java
|
bsd-3-clause
| 2,168
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (recalc) {
if (!size && size !== 0 || recalc) {
if (_ExecutionEnvironment2.default.canUseDOM) {
var scrollDiv = document.createElement("div");
scrollDiv.style.position = "absolute";
scrollDiv.style.top = "-9999px";
scrollDiv.style.width = "50px";
scrollDiv.style.height = "50px";
scrollDiv.style.overflow = "scroll";
document.body.appendChild(scrollDiv);
size = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
}
}
return size;
};
var _ExecutionEnvironment = require("./ExecutionEnvironment.js");
var _ExecutionEnvironment2 = _interopRequireDefault(_ExecutionEnvironment);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var size = void 0;
|
teasim/teasim-helpers
|
build/scrollbarSize.js
|
JavaScript
|
bsd-3-clause
| 906
|
# 0.15.09.08
* Add a `.gitignore` file. (Stéphane HULARD, 2015-08-03T11:41:34+02:00)
# 0.15.06.01
* Make the `praspel` function global. (Ivan Enderlin, 2015-06-01T12:19:17+02:00)
* Change `interprete` method name to `interpret`. (Ivan Enderlin, 2015-06-01T12:02:37+02:00)
# 0.15.05.29
* Move to `Hoa\Ustring`. (Ivan Enderlin, 2015-05-29T14:50:47+02:00)
* Move to PSR-1-2 & drop PHP5.3 & `from`/`import`. (Ivan Enderlin, 2015-05-28T12:10:30+02:00)
# 0.15.02.24
* Add the `CHANGELOG.md` file. (Ivan Enderlin, 2015-02-24T09:36:29+01:00)
* Happy new year! (Ivan Enderlin, 2015-01-05T14:44:27+01:00)
# 0.14.12.10
* Move to PSR-4. (Ivan Enderlin, 2014-12-09T13:59:10+01:00)
# 0.14.11.25
* `Hoa\Visitor` has been finalized. (Ivan Enderlin, 2014-11-15T22:22:01+01:00)
# 0.14.11.09
* Use `hoa/iterator` `~1.0`. (Ivan Enderlin, 2014-11-09T11:05:20+01:00)
# 0.14.09.23
* Add `branch-alias`. (Stéphane PY, 2014-09-23T11:56:17+02:00)
# 0.14.09.17
* Drop PHP5.3. (Ivan Enderlin, 2014-09-17T17:36:18+02:00)
* Add the installation section. (Ivan Enderlin, 2014-09-17T17:36:04+02:00)
(first snapshot)
|
vcgato29/Central
|
Hoa/Praspel/CHANGELOG.md
|
Markdown
|
bsd-3-clause
| 1,130
|
using System;
using System.Collections.Generic;
using System.Threading;
using System.Reflection;
using System.Xml;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenMetaverse.Utilities;
namespace OpenMetaverse.TestClient
{
public class TestClient : GridClient
{
public UUID GroupID = UUID.Zero;
public Dictionary<UUID, GroupMember> GroupMembers;
public Dictionary<UUID, AvatarAppearancePacket> Appearances = new Dictionary<UUID, AvatarAppearancePacket>();
public Dictionary<string, Command> Commands = new Dictionary<string, Command>();
public bool Running = true;
public bool GroupCommands = false;
public string MasterName = String.Empty;
public UUID MasterKey = UUID.Zero;
public bool AllowObjectMaster = false;
public ClientManager ClientManager;
public VoiceManager VoiceManager;
// Shell-like inventory commands need to be aware of the 'current' inventory folder.
public InventoryFolder CurrentDirectory = null;
private System.Timers.Timer updateTimer;
private UUID GroupMembersRequestID;
public Dictionary<UUID, Group> GroupsCache = null;
private ManualResetEvent GroupsEvent = new ManualResetEvent(false);
/// <summary>
///
/// </summary>
public TestClient(ClientManager manager)
{
ClientManager = manager;
updateTimer = new System.Timers.Timer(500);
updateTimer.Elapsed += new System.Timers.ElapsedEventHandler(updateTimer_Elapsed);
RegisterAllCommands(Assembly.GetExecutingAssembly());
Settings.LOG_LEVEL = Helpers.LogLevel.Debug;
Settings.LOG_RESENDS = false;
Settings.STORE_LAND_PATCHES = true;
Settings.ALWAYS_DECODE_OBJECTS = true;
Settings.ALWAYS_REQUEST_OBJECTS = true;
Settings.SEND_AGENT_UPDATES = true;
Settings.USE_ASSET_CACHE = true;
Network.RegisterCallback(PacketType.AgentDataUpdate, AgentDataUpdateHandler);
Network.LoginProgress += LoginHandler;
Self.IM += Self_IM;
Groups.GroupMembersReply += GroupMembersHandler;
Inventory.InventoryObjectOffered += Inventory_OnInventoryObjectReceived;
Network.RegisterCallback(PacketType.AvatarAppearance, AvatarAppearanceHandler);
Network.RegisterCallback(PacketType.AlertMessage, AlertMessageHandler);
VoiceManager = new VoiceManager(this);
updateTimer.Start();
}
void Self_IM(object sender, InstantMessageEventArgs e)
{
bool groupIM = e.IM.GroupIM && GroupMembers != null && GroupMembers.ContainsKey(e.IM.FromAgentID) ? true : false;
if (e.IM.FromAgentID == MasterKey || (GroupCommands && groupIM))
{
// Received an IM from someone that is authenticated
Console.WriteLine("<{0} ({1})> {2}: {3} (@{4}:{5})", e.IM.GroupIM ? "GroupIM" : "IM", e.IM.Dialog, e.IM.FromAgentName, e.IM.Message,
e.IM.RegionID, e.IM.Position);
if (e.IM.Dialog == InstantMessageDialog.RequestTeleport)
{
Console.WriteLine("Accepting teleport lure.");
Self.TeleportLureRespond(e.IM.FromAgentID, e.IM.IMSessionID, true);
}
else if (
e.IM.Dialog == InstantMessageDialog.MessageFromAgent ||
e.IM.Dialog == InstantMessageDialog.MessageFromObject)
{
ClientManager.Instance.DoCommandAll(e.IM.Message, e.IM.FromAgentID);
}
}
else
{
// Received an IM from someone that is not the bot's master, ignore
Console.WriteLine("<{0} ({1})> {2} (not master): {3} (@{4}:{5})", e.IM.GroupIM ? "GroupIM" : "IM", e.IM.Dialog, e.IM.FromAgentName, e.IM.Message,
e.IM.RegionID, e.IM.Position);
return;
}
}
/// <summary>
/// Initialize everything that needs to be initialized once we're logged in.
/// </summary>
/// <param name="login">The status of the login</param>
/// <param name="message">Error message on failure, MOTD on success.</param>
public void LoginHandler(object sender, LoginProgressEventArgs e)
{
if (e.Status == LoginStatus.Success)
{
// Start in the inventory root folder.
CurrentDirectory = Inventory.Store.RootFolder;
}
}
public void RegisterAllCommands(Assembly assembly)
{
foreach (Type t in assembly.GetTypes())
{
try
{
if (t.IsSubclassOf(typeof(Command)))
{
ConstructorInfo info = t.GetConstructor(new Type[] { typeof(TestClient) });
Command command = (Command)info.Invoke(new object[] { this });
RegisterCommand(command);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
public void RegisterCommand(Command command)
{
command.Client = this;
if (!Commands.ContainsKey(command.Name.ToLower()))
{
Commands.Add(command.Name.ToLower(), command);
}
}
public void ReloadGroupsCache()
{
Groups.CurrentGroups += Groups_CurrentGroups;
Groups.RequestCurrentGroups();
GroupsEvent.WaitOne(10000, false);
Groups.CurrentGroups -= Groups_CurrentGroups;
GroupsEvent.Reset();
}
void Groups_CurrentGroups(object sender, CurrentGroupsEventArgs e)
{
if (null == GroupsCache)
GroupsCache = e.Groups;
else
lock (GroupsCache) { GroupsCache = e.Groups; }
GroupsEvent.Set();
}
public UUID GroupName2UUID(String groupName)
{
UUID tryUUID;
if (UUID.TryParse(groupName,out tryUUID))
return tryUUID;
if (null == GroupsCache) {
ReloadGroupsCache();
if (null == GroupsCache)
return UUID.Zero;
}
lock(GroupsCache) {
if (GroupsCache.Count > 0) {
foreach (Group currentGroup in GroupsCache.Values)
if (currentGroup.Name.ToLower() == groupName.ToLower())
return currentGroup.ID;
}
}
return UUID.Zero;
}
private void updateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
foreach (Command c in Commands.Values)
if (c.Active)
c.Think();
}
private void AgentDataUpdateHandler(object sender, PacketReceivedEventArgs e)
{
AgentDataUpdatePacket p = (AgentDataUpdatePacket)e.Packet;
if (p.AgentData.AgentID == e.Simulator.Client.Self.AgentID)
{
GroupID = p.AgentData.ActiveGroupID;
GroupMembersRequestID = e.Simulator.Client.Groups.RequestGroupMembers(GroupID);
}
}
private void GroupMembersHandler(object sender, GroupMembersReplyEventArgs e)
{
if (e.RequestID != GroupMembersRequestID) return;
GroupMembers = e.Members;
}
private void AvatarAppearanceHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
AvatarAppearancePacket appearance = (AvatarAppearancePacket)packet;
lock (Appearances) Appearances[appearance.Sender.ID] = appearance;
}
private void AlertMessageHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
AlertMessagePacket message = (AlertMessagePacket)packet;
Logger.Log("[AlertMessage] " + Utils.BytesToString(message.AlertData.Message), Helpers.LogLevel.Info, this);
}
private void Inventory_OnInventoryObjectReceived(object sender, InventoryObjectOfferedEventArgs e)
{
if (MasterKey != UUID.Zero)
{
if (e.Offer.FromAgentID != MasterKey)
return;
}
else if (GroupMembers != null && !GroupMembers.ContainsKey(e.Offer.FromAgentID))
{
return;
}
e.Accept = true;
return;
}
}
}
|
N3X15/VoxelSim
|
ThirdParty/libomv/Programs/examples/TestClient/TestClient.cs
|
C#
|
bsd-3-clause
| 8,958
|
<?php
namespace Maghead\Manager;
use Maghead\Runtime\Config\Config;
use Maghead\Runtime\Config\FileConfigLoader;
use Maghead\Runtime\Config\SymbolicLinkConfigWriter;
use Maghead\DSN\DSNParser;
use Maghead\DSN\DSN;
use InvalidArgumentException;
class ConfigManager
{
protected $config;
public function __construct(Config $config)
{
$this->config = $config;
}
public function removeInstance($nodeId)
{
unset($this->config['instances'][$nodeId]);
}
public function addInstance($nodeId, $dsnArg, array $opts = null)
{
$dsn = DSNParser::parse($dsnArg);
$node = $dsn->toConfig();
if ($opts) {
$opts = $this->reconcileNodeConfigKeys($opts);
$node = array_merge($node, $opts);
}
$node = DSN::update($node);
return $this->config['instances'][$nodeId] = $node;
}
public function removeDatabase($nodeId)
{
unset($this->config['databases'][$nodeId]);
}
public function addDatabaseConfig($nodeId, array $nodeConfig)
{
return $this->config['databases'][$nodeId] = $nodeConfig;
}
private function reconcileNodeConfigKeys(array $node)
{
if (isset($node['dbname']) && $node['dbname']) {
$node['database'] = $node['dbname'];
unset($node['dbname']);
}
if (isset($node['pass']) && $node['pass']) {
$node['password'] = $node['pass'];
unset($node['pass']);
}
return $node;
}
public function addDatabase($nodeId, $dsnArg, array $opts = null)
{
$dsn = DSNParser::parse($dsnArg);
$node = $dsn->toConfig();
if ($opts) {
$opts = $this->reconcileNodeConfigKeys($opts);
$node = array_merge($node, $opts);
}
$node = DSN::update($node);
return $this->addDatabaseConfig($nodeId, $node);
}
public function save($file = null)
{
$f = $file ?: $this->config->file;
return SymbolicLinkConfigWriter::write($this->config, $f);
}
}
|
c9s/LazyRecord
|
src/Manager/ConfigManager.php
|
PHP
|
bsd-3-clause
| 2,083
|
---
id: components-and-props
title: Components and Props
permalink: docs/components-and-props.html
redirect_from:
- "docs/reusable-components.html"
- "docs/reusable-components-zh-CN.html"
- "docs/transferring-props.html"
- "docs/transferring-props-it-IT.html"
- "docs/transferring-props-ja-JP.html"
- "docs/transferring-props-ko-KR.html"
- "docs/transferring-props-zh-CN.html"
- "tips/props-in-getInitialState-as-anti-pattern.html"
- "tips/communicate-between-components.html"
prev: rendering-elements.html
next: state-and-lifecycle.html
---
Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.
## Functional and Class Components
The simplest way to define a component is to write a JavaScript function:
```js
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
```
This function is a valid React component because it accepts a single "props" object argument with data and returns a React element. We call such components "functional" because they are literally JavaScript functions.
You can also use an [ES6 class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes) to define a component:
```js
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
```
The above two components are equivalent from React's point of view.
Classes have some additional features that we will discuss in the [next sections](/docs/state-and-lifecycle.html). Until then, we will use functional components for their conciseness.
## Rendering a Component
Previously, we only encountered React elements that represent DOM tags:
```js
const element = <div />;
```
However, elements can also represent user-defined components:
```js
const element = <Welcome name="Sara" />;
```
When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object "props".
For example, this code renders "Hello, Sara" on the page:
```js{1,5}
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Sara" />;
ReactDOM.render(
element,
document.getElementById('root')
);
```
[Try it on CodePen.](http://codepen.io/gaearon/pen/YGYmEG?editors=0010)
Let's recap what happens in this example:
1. We call `ReactDOM.render()` with the `<Welcome name="Sara" />` element.
2. React calls the `Welcome` component with `{name: 'Sara'}` as the props.
3. Our `Welcome` component returns a `<h1>Hello, Sara</h1>` element as the result.
4. React DOM efficiently updates the DOM to match `<h1>Hello, Sara</h1>`.
>**Caveat:**
>
>Always start component names with a capital letter.
>
>For example, `<div />` represents a DOM tag, but `<Welcome />` represents a component and requires `Welcome` to be in scope.
## Composing Components
Components can refer to other components in their output. This lets us use the same component abstraction for any level of detail. A button, a form, a dialog, a screen: in React apps, all those are commonly expressed as components.
For example, we can create an `App` component that renders `Welcome` many times:
```js{8-10}
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
```
[Try it on CodePen.](http://codepen.io/gaearon/pen/KgQKPr?editors=0010)
Typically, new React apps have a single `App` component at the very top. However, if you integrate React into an existing app, you might start bottom-up with a small component like `Button` and gradually work your way to the top of the view hierarchy.
>**Caveat:**
>
>Components must return a single root element. This is why we added a `<div>` to contain all the `<Welcome />` elements.
## Extracting Components
Don't be afraid to split components into smaller components.
For example, consider this `Comment` component:
```js
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name}
/>
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}
```
[Try it on CodePen.](http://codepen.io/gaearon/pen/VKQwEo?editors=0010)
It accepts `author` (an object), `text` (a string), and `date` (a date) as props, and describes a comment on a social media website.
This component can be tricky to change because of all the nesting, and it is also hard to reuse individual parts of it. Let's extract a few components from it.
First, we will extract `Avatar`:
```js{3-6}
function Avatar(props) {
return (
<img className="Avatar"
src={props.user.avatarUrl}
alt={props.user.name}
/>
);
}
```
The `Avatar` doesn't need to know that it is being rendered inside a `Comment`. This is why we have given its prop a more generic name: `user` rather than `author`.
We recommend naming props from the component's own point of view rather than the context in which it is being used.
We can now simplify `Comment` a tiny bit:
```js{5}
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<Avatar user={props.author} />
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}
```
Next, we will extract a `UserInfo` component that renders an `Avatar` next to user's name:
```js{3-8}
function UserInfo(props) {
return (
<div className="UserInfo">
<Avatar user={props.user} />
<div className="UserInfo-name">
{props.user.name}
</div>
</div>
);
}
```
This lets us simplify `Comment` even further:
```js{4}
function Comment(props) {
return (
<div className="Comment">
<UserInfo user={props.author} />
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}
```
[Try it on CodePen.](http://codepen.io/gaearon/pen/rrJNJY?editors=0010)
Extracting components might seem like grunt work at first, but having a palette of reusable components pays off in larger apps. A good rule of thumb is that if a part of your UI is used several times (`Button`, `Panel`, `Avatar`), or is complex enough on its own (`App`, `FeedStory`, `Comment`), it is a good candidate to be a reusable component.
## Props are Read-Only
Whether you declare a component [as a function or a class](#functional-and-class-components), it must never modify its own props. Consider this `sum` function:
```js
function sum(a, b) {
return a + b;
}
```
Such functions are called ["pure"](https://en.wikipedia.org/wiki/Pure_function) because they do not attempt to change their inputs, and always return the same result for the same inputs.
In contrast, this function is impure because it changes its own input:
```js
function withdraw(account, amount) {
account.total -= amount;
}
```
React is pretty flexible but it has a single strict rule:
**All React components must act like pure functions with respect to their props.**
Of course, application UIs are dynamic and change over time. In the [next section](/docs/state-and-lifecycle.html), we will introduce a new concept of "state". State allows React components to change their output over time in response to user actions, network responses, and anything else, without violating this rule.
|
yangshun/react
|
docs/docs/components-and-props.md
|
Markdown
|
bsd-3-clause
| 8,172
|
// (C) Copyright 2009-2011 Frederic Bron.
//
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
//
// See http://www.boost.org/libs/type_traits for most recent version including documentation.
#ifndef NDNBOOST_TT_HAS_PRE_INCREMENT_HPP_INCLUDED
#define NDNBOOST_TT_HAS_PRE_INCREMENT_HPP_INCLUDED
#define NDNBOOST_TT_TRAIT_NAME has_pre_increment
#define NDNBOOST_TT_TRAIT_OP ++
#define NDNBOOST_TT_FORBIDDEN_IF\
::ndnboost::type_traits::ice_or<\
/* bool */\
::ndnboost::is_same< bool, Rhs_nocv >::value,\
/* void* */\
::ndnboost::type_traits::ice_and<\
::ndnboost::is_pointer< Rhs_noref >::value,\
::ndnboost::is_void< Rhs_noptr >::value\
>::value,\
/* (fundamental or pointer) and const */\
::ndnboost::type_traits::ice_and<\
::ndnboost::type_traits::ice_or<\
::ndnboost::is_fundamental< Rhs_nocv >::value,\
::ndnboost::is_pointer< Rhs_noref >::value\
>::value,\
::ndnboost::is_const< Rhs_noref >::value\
>::value\
>::value
#include <ndnboost/type_traits/detail/has_prefix_operator.hpp>
#undef NDNBOOST_TT_TRAIT_NAME
#undef NDNBOOST_TT_TRAIT_OP
#undef NDNBOOST_TT_FORBIDDEN_IF
#endif
|
cawka/packaging-ndn-cpp
|
include/ndnboost/type_traits/has_pre_increment.hpp
|
C++
|
bsd-3-clause
| 1,355
|
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
using NMFExamples.Pcm.Core;
using NMFExamples.Pcm.Core.Composition;
using NMFExamples.Pcm.Core.Entity;
using NMFExamples.Pcm.Parameter;
using NMFExamples.Pcm.Repository;
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using global::System.Collections;
using global::System.Collections.Generic;
using global::System.Collections.ObjectModel;
using global::System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
namespace NMFExamples.Pcm.Usagemodel
{
/// <summary>
/// The public interface for Stop
/// </summary>
[DefaultImplementationTypeAttribute(typeof(Stop))]
[XmlDefaultImplementationTypeAttribute(typeof(Stop))]
public interface IStop : IModelElement, IAbstractUserAction
{
}
}
|
NMFCode/NMF
|
IntegrationTests/ComponentBasedSoftwareArchitectures/Pcm/Usagemodel/IStop.cs
|
C#
|
bsd-3-clause
| 1,471
|
/**
* Pimcore
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.pimcore.org/license
*
* @copyright Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license New BSD License
*/
pimcore.registerNS("pimcore.report.custom.report");
pimcore.report.custom.report = Class.create(pimcore.report.abstract, {
drillDownFilters: {},
drillDownStores: [],
matchType: function (type) {
var types = ["global"];
if (pimcore.report.abstract.prototype.matchTypeValidate(type, types)) {
return true;
}
return false;
},
getName: function () {
return "overview";
},
getIconCls: function () {
return "pimcore_icon_sql";
},
initGrid: function (data) {
this.drillDownFilters = {};
this.drillDownStores = [];
var storeFields = [];
var gridColums = [];
var colConfig;
var gridColConfig = {};
var filters = [];
var drillDownFilterDefinitions = [];
this.columnLabels = {};
this.gridfilters = {};
for(var f=0; f<data.columnConfiguration.length; f++) {
colConfig = data.columnConfiguration[f];
storeFields.push(colConfig["name"]);
this.columnLabels[colConfig["name"]] = colConfig["label"] ? ts(colConfig["label"]) : ts(colConfig["name"]);
gridColConfig = {
header: colConfig["label"] ? ts(colConfig["label"]) : ts(colConfig["name"]),
hidden: !colConfig["display"],
sortable: colConfig["order"],
dataIndex: colConfig["name"]
};
if(colConfig["width"]) {
gridColConfig["width"] = intval(colConfig["width"]);
}
if(colConfig["filter"]) {
gridColConfig["filter"] = colConfig["filter"];
this.gridfilters[colConfig["name"]] = colConfig["filter"];
}
if(colConfig["filter_drilldown"] == 'only_filter' || colConfig["filter_drilldown"] == 'filter_and_show') {
drillDownFilterDefinitions.push(colConfig);
}
if(colConfig["filter_drilldown"] != 'only_filter') {
gridColums.push(gridColConfig);
}
}
var itemsPerPage = 40;
var url = '/admin/reports/custom-report/data?';
this.store = pimcore.helpers.grid.buildDefaultStore(
url, storeFields, itemsPerPage
);
this.pagingtoolbar = pimcore.helpers.grid.buildDefaultPagingToolbar(this.store, itemsPerPage);
var proxy = this.store.getProxy();
proxy.extraParams.name = this.config["name"];
this.store.addListener('load', function() {
var filterData = this.store.getFilters().items;
if(this.chartStore) {
this.chartStore.load({
params: {
name: this.config["name"],
filter: proxy.encodeFilters(filterData)
}
});
}
for(var j = 0; j < this.drillDownStores.length; j++) {
if(this.drillDownStores[j].notReload) {
//to prevent reopening of combo box
this.drillDownStores[j].notReload = false;
} else {
this.drillDownStores[j].load({
params: {
filter: proxy.encodeFilters(filterData)
}
});
}
}
}.bind(this));
var topBar = this.buildTopBar(drillDownFilterDefinitions);
topBar.push("->");
topBar.push({
xtype: "button",
text: t("export_csv"),
iconCls: "pimcore_icon_export",
handler: function () {
var query = "";
var filterData = this.store.getFilters().items;
if(filterData.length > 0) {
query = "filter=" + encodeURIComponent(proxy.encodeFilters(filterData));
} else {
query = "filter=";
}
query += "&extjs6=1&name=" + this.config.name;
if(this.drillDownFilters) {
var fieldnames = Object.getOwnPropertyNames(this.drillDownFilters);
for(var j = 0; j < fieldnames.length; j++) {
if(this.drillDownFilters[fieldnames[j]] !== null) {
query += "&" + 'drillDownFilters[' + fieldnames[j] + ']='
+ this.drillDownFilters[fieldnames[j]];
}
}
}
var downloadUrl = "/admin/reports/custom-report/download-csv?" + query;
pimcore.helpers.download(downloadUrl);
}.bind(this)
});
this.grid = new Ext.grid.GridPanel({
region: "center",
store: this.store,
bbar: this.pagingtoolbar,
columns: gridColums,
columnLines: true,
plugins: ['gridfilters'],
stripeRows: true,
trackMouseOver: true,
viewConfig: {
forceFit: false
},
tbar: topBar
});
return this.grid;
},
buildTopBar: function(drillDownFilterDefinitions) {
var drillDownFilterComboboxes = [];
for(var i = 0; i < drillDownFilterDefinitions.length; i++) {
drillDownFilterComboboxes.push({
xtype: 'label',
text: drillDownFilterDefinitions[i]["label"] ? ts(drillDownFilterDefinitions[i]["label"])
: ts(drillDownFilterDefinitions[i]["name"]),
style: 'padding-right: 5px'
});
var drillDownStore = pimcore.helpers.grid.buildDefaultStore(
'/admin/reports/custom-report/drill-down-options/?',
['value'],
400
);
var proxy = drillDownStore.getProxy();
proxy.extraParams.name = this.config["name"];
proxy.extraParams.field = drillDownFilterDefinitions[i]["name"];
this.drillDownStores.push(drillDownStore);
drillDownFilterComboboxes.push({
xtype: 'combo',
forceSelection: true,
triggerAction: 'all',
store: drillDownStore,
listeners: {
select: function(fieldname, combo, record, index) {
var value = combo.getValue();
this.drillDownFilters[fieldname] = value;
var proxy = this.store.getProxy();
proxy.extraParams['drillDownFilters[' + fieldname + ']'] = value;
if(this.chartStore) {
var chartProxy = this.chartStore.getProxy();
chartProxy.extraParams['drillDownFilters[' + fieldname + ']'] = value;
}
for(var j = 0; j < this.drillDownStores.length; j++) {
if(this.drillDownStores[j] != combo.getStore()) {
var drillDownProxy = this.drillDownStores[j].getProxy();
drillDownProxy.extraParams['drillDownFilters[' + fieldname + ']'] = value;
} else {
this.drillDownStores[j].notReload = true;
}
}
this.store.reload();
}.bind(this, drillDownFilterDefinitions[i]["name"])
},
valueField: 'value',
displayField: 'value'
});
if(i < drillDownFilterDefinitions.length-1) {
drillDownFilterComboboxes.push('-');
}
}
return drillDownFilterComboboxes;
},
chartColors: [
0x01841c,
0x3D32FF,
0xFF1000,
0xFFEE00,
0x00FF21,
0x7F92FF,
0xFFD800
],
getChart: function(initData) {
if(initData) {
this.chartInitData = initData;
}
var data = this.chartInitData;
if(data.chartType == 'line' || data.chartType == 'bar') {
var storeFields = [];
storeFields.push(data.xAxis);
for(var i = 0; i < data.yAxis.length; i++) {
storeFields.push(data.yAxis[i]);
}
this.chartStore = pimcore.helpers.grid.buildDefaultStore(
'/admin/reports/custom-report/chart/?',
storeFields,
400000000
);
var proxy = this.chartStore.getProxy();
proxy.extraParams.name = this.config["name"];
var series = [];
for(var i = 0; i < data.yAxis.length; i++) {
var yAxis = data.yAxis[i];
series.push({
displayName: this.columnLabels[data.yAxis[i]],
type: (data.chartType == 'line' ? 'line' : 'bar'),
xField: data.xAxis,
yField: yAxis,
marker: {
radius: 4
},
highlight: true,
tooltip: {
trackMouse: true,
renderer: function (tooltip, record, item) {
tooltip.setHtml(record.get(data.xAxis) + ': ' + record.get(yAxis));
}
}
});
}
var chart = Ext.create('Ext.chart.CartesianChart', {
store: this.chartStore,
width: '100%',
height: 350,
insetPadding: 5,
innerPadding: 10,
legend: {
docked: 'bottom'
},
interactions: [
'itemhighlight',
{
type: 'panzoom',
zoomOnPanGesture: true
}
],
axes: [
{
type: 'numeric',
fields: data.yAxis,
position: 'left',
grid: true
},{
type: 'category',
fields: data.xAxis,
position: 'bottom'
}
],
series: series
});
} else if(data.chartType == 'pie') {
this.chartStore = pimcore.helpers.grid.buildDefaultStore(
'/admin/reports/custom-report/chart/?',
[data.pieLabelColumn, data.pieColumn],
400000000
);
var proxy = this.chartStore.getProxy();
proxy.extraParams.name = this.config["name"];
var chart = Ext.create('Ext.chart.PolarChart', {
xtype: "polar",
store: this.chartStore,
theme: 'default-gradients',
width: '100%',
height: 350,
innerPadding: 10,
legend: {
docked: 'right'
},
interactions: ['rotate'],
series: [{
type: 'pie',
xField: data.pieColumn,
highlight: true,
tooltip: {
trackMouse: true,
renderer: function (tooltip, record, item) {
tooltip.setHtml(record.get(data.pieLabelColumn) + ': ' + record.get(data.pieColumn) + '%');
}
}
}]
});
//this is needed to display correct data in legend when no label is defined
//label cannot be defined, because there is a bug when reloading chartstore with another amount of data entries
var series = chart.getSeries()[0];
series.provideLegendInfo = function (target) {
var me = this,
store = me.getStore();
console.log("hello");
if (store) {
var items = store.getData().items,
labelField = data.pieLabelColumn,
xField = me.getXField(),
hidden = me.getHidden(),
i, style, fill;
for (i = 0; i < items.length; i++) {
style = me.getStyleByIndex(i);
fill = style.fillStyle;
if (Ext.isObject(fill)) {
fill = fill.stops && fill.stops[0].color;
}
target.push({
name: labelField ? String(items[i].get(labelField)) : xField + ' ' + i,
mark: fill || style.strokeStyle || 'black',
disabled: hidden[i],
series: me.getId(),
index: i
});
}
}
};
}
return chart;
},
getChartPanel: function(data) {
this.chartPanel = new Ext.Panel({
region: "north",
height: 350,
border: false,
items: [this.getChart(data)]
});
return this.chartPanel;
},
getPanel: function () {
if(!this.panel) {
this.panel = new Ext.Panel({
title: this.config["niceName"],
layout: "fit",
border: false,
items: []
});
Ext.Ajax.request({
url: "/admin/reports/custom-report/get",
params: {
name: this.config.name
},
success: function (response) {
var data = Ext.decode(response.responseText);
var grid = this.initGrid(data);
var items = [];
if(data.chartType) {
var chartPanel = this.getChartPanel(data);
if(chartPanel) {
items.push(chartPanel);
}
}
items.push(grid);
var subPanel = new Ext.Panel({
layout: "border",
border: false,
items: items
});
this.panel.add(subPanel);
this.panel.updateLayout();
}.bind(this)
});
}
return this.panel;
}
});
pimcore.registerNS("pimcore.report.custom.reportplugin");
pimcore.report.custom.reportplugin = Class.create(pimcore.plugin.admin, {
getClassName: function() {
return "pimcore.report.custom.reportplugin";
},
initialize: function() {
pimcore.plugin.broker.registerPlugin(this);
},
pimcoreReady: function (params,broker){
var user = pimcore.globalmanager.get("user");
if(user.isAllowed("reports")){
// get available reports
Ext.Ajax.request({
url: "/admin/reports/custom-report/get-report-config",
success: function (response) {
var res = Ext.decode(response.responseText);
var report;
if(res.success && res.reports && res.reports.length > 0) {
for (var i=0; i<res.reports.length; i++) {
report = res.reports[i];
// set some defaults
if(!report["group"]) {
report["group"] = "custom_reports"
}
if(!report["niceName"]) {
report["niceName"] = report["name"]
}
if(!report["iconClass"]) {
report["iconClass"] = "pimcore_icon_sql";
}
if(!report["groupIconClass"]) {
report["groupIconClass"] = "pimcore_icon_sql";
}
pimcore.report.broker.addGroup(report["group"], report["group"], report["groupIconClass"]);
pimcore.report.broker.addReport(pimcore.report.custom.report, report["group"], {
name: report["name"],
text: report["niceName"],
niceName: report["niceName"],
iconCls: report["iconClass"]
});
// add the report directly into the reports menu in "extras" -> main menu
if(report["menuShortcut"]) {
try {
var toolbar = pimcore.globalmanager.get("layout_toolbar");
if(toolbar["marketingMenu"]) {
toolbar["marketingMenu"].add({
text: report["niceName"],
iconCls: report["iconClass"],
handler: function (report) {
toolbar.showReports(pimcore.report.custom.report, {
name: report["name"],
text: report["niceName"],
niceName: report["niceName"],
iconCls: report["iconClass"]
});
}.bind(this, report)
});
}
} catch (e) {
console.log(e);
}
}
}
}
}
});
}
}
});
(function() {
new pimcore.report.custom.reportplugin();
})();
|
h4rdc0m/pimcore
|
pimcore/static6/js/pimcore/report/custom/report.js
|
JavaScript
|
bsd-3-clause
| 18,963
|
/*
Copyright (c) 2012-2015, The Saffire Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Saffire Group the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __OBJECT_STRING_H__
#define __OBJECT_STRING_H__
#include <saffire/objects/object.h>
#include <saffire/general/string.h>
// Allocate string objects
#define STR02OBJ(mystr) object_alloc_instance(Object_String, 2, strlen(mystr), mystr)
#define STR2OBJ(mystr) object_alloc_instance(Object_String, 1, mystr)
// Return a zero-terminated string
#define RETURN_STRING_FROM_CHAR(s) RETURN_OBJECT(STR02OBJ(s))
// Return binary safe string
#define RETURN_STRING_FROM_BINSAFE_CHAR(l, s) RETURN_OBJECT(object_alloc_instance(Object_String, 2, l, s))
#define RETURN_STRING(s) RETURN_OBJECT(STR2OBJ(s))
// Returns value inside the string object's t_string
#define STROBJ2CHAR0(obj) ((((t_string_object *)obj)->data.value)->val)
// Returns length inside the string object's t_string
#define STROBJ2CHAR0LEN(obj) ((((t_string_object *)obj)->data.value)->len)
typedef struct {
t_string *value; // string value
md5_byte_t hash[16]; // (MD5) hash of the actual string
int needs_hashing; // 1 : string needs hashing, 0 : hash done
int iter; // Simple iteration index on the characters
char *locale; // Locale
} t_string_object_data;
typedef struct {
SAFFIRE_OBJECT_HEADER
t_string_object_data data;
SAFFIRE_OBJECT_FOOTER
} t_string_object;
t_string_object Object_String_struct;
#define Object_String (t_object *)&Object_String_struct
void object_string_init(void);
void object_string_fini(void);
int object_string_hash_compare(t_string_object *s1, t_string_object *s2);
int object_string_compare(t_string_object *s1, t_string_object *s2);
#endif
|
Drarok/saffire
|
include/saffire/objects/string.h
|
C
|
bsd-3-clause
| 3,433
|
$(document).ready(function() {
$(".range_date_field").datepicker({
showOtherMonths: true,
selectOtherMonths: true,
changeMonth: true,
changeYear: true,
minDate: "-10Y",
maxDate: "+2Y",
dateFormat: "dd/mm/yy"
});
$("input[type=submit]").button();
$("th.persona").parent().css("background-color", "lightpink");
$("th.assessore").parent().css("background-color", "lightblue");
$("#result_list tr:last").prepend(
"<th colspan='" + ($("#result_list tr:first").children().length -
$("#result_list tr:last").children().length) +"'>Totali:</th>");
$("#result_list tr:last").children().css("padding-top", "20px");
});
|
simodalla/pympa-affarigenerali
|
pympa_affarigenerali/static/affarigenerali/js/riepilogo_presenze.js
|
JavaScript
|
bsd-3-clause
| 713
|
var gulp = require('gulp');
gulp.task('default', function () {
// place code for your default task here
});
|
rlvillacarlos/nocaptcha
|
public/js/nocaptchajs/gulpfile.js
|
JavaScript
|
bsd-3-clause
| 113
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_67a.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.string.label.xml
Template File: sources-sink-67a.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using new[] and set data pointer to a small buffer
* GoodSource: Allocate using new[] and set data pointer to a large buffer
* Sinks: snprintf
* BadSink : Copy string to data using snprintf
* Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define SNPRINTF _snwprintf
#else
#define SNPRINTF snprintf
#endif
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_67
{
typedef struct _structType
{
wchar_t * structFirst;
} structType;
#ifndef OMITBAD
/* bad function declaration */
void badSink(structType myStruct);
void bad()
{
wchar_t * data;
structType myStruct;
data = NULL;
/* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */
data = new wchar_t[50];
data[0] = L'\0'; /* null terminate */
myStruct.structFirst = data;
badSink(myStruct);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(structType myStruct);
static void goodG2B()
{
wchar_t * data;
structType myStruct;
data = NULL;
/* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = new wchar_t[100];
data[0] = L'\0'; /* null terminate */
myStruct.structFirst = data;
goodG2BSink(myStruct);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_67; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
JianpingZeng/xcc
|
xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s04/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_snprintf_67a.cpp
|
C++
|
bsd-3-clause
| 2,804
|
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban
// =============================================================================
//
// Torsion-bar suspension system using linear dampers constructed with data from
// file (JSON format)
//
// =============================================================================
#include "chrono_vehicle/tracked_vehicle/suspension/LinearDamperRWAssembly.h"
#include "chrono_vehicle/ChVehicleModelData.h"
#include "chrono_vehicle/utils/ChUtilsJSON.h"
using namespace rapidjson;
namespace chrono {
namespace vehicle {
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
LinearDamperRWAssembly::LinearDamperRWAssembly(const std::string& filename, bool has_shock)
: ChLinearDamperRWAssembly("", has_shock), m_spring_torqueCB(nullptr), m_shock_forceCB(nullptr) {
Document d; ReadFileJSON(filename, d);
if (d.IsNull())
return;
Create(d);
GetLog() << "Loaded JSON: " << filename.c_str() << "\n";
}
LinearDamperRWAssembly::LinearDamperRWAssembly(const rapidjson::Document& d, bool has_shock)
: ChLinearDamperRWAssembly("", has_shock), m_spring_torqueCB(nullptr), m_shock_forceCB(nullptr) {
Create(d);
}
LinearDamperRWAssembly::~LinearDamperRWAssembly() {}
void LinearDamperRWAssembly::Create(const rapidjson::Document& d) {
// Invoke base class method.
ChPart::Create(d);
// Read suspension arm data
assert(d.HasMember("Suspension Arm"));
assert(d["Suspension Arm"].IsObject());
m_arm_mass = d["Suspension Arm"]["Mass"].GetDouble();
m_points[ARM] = ReadVectorJSON(d["Suspension Arm"]["COM"]);
m_arm_inertia = ReadVectorJSON(d["Suspension Arm"]["Inertia"]);
m_points[ARM_CHASSIS] = ReadVectorJSON(d["Suspension Arm"]["Location Chassis"]);
m_points[ARM_WHEEL] = ReadVectorJSON(d["Suspension Arm"]["Location Wheel"]);
m_arm_radius = d["Suspension Arm"]["Radius"].GetDouble();
// Read data for torsional spring
assert(d.HasMember("Torsional Spring"));
assert(d["Torsional Spring"].IsObject());
double torsion_a0 = d["Torsional Spring"]["Free Angle"].GetDouble();
double torsion_k = d["Torsional Spring"]["Spring Constant"].GetDouble();
double torsion_c = d["Torsional Spring"]["Damping Coefficient"].GetDouble();
double torsion_t = d["Torsional Spring"]["Preload"].GetDouble();
m_spring_torqueCB = chrono_types::make_shared<LinearSpringDamperActuatorTorque>(torsion_k, torsion_c, torsion_t, torsion_a0);
// Read linear shock data
assert(d.HasMember("Damper"));
m_points[SHOCK_C] = ReadVectorJSON(d["Damper"]["Location Chassis"]);
m_points[SHOCK_A] = ReadVectorJSON(d["Damper"]["Location Arm"]);
double shock_c = d["Damper"]["Damping Coefficient"].GetDouble();
m_shock_forceCB = chrono_types::make_shared<LinearDamperForce>(shock_c);
// Create the associated road-wheel
assert(d.HasMember("Road Wheel Input File"));
std::string file_name = d["Road Wheel Input File"].GetString();
m_road_wheel = ReadRoadWheelJSON(vehicle::GetDataFile(file_name));
}
} // end namespace vehicle
} // end namespace chrono
|
projectchrono/chrono
|
src/chrono_vehicle/tracked_vehicle/suspension/LinearDamperRWAssembly.cpp
|
C++
|
bsd-3-clause
| 3,663
|
\catcode`\#=12
\def\versiontag/{#2.60}%
\def\versiondate/{Thu Aug 8 14:53:26 PDT 1985}%
\catcode`\#=6
\tell{Version \versiontag/ of \versiondate/}
|
dscho/nmh
|
docs/historical/mh-6.8.5/papers/trusted/version.tex
|
TeX
|
bsd-3-clause
| 147
|
#include "compiler.h"
#include "dosio.h"
#include "pccore.h"
#include "iocore.h"
#include "fddfile.h"
#include "fdd_xdf.h"
static const _XDFINFO supportxdf[] = {
#if 0
// 256
{0, 154, 26, 1, DISKTYPE_2HD, 0},
// 512
{0, 154, 15, 2, DISKTYPE_2HD, 0},
#endif
#if 1
// 512
{0, 160, 15, 2, DISKTYPE_2HD, 0},
#endif
// 1024
{0, 154, 8, 3, DISKTYPE_2HD, 0},
// 1.44MB
{0, 160, 18, 2, DISKTYPE_2HD, 1},
};
typedef struct {
UINT8 dummy[4];
UINT8 fddtype[4];
UINT8 headersize[4];
UINT8 fddsize[4];
UINT8 sectorsize[4];
UINT8 sectors[4];
UINT8 surfaces[4];
UINT8 cylinders[4];
} FDIHDR;
BRESULT fddxdf_set(FDDFILE fdd, const OEMCHAR *fname, int ro) {
const _XDFINFO *xdf;
short attr;
FILEH fh;
UINT32 fdsize;
UINT size;
attr = file_attr(fname);
if (attr & 0x18) {
return(FAILURE);
}
fh = file_open(fname);
if (fh == FILEH_INVALID) {
return(FAILURE);
}
fdsize = file_getsize(fh);
file_close(fh);
xdf = supportxdf;
while(xdf < (supportxdf + NELEMENTS(supportxdf))) {
size = xdf->tracks;
size *= xdf->sectors;
size <<= (7 + xdf->n);
if (size == fdsize) {
fdd->type = DISKTYPE_BETA;
fdd->protect = ((attr & 1) || (ro))?TRUE:FALSE;
fdd->inf.xdf = *xdf;
return(SUCCESS);
}
xdf++;
}
return(FAILURE);
}
// ±Á»èε½èµÄ
BRESULT fddxdf_setfdi(FDDFILE fdd, const OEMCHAR *fname, int ro) {
short attr;
FILEH fh;
UINT32 fdsize;
UINT r;
FDIHDR fdi;
UINT32 fddtype;
UINT32 headersize;
UINT32 size;
UINT32 sectors;
UINT32 surfaces;
UINT32 cylinders;
UINT8 n;
UINT8 disktype;
UINT8 rpm;
attr = file_attr(fname);
if (attr & 0x18) {
return(FAILURE);
}
fdsize = 0;
r = 0;
fh = file_open_rb(fname);
if (fh != FILEH_INVALID) {
fdsize = file_getsize(fh);
r = file_read(fh, &fdi, sizeof(fdi));
file_close(fh);
}
if (r != sizeof(fdi)) {
return(FAILURE);
}
fddtype = LOADINTELDWORD(fdi.fddtype);
headersize = LOADINTELDWORD(fdi.headersize);
size = LOADINTELDWORD(fdi.sectorsize);
sectors = LOADINTELDWORD(fdi.sectors);
surfaces = LOADINTELDWORD(fdi.surfaces);
cylinders = LOADINTELDWORD(fdi.cylinders);
if (((size & (size - 1)) != 0) || (!(size & 0x7f80)) ||
(sectors == 0) || (sectors >= 256) ||
(surfaces != 2) ||
(cylinders == 0) || (cylinders >= 128)) {
return(FAILURE);
}
if (fdsize != (headersize + (size * sectors * surfaces * cylinders))) {
return(FAILURE);
}
size >>= 8;
n = 0;
while(size) {
size >>= 1;
n++;
}
disktype = DISKTYPE_2HD;
rpm = 0;
switch(fddtype & 0xf0) {
case 0x10: // 1MB/640KB - 2DD
case 0x70: // 640KB - 2DD
case 0xf0:
disktype = DISKTYPE_2DD;
break;
case 0x30: // 1.44MB - 2HD
case 0xb0:
rpm = 1;
break;
case 0x50: // 320KB - 2D
case 0xd0: //
disktype = DISKTYPE_2D;
break;
case 0x90: // 2HD
break;
default:
return(FAILURE);
}
fdd->type = DISKTYPE_BETA;
fdd->protect = ((attr & 1) || (ro))?TRUE:FALSE;
fdd->inf.xdf.headersize = headersize;
fdd->inf.xdf.tracks = (UINT8)(cylinders * 2);
fdd->inf.xdf.sectors = (UINT8)sectors;
fdd->inf.xdf.n = n;
fdd->inf.xdf.disktype = disktype;
fdd->inf.xdf.rpm = rpm;
return(SUCCESS);
}
BRESULT fddxdf_eject(FDDFILE fdd) {
fdd->fname[0] = '\0';
fdd->type = DISKTYPE_NOTREADY;
return(SUCCESS);
}
BRESULT fddxdf_diskaccess(FDDFILE fdd) {
if ((fdd->type != DISKTYPE_BETA) ||
(CTRL_FDMEDIA != fdd->inf.xdf.disktype)) {
return(FAILURE);
}
return(SUCCESS);
}
BRESULT fddxdf_seek(FDDFILE fdd) {
if ((fdd->type != DISKTYPE_BETA) ||
(CTRL_FDMEDIA != fdd->inf.xdf.disktype) ||
(fdc.rpm[fdc.us] != fdd->inf.xdf.rpm) ||
(fdc.ncn >= (fdd->inf.xdf.tracks >> 1))) {
return(FAILURE);
}
return(SUCCESS);
}
BRESULT fddxdf_seeksector(FDDFILE fdd) {
if ((fdd->type != DISKTYPE_BETA) ||
(CTRL_FDMEDIA != fdd->inf.xdf.disktype) ||
(fdc.rpm[fdc.us] != fdd->inf.xdf.rpm) ||
(fdc.treg[fdc.us] >= (fdd->inf.xdf.tracks >> 1))) {
fddlasterror = 0xe0;
return(FAILURE);
}
if ((!fdc.R) || (fdc.R > fdd->inf.xdf.sectors)) {
fddlasterror = 0xc0;
return(FAILURE);
}
if ((fdc.mf != 0xff) && (fdc.mf != 0x40)) {
fddlasterror = 0xc0;
return(FAILURE);
}
return(SUCCESS);
}
BRESULT fddxdf_read(FDDFILE fdd) {
FILEH hdl;
long seekp;
UINT secsize;
fddlasterror = 0x00;
if (fddxdf_seeksector(fdd)) {
return(FAILURE);
}
if (fdc.N != fdd->inf.xdf.n) {
fddlasterror = 0xc0;
return(FAILURE);
}
seekp = (fdc.treg[fdc.us] << 1) + fdc.hd;
seekp *= fdd->inf.xdf.sectors;
seekp += fdc.R - 1;
seekp <<= (7 + fdd->inf.xdf.n);
seekp += fdd->inf.xdf.headersize;
secsize = 128 << fdd->inf.xdf.n;
hdl = file_open_rb(fdd->fname);
if (hdl == FILEH_INVALID) {
fddlasterror = 0xe0;
return(FAILURE);
}
if ((file_seek(hdl, seekp, FSEEK_SET) != seekp) ||
(file_read(hdl, fdc.buf, secsize) != secsize)) {
file_close(hdl);
fddlasterror = 0xe0;
return(FAILURE);
}
file_close(hdl);
fdc.bufcnt = secsize;
fddlasterror = 0x00;
return(SUCCESS);
}
BRESULT fddxdf_write(FDDFILE fdd) {
FILEH hdl;
long seekp;
UINT secsize;
fddlasterror = 0x00;
if (fddxdf_seeksector(fdd)) {
fddlasterror = 0xe0;
return(FAILURE);
}
if (fdd->protect) {
fddlasterror = 0x70;
return(FAILURE);
}
if (fdc.N != fdd->inf.xdf.n) {
fddlasterror = 0xc0;
return(FAILURE);
}
seekp = (fdc.treg[fdc.us] << 1) + fdc.hd;
seekp *= fdd->inf.xdf.sectors;
seekp += fdc.R - 1;
seekp <<= (7 + fdd->inf.xdf.n);
seekp += fdd->inf.xdf.headersize;
secsize = 128 << fdd->inf.xdf.n;
hdl = file_open(fdd->fname);
if (hdl == FILEH_INVALID) {
fddlasterror = 0xc0;
return(FAILURE);
}
if ((file_seek(hdl, seekp, FSEEK_SET) != seekp) ||
(file_write(hdl, fdc.buf, secsize) != secsize)) {
file_close(hdl);
fddlasterror = 0xc0;
return(FAILURE);
}
file_close(hdl);
fdc.bufcnt = secsize;
fddlasterror = 0x00;
return(SUCCESS);
}
BRESULT fddxdf_readid(FDDFILE fdd) {
fddlasterror = 0x00;
if ((!fdc.mf) ||
(fdc.rpm[fdc.us] != fdd->inf.xdf.rpm) ||
(fdc.crcn >= fdd->inf.xdf.sectors)) {
fddlasterror = 0xe0;
return(FAILURE);
}
fdc.C = fdc.treg[fdc.us];
fdc.H = fdc.hd;
fdc.R = ++fdc.crcn;
fdc.N = fdd->inf.xdf.n;
return(SUCCESS);
}
|
masaki-furuta/xnp2
|
src/fdd/fdd_xdf.c
|
C
|
bsd-3-clause
| 6,145
|
import os
import numpy as np
import pytest
from pandas import (
Categorical,
DatetimeIndex,
Interval,
IntervalIndex,
NaT,
Series,
TimedeltaIndex,
Timestamp,
cut,
date_range,
isna,
qcut,
timedelta_range,
)
from pandas.api.types import CategoricalDtype as CDT
from pandas.core.algorithms import quantile
import pandas.util.testing as tm
from pandas.tseries.offsets import Day, Nano
def test_qcut():
arr = np.random.randn(1000)
# We store the bins as Index that have been
# rounded to comparisons are a bit tricky.
labels, bins = qcut(arr, 4, retbins=True)
ex_bins = quantile(arr, [0, 0.25, 0.5, 0.75, 1.0])
result = labels.categories.left.values
assert np.allclose(result, ex_bins[:-1], atol=1e-2)
result = labels.categories.right.values
assert np.allclose(result, ex_bins[1:], atol=1e-2)
ex_levels = cut(arr, ex_bins, include_lowest=True)
tm.assert_categorical_equal(labels, ex_levels)
def test_qcut_bounds():
arr = np.random.randn(1000)
factor = qcut(arr, 10, labels=False)
assert len(np.unique(factor)) == 10
def test_qcut_specify_quantiles():
arr = np.random.randn(100)
factor = qcut(arr, [0, 0.25, 0.5, 0.75, 1.0])
expected = qcut(arr, 4)
tm.assert_categorical_equal(factor, expected)
def test_qcut_all_bins_same():
with pytest.raises(ValueError, match="edges.*unique"):
qcut([0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 3)
def test_qcut_include_lowest():
values = np.arange(10)
ii = qcut(values, 4)
ex_levels = IntervalIndex(
[
Interval(-0.001, 2.25),
Interval(2.25, 4.5),
Interval(4.5, 6.75),
Interval(6.75, 9),
]
)
tm.assert_index_equal(ii.categories, ex_levels)
def test_qcut_nas():
arr = np.random.randn(100)
arr[:20] = np.nan
result = qcut(arr, 4)
assert isna(result[:20]).all()
def test_qcut_index():
result = qcut([0, 2], 2)
intervals = [Interval(-0.001, 1), Interval(1, 2)]
expected = Categorical(intervals, ordered=True)
tm.assert_categorical_equal(result, expected)
def test_qcut_binning_issues(datapath):
# see gh-1978, gh-1979
cut_file = datapath(os.path.join("reshape", "data", "cut_data.csv"))
arr = np.loadtxt(cut_file)
result = qcut(arr, 20)
starts = []
ends = []
for lev in np.unique(result):
s = lev.left
e = lev.right
assert s != e
starts.append(float(s))
ends.append(float(e))
for (sp, sn), (ep, en) in zip(
zip(starts[:-1], starts[1:]), zip(ends[:-1], ends[1:])
):
assert sp < sn
assert ep < en
assert ep <= sn
def test_qcut_return_intervals():
ser = Series([0, 1, 2, 3, 4, 5, 6, 7, 8])
res = qcut(ser, [0, 0.333, 0.666, 1])
exp_levels = np.array(
[Interval(-0.001, 2.664), Interval(2.664, 5.328), Interval(5.328, 8)]
)
exp = Series(exp_levels.take([0, 0, 0, 1, 1, 1, 2, 2, 2])).astype(CDT(ordered=True))
tm.assert_series_equal(res, exp)
@pytest.mark.parametrize(
"kwargs,msg",
[
(dict(duplicates="drop"), None),
(dict(), "Bin edges must be unique"),
(dict(duplicates="raise"), "Bin edges must be unique"),
(dict(duplicates="foo"), "invalid value for 'duplicates' parameter"),
],
)
def test_qcut_duplicates_bin(kwargs, msg):
# see gh-7751
values = [0, 0, 0, 0, 1, 2, 3]
if msg is not None:
with pytest.raises(ValueError, match=msg):
qcut(values, 3, **kwargs)
else:
result = qcut(values, 3, **kwargs)
expected = IntervalIndex([Interval(-0.001, 1), Interval(1, 3)])
tm.assert_index_equal(result.categories, expected)
@pytest.mark.parametrize(
"data,start,end", [(9.0, 8.999, 9.0), (0.0, -0.001, 0.0), (-9.0, -9.001, -9.0)]
)
@pytest.mark.parametrize("length", [1, 2])
@pytest.mark.parametrize("labels", [None, False])
def test_single_quantile(data, start, end, length, labels):
# see gh-15431
ser = Series([data] * length)
result = qcut(ser, 1, labels=labels)
if labels is None:
intervals = IntervalIndex([Interval(start, end)] * length, closed="right")
expected = Series(intervals).astype(CDT(ordered=True))
else:
expected = Series([0] * length)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"ser",
[
Series(DatetimeIndex(["20180101", NaT, "20180103"])),
Series(TimedeltaIndex(["0 days", NaT, "2 days"])),
],
ids=lambda x: str(x.dtype),
)
def test_qcut_nat(ser):
# see gh-19768
intervals = IntervalIndex.from_tuples(
[(ser[0] - Nano(), ser[2] - Day()), np.nan, (ser[2] - Day(), ser[2])]
)
expected = Series(Categorical(intervals, ordered=True))
result = qcut(ser, 2)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("bins", [3, np.linspace(0, 1, 4)])
def test_datetime_tz_qcut(bins):
# see gh-19872
tz = "US/Eastern"
ser = Series(date_range("20130101", periods=3, tz=tz))
result = qcut(ser, bins)
expected = Series(
IntervalIndex(
[
Interval(
Timestamp("2012-12-31 23:59:59.999999999", tz=tz),
Timestamp("2013-01-01 16:00:00", tz=tz),
),
Interval(
Timestamp("2013-01-01 16:00:00", tz=tz),
Timestamp("2013-01-02 08:00:00", tz=tz),
),
Interval(
Timestamp("2013-01-02 08:00:00", tz=tz),
Timestamp("2013-01-03 00:00:00", tz=tz),
),
]
)
).astype(CDT(ordered=True))
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"arg,expected_bins",
[
[
timedelta_range("1day", periods=3),
TimedeltaIndex(["1 days", "2 days", "3 days"]),
],
[
date_range("20180101", periods=3),
DatetimeIndex(["2018-01-01", "2018-01-02", "2018-01-03"]),
],
],
)
def test_date_like_qcut_bins(arg, expected_bins):
# see gh-19891
ser = Series(arg)
result, result_bins = qcut(ser, 2, retbins=True)
tm.assert_index_equal(result_bins, expected_bins)
|
toobaz/pandas
|
pandas/tests/reshape/test_qcut.py
|
Python
|
bsd-3-clause
| 6,328
|
# -*- coding: utf-8 -*-
import csv
import json
from cStringIO import StringIO
from datetime import datetime
from django.conf import settings
from django.core import mail
from django.core.cache import cache
import mock
from pyquery import PyQuery as pq
from olympia import amo
from olympia.amo.tests import TestCase
from olympia.amo.tests import formset, initial
from olympia.access.models import Group, GroupUser
from olympia.addons.models import Addon, CompatOverride, CompatOverrideRange
from olympia.amo.urlresolvers import reverse
from olympia.amo.tests.test_helpers import get_image_path
from olympia.amo.utils import urlparams
from olympia.applications.models import AppVersion
from olympia.bandwagon.models import FeaturedCollection, MonthlyPick
from olympia.compat.cron import compatibility_report
from olympia.compat.models import CompatReport
from olympia.constants.base import VALIDATOR_SKELETON_RESULTS
from olympia.devhub.models import ActivityLog
from olympia.files.models import File, FileUpload
from olympia.stats.models import UpdateCount
from olympia.users.models import UserProfile
from olympia.users.utils import get_task_user
from olympia.versions.models import ApplicationsVersions, Version
from olympia.zadmin import forms, tasks
from olympia.zadmin.forms import DevMailerForm
from olympia.zadmin.models import (
EmailPreviewTopic, ValidationJob, ValidationResult)
from olympia.zadmin.tasks import updated_versions
from olympia.zadmin.views import find_files
class TestSiteEvents(TestCase):
fixtures = ['base/users', 'zadmin/tests/siteevents']
def setUp(self):
super(TestSiteEvents, self).setUp()
self.client.login(username='admin@mozilla.com', password='password')
def test_get(self):
url = reverse('zadmin.site_events')
response = self.client.get(url)
assert response.status_code == 200
events = response.context['events']
assert len(events) == 1
def test_add(self):
url = reverse('zadmin.site_events')
new_event = {
'event_type': 2,
'start': '2012-01-01',
'description': 'foo',
}
response = self.client.post(url, new_event, follow=True)
assert response.status_code == 200
events = response.context['events']
assert len(events) == 2
def test_edit(self):
url = reverse('zadmin.site_events', args=[1])
modified_event = {
'event_type': 2,
'start': '2012-01-01',
'description': 'bar',
}
response = self.client.post(url, modified_event, follow=True)
assert response.status_code == 200
events = response.context['events']
assert events[0].description == 'bar'
def test_delete(self):
url = reverse('zadmin.site_events.delete', args=[1])
response = self.client.get(url, follow=True)
assert response.status_code == 200
events = response.context['events']
assert len(events) == 0
class BulkValidationTest(TestCase):
fixtures = ['base/addon_3615', 'base/appversion', 'base/users']
def setUp(self):
super(BulkValidationTest, self).setUp()
assert self.client.login(username='admin@mozilla.com',
password='password')
self.addon = Addon.objects.get(pk=3615)
self.creator = UserProfile.objects.get(username='editor')
self.version = self.addon.get_version()
ApplicationsVersions.objects.filter(
application=amo.FIREFOX.id, version=self.version).update(
max=AppVersion.objects.get(application=1, version='3.7a1pre'))
self.application_version = self.version.apps.all()[0]
self.application = self.application_version.application
self.min = self.application_version.min
self.max = self.application_version.max
self.curr_max = self.appversion('3.7a1pre')
self.counter = 0
self.old_task_user = settings.TASK_USER_ID
settings.TASK_USER_ID = self.creator.id
def tearDown(self):
settings.TASK_USER_ID = self.old_task_user
super(BulkValidationTest, self).tearDown()
def appversion(self, version, application=amo.FIREFOX.id):
return AppVersion.objects.get(application=application,
version=version)
def create_job(self, **kwargs):
kw = dict(application=amo.FIREFOX.id,
curr_max_version=kwargs.pop('current', self.curr_max),
target_version=kwargs.pop('target',
self.appversion('3.7a3')),
creator=self.creator)
kw.update(kwargs)
return ValidationJob.objects.create(**kw)
def create_file(self, version=None, platform=amo.PLATFORM_ALL.id):
if not version:
version = self.version
return File.objects.create(version=version,
filename='file-%s' % self.counter,
platform=platform,
status=amo.STATUS_PUBLIC)
def create_result(self, job, f, **kwargs):
self.counter += 1
kw = dict(file=f,
validation='{}',
errors=0,
warnings=0,
notices=0,
validation_job=job,
task_error=None,
valid=0,
completed=datetime.now())
kw.update(kwargs)
return ValidationResult.objects.create(**kw)
def start_validation(self, new_max='3.7a3'):
self.new_max = self.appversion(new_max)
r = self.client.post(reverse('zadmin.start_validation'),
{'application': amo.FIREFOX.id,
'curr_max_version': self.curr_max.id,
'target_version': self.new_max.id,
'finish_email': 'fliggy@mozilla.com'},
follow=True)
assert r.status_code == 200
class TestBulkValidation(BulkValidationTest):
@mock.patch('olympia.zadmin.tasks.bulk_validate_file')
def test_start(self, bulk_validate_file):
new_max = self.appversion('3.7a3')
r = self.client.post(reverse('zadmin.start_validation'),
{'application': amo.FIREFOX.id,
'curr_max_version': self.curr_max.id,
'target_version': new_max.id,
'finish_email': 'fliggy@mozilla.com'},
follow=True)
self.assertNoFormErrors(r)
self.assert3xx(r, reverse('zadmin.validation'))
job = ValidationJob.objects.get()
assert job.application == amo.FIREFOX.id
assert job.curr_max_version.version == self.curr_max.version
assert job.target_version.version == new_max.version
assert job.finish_email == 'fliggy@mozilla.com'
assert job.completed is None
assert job.result_set.all().count() == len(self.version.all_files)
assert bulk_validate_file.delay.called
@mock.patch('olympia.zadmin.tasks.bulk_validate_file')
def test_ignore_user_disabled_addons(self, bulk_validate_file):
self.addon.update(disabled_by_user=True)
r = self.client.post(reverse('zadmin.start_validation'),
{'application': amo.FIREFOX.id,
'curr_max_version': self.curr_max.id,
'target_version': self.appversion('3.7a3').id,
'finish_email': 'fliggy@mozilla.com'},
follow=True)
self.assertNoFormErrors(r)
self.assert3xx(r, reverse('zadmin.validation'))
assert not bulk_validate_file.delay.called
@mock.patch('olympia.zadmin.tasks.bulk_validate_file')
def test_ignore_non_public_addons(self, bulk_validate_file):
target_ver = self.appversion('3.7a3').id
for status in (amo.STATUS_DISABLED, amo.STATUS_NULL,
amo.STATUS_DELETED):
self.addon.update(status=status)
r = self.client.post(reverse('zadmin.start_validation'),
{'application': amo.FIREFOX.id,
'curr_max_version': self.curr_max.id,
'target_version': target_ver,
'finish_email': 'fliggy@mozilla.com'},
follow=True)
self.assertNoFormErrors(r)
self.assert3xx(r, reverse('zadmin.validation'))
assert not bulk_validate_file.delay.called, (
'Addon with status %s should be ignored' % status)
@mock.patch('olympia.zadmin.tasks.bulk_validate_file')
def test_ignore_lang_packs(self, bulk_validate_file):
target_ver = self.appversion('3.7a3').id
self.addon.update(type=amo.ADDON_LPAPP)
r = self.client.post(reverse('zadmin.start_validation'),
{'application': amo.FIREFOX.id,
'curr_max_version': self.curr_max.id,
'target_version': target_ver,
'finish_email': 'fliggy@mozilla.com'},
follow=True)
self.assertNoFormErrors(r)
self.assert3xx(r, reverse('zadmin.validation'))
assert not bulk_validate_file.delay.called, (
'Lang pack addons should be ignored')
@mock.patch('olympia.zadmin.tasks.bulk_validate_file')
def test_ignore_themes(self, bulk_validate_file):
target_ver = self.appversion('3.7a3').id
self.addon.update(type=amo.ADDON_THEME)
self.client.post(reverse('zadmin.start_validation'),
{'application': amo.FIREFOX.id,
'curr_max_version': self.curr_max.id,
'target_version': target_ver,
'finish_email': 'fliggy@mozilla.com'})
assert not bulk_validate_file.delay.called, (
'Theme addons should be ignored')
@mock.patch('olympia.zadmin.tasks.bulk_validate_file')
def test_validate_all_non_disabled_addons(self, bulk_validate_file):
target_ver = self.appversion('3.7a3').id
bulk_validate_file.delay.called = False
self.addon.update(status=amo.STATUS_PUBLIC)
r = self.client.post(reverse('zadmin.start_validation'),
{'application': amo.FIREFOX.id,
'curr_max_version': self.curr_max.id,
'target_version': target_ver,
'finish_email': 'fliggy@mozilla.com'},
follow=True)
self.assertNoFormErrors(r)
self.assert3xx(r, reverse('zadmin.validation'))
assert bulk_validate_file.delay.called, (
'Addon with status %s should be validated' % self.addon.status)
def test_grid(self):
job = self.create_job()
for res in (dict(errors=0), dict(errors=1)):
self.create_result(job, self.create_file(), **res)
r = self.client.get(reverse('zadmin.validation'))
assert r.status_code == 200
doc = pq(r.content)
assert doc('table tr td').eq(0).text() == str(job.pk) # ID
assert doc('table tr td').eq(3).text() == 'Firefox' # Application
assert doc('table tr td').eq(4).text() == self.curr_max.version
assert doc('table tr td').eq(5).text() == '3.7a3'
assert doc('table tr td').eq(6).text() == '2' # tested
assert doc('table tr td').eq(7).text() == '1' # failing
assert doc('table tr td').eq(8).text()[0] == '1' # passing
assert doc('table tr td').eq(9).text() == '0' # exceptions
def test_application_versions_json(self):
r = self.client.post(reverse('zadmin.application_versions_json'),
{'application': amo.FIREFOX.id})
assert r.status_code == 200
data = json.loads(r.content)
empty = True
for id, ver in data['choices']:
empty = False
assert AppVersion.objects.get(pk=id).version == ver
assert not empty, "Unexpected: %r" % data
def test_job_status(self):
job = self.create_job()
def get_data():
self.create_result(job, self.create_file(), **{})
r = self.client.post(reverse('zadmin.job_status'),
{'job_ids': json.dumps([job.pk])})
assert r.status_code == 200
data = json.loads(r.content)[str(job.pk)]
return data
data = get_data()
assert data['completed'] == 1
assert data['total'] == 1
assert data['percent_complete'] == '100'
assert data['job_id'] == job.pk
assert data['completed_timestamp'] == ''
job.update(completed=datetime.now())
data = get_data()
assert data['completed_timestamp'] != '', (
'Unexpected: %s' % data['completed_timestamp'])
class TestBulkUpdate(BulkValidationTest):
def setUp(self):
super(TestBulkUpdate, self).setUp()
self.job = self.create_job(completed=datetime.now())
self.update_url = reverse('zadmin.notify', args=[self.job.pk])
self.list_url = reverse('zadmin.validation')
self.data = {'text': '{{ APPLICATION }} {{ VERSION }}',
'subject': '..'}
self.version_one = Version.objects.create(addon=self.addon)
self.version_two = Version.objects.create(addon=self.addon)
appver = AppVersion.objects.get(application=1, version='3.7a1pre')
for v in self.version_one, self.version_two:
ApplicationsVersions.objects.create(
application=amo.FIREFOX.id, version=v,
min=appver, max=appver)
def test_no_update_link(self):
self.create_result(self.job, self.create_file(), **{})
r = self.client.get(self.list_url)
doc = pq(r.content)
assert doc('table tr td a.set-max-version').text() == (
'Notify and set max versions')
def test_update_link(self):
self.create_result(self.job, self.create_file(), **{'valid': 1})
r = self.client.get(self.list_url)
doc = pq(r.content)
assert doc('table tr td a.set-max-version').text() == (
'Notify and set max versions')
def test_update_url(self):
self.create_result(self.job, self.create_file(), **{'valid': 1})
r = self.client.get(self.list_url)
doc = pq(r.content)
assert doc('table tr td a.set-max-version').attr('data-job-url') == (
self.update_url)
def test_update_anonymous(self):
self.client.logout()
r = self.client.post(self.update_url)
assert r.status_code == 302
def test_version_pks(self):
for version in [self.version_one, self.version_two]:
for x in range(0, 3):
self.create_result(self.job, self.create_file(version))
assert sorted(updated_versions(self.job)) == (
[self.version_one.pk, self.version_two.pk])
def test_update_passing_only(self):
self.create_result(self.job, self.create_file(self.version_one))
self.create_result(self.job, self.create_file(self.version_two),
errors=1)
assert sorted(updated_versions(self.job)) == (
[self.version_one.pk])
def test_update_pks(self):
self.create_result(self.job, self.create_file(self.version))
r = self.client.post(self.update_url, self.data)
assert r.status_code == 302
assert self.version.apps.all()[0].max == self.job.target_version
def test_update_unclean_pks(self):
self.create_result(self.job, self.create_file(self.version))
self.create_result(self.job, self.create_file(self.version),
errors=1)
r = self.client.post(self.update_url, self.data)
assert r.status_code == 302
assert self.version.apps.all()[0].max == self.job.curr_max_version
def test_update_pks_logs(self):
self.create_result(self.job, self.create_file(self.version))
assert ActivityLog.objects.for_addons(self.addon).count() == 0
self.client.post(self.update_url, self.data)
upd = amo.LOG.MAX_APPVERSION_UPDATED.id
logs = ActivityLog.objects.for_addons(self.addon).filter(action=upd)
assert logs.count() == 1
assert logs[0].user == get_task_user()
def test_update_wrong_version(self):
self.create_result(self.job, self.create_file(self.version))
av = self.version.apps.all()[0]
av.max = self.appversion('3.6')
av.save()
self.client.post(self.update_url, self.data)
assert self.version.apps.all()[0].max == self.appversion('3.6')
def test_update_all_within_range(self):
self.create_result(self.job, self.create_file(self.version))
# Create an appversion in between current and target.
av = self.version.apps.all()[0]
av.max = self.appversion('3.7a2')
av.save()
self.client.post(self.update_url, self.data)
assert self.version.apps.all()[0].max == self.appversion('3.7a3')
def test_version_comparison(self):
# regression test for bug 691984
job = self.create_job(completed=datetime.now(),
current=self.appversion('3.0.9'),
target=self.appversion('3.5'))
# .* was not sorting right
self.version.apps.all().update(max=self.appversion('3.0.*'))
self.create_result(job, self.create_file(self.version))
self.client.post(reverse('zadmin.notify', args=[job.pk]),
self.data)
assert self.version.apps.all()[0].max == self.appversion('3.5')
def test_update_different_app(self):
self.create_result(self.job, self.create_file(self.version))
target = self.version.apps.all()[0]
target.application = amo.FIREFOX.id
target.save()
assert self.version.apps.all()[0].max == self.curr_max
def test_update_twice(self):
self.create_result(self.job, self.create_file(self.version))
self.client.post(self.update_url, self.data)
assert self.version.apps.all()[0].max == self.job.target_version
now = self.version.modified
self.client.post(self.update_url, self.data)
assert self.version.modified == now
def test_update_notify(self):
self.create_result(self.job, self.create_file(self.version))
self.client.post(self.update_url, self.data)
assert len(mail.outbox) == 1
def test_update_subject(self):
data = self.data.copy()
data['subject'] = '{{ PASSING_ADDONS.0.name }}'
f = self.create_file(self.version)
self.create_result(self.job, f)
self.client.post(self.update_url, data)
assert mail.outbox[0].subject == (
'%s' % self.addon.name)
@mock.patch('olympia.zadmin.tasks.log')
def test_bulk_email_logs_stats(self, log):
log.info = mock.Mock()
self.create_result(self.job, self.create_file(self.version))
self.client.post(self.update_url, self.data)
assert log.info.call_args_list[-8][0][0] == (
'[1@None] bulk update stats for job %s: '
'{bumped: 1, is_dry_run: 0, processed: 1}'
% self.job.pk)
assert log.info.call_args_list[-2][0][0] == (
'[1@None] bulk email stats for job %s: '
'{author_emailed: 1, is_dry_run: 0, processed: 1}'
% self.job.pk)
def test_application_version(self):
self.create_result(self.job, self.create_file(self.version))
self.client.post(self.update_url, self.data)
assert mail.outbox[0].body == 'Firefox 3.7a3'
def test_multiple_result_links(self):
# Creates validation results for two files of the same addon:
results = [
self.create_result(self.job, self.create_file(self.version)),
self.create_result(self.job, self.create_file(self.version))]
self.client.post(self.update_url,
{'text': '{{ PASSING_ADDONS.0.links }}',
'subject': '..'})
body = mail.outbox[0].body
assert all((reverse('devhub.bulk_compat_result',
args=(self.addon.slug, result.pk))
in body)
for result in results)
def test_notify_mail_preview(self):
self.create_result(self.job, self.create_file(self.version))
self.client.post(self.update_url,
{'text': 'the message', 'subject': 'the subject',
'preview_only': 'on'})
assert len(mail.outbox) == 0
rs = self.job.get_notify_preview_emails()
assert [e.subject for e in rs] == ['the subject']
# version should not be bumped since it's in preview mode:
assert self.version.apps.all()[0].max == self.max
upd = amo.LOG.MAX_APPVERSION_UPDATED.id
logs = ActivityLog.objects.for_addons(self.addon).filter(action=upd)
assert logs.count() == 0
class TestBulkNotify(BulkValidationTest):
def setUp(self):
super(TestBulkNotify, self).setUp()
self.job = self.create_job(completed=datetime.now())
self.update_url = reverse('zadmin.notify', args=[self.job.pk])
self.syntax_url = reverse('zadmin.notify.syntax')
self.list_url = reverse('zadmin.validation')
self.version_one = Version.objects.create(addon=self.addon)
self.version_two = Version.objects.create(addon=self.addon)
def test_no_notify_link(self):
self.create_result(self.job, self.create_file(), **{})
r = self.client.get(self.list_url)
doc = pq(r.content)
assert len(doc('table tr td a.notify')) == 0
def test_notify_link(self):
self.create_result(self.job, self.create_file(), **{'errors': 1})
r = self.client.get(self.list_url)
doc = pq(r.content)
assert doc('table tr td a.set-max-version').text() == (
'Notify and set max versions')
def test_notify_url(self):
self.create_result(self.job, self.create_file(), **{'errors': 1})
r = self.client.get(self.list_url)
doc = pq(r.content)
assert doc('table tr td a.set-max-version').attr('data-job-url') == (
self.update_url)
def test_notify_anonymous(self):
self.client.logout()
r = self.client.post(self.update_url)
assert r.status_code == 302
def test_notify_log(self):
self.create_result(self.job, self.create_file(self.version),
**{'errors': 1})
assert ActivityLog.objects.for_addons(self.addon).count() == 0
self.client.post(self.update_url, {'text': '..', 'subject': '..'})
upd = amo.LOG.BULK_VALIDATION_USER_EMAILED.id
logs = (ActivityLog.objects.for_user(self.creator)
.filter(action=upd))
assert logs.count() == 1
assert logs[0].user == self.creator
def test_compat_bump_log(self):
self.create_result(self.job, self.create_file(self.version),
**{'errors': 0})
assert ActivityLog.objects.for_addons(self.addon).count() == 0
self.client.post(self.update_url, {'text': '..', 'subject': '..'})
upd = amo.LOG.MAX_APPVERSION_UPDATED.id
logs = ActivityLog.objects.for_addons(self.addon).filter(action=upd)
assert logs.count() == 1
assert logs[0].user == self.creator
def test_notify_mail(self):
self.create_result(self.job, self.create_file(self.version),
**{'errors': 1})
r = self.client.post(self.update_url,
{'text': '..',
'subject': '{{ FAILING_ADDONS.0.name }}'})
assert r.status_code == 302
assert len(mail.outbox) == 1
assert mail.outbox[0].body == '..'
assert mail.outbox[0].subject == self.addon.name
assert mail.outbox[0].to == [u'del@icio.us']
def test_result_links(self):
result = self.create_result(self.job, self.create_file(self.version),
**{'errors': 1})
r = self.client.post(self.update_url,
{'text': '{{ FAILING_ADDONS.0.links }}',
'subject': '...'})
assert r.status_code == 302
assert len(mail.outbox) == 1
res = reverse('devhub.bulk_compat_result',
args=(self.addon.slug, result.pk))
email = mail.outbox[0].body
assert res in email, ('Unexpected message: %s' % email)
def test_notify_mail_partial(self):
self.create_result(self.job, self.create_file(self.version),
**{'errors': 1})
self.create_result(self.job, self.create_file(self.version))
r = self.client.post(self.update_url, {'text': '..', 'subject': '..'})
assert r.status_code == 302
assert len(mail.outbox) == 1
def test_notify_mail_multiple(self):
self.create_result(self.job, self.create_file(self.version),
**{'errors': 1})
self.create_result(self.job, self.create_file(self.version),
**{'errors': 1})
r = self.client.post(self.update_url, {'text': '..', 'subject': '..'})
assert r.status_code == 302
assert len(mail.outbox) == 1
def test_notify_mail_preview(self):
for i in range(2):
self.create_result(self.job, self.create_file(self.version),
**{'errors': 1})
r = self.client.post(self.update_url,
{'text': 'the message', 'subject': 'the subject',
'preview_only': 'on'})
assert r.status_code == 302
assert len(mail.outbox) == 0
rs = self.job.get_notify_preview_emails()
assert [e.subject for e in rs] == ['the subject']
def test_notify_rendering(self):
self.create_result(self.job, self.create_file(self.version),
**{'errors': 1})
r = self.client.post(self.update_url,
{'text': '{{ FAILING_ADDONS.0.name }}'
'{{ FAILING_ADDONS.0.compat_link }}',
'subject': '{{ FAILING_ADDONS.0.name }} blah'})
assert r.status_code == 302
assert len(mail.outbox) == 1
url = reverse('devhub.versions.edit', args=[self.addon.pk,
self.version.pk])
assert str(self.addon.name) in mail.outbox[0].body
assert url in mail.outbox[0].body
assert str(self.addon.name) in mail.outbox[0].subject
def test_notify_unicode(self):
self.addon.name = u'འབྲུག་ཡུལ།'
self.addon.save()
self.create_result(self.job, self.create_file(self.version),
**{'errors': 1})
r = self.client.post(self.update_url,
{'text': '{{ FAILING_ADDONS.0.name }}',
'subject': '{{ FAILING_ADDONS.0.name }} blah'})
assert r.status_code == 302
assert len(mail.outbox) == 1
assert mail.outbox[0].body == self.addon.name
def test_notify_template(self):
for text, res in (['some sample text', True],
['{{ FAILING_ADDONS.0.name }}{% if %}', False]):
assert forms.NotifyForm(
{'text': text, 'subject': '...'}).is_valid() == res
def test_notify_syntax(self):
for text, res in (['some sample text', True],
['{{ FAILING_ADDONS.0.name }}{% if %}', False]):
r = self.client.post(self.syntax_url, {'text': text,
'subject': '..'})
assert r.status_code == 200
assert json.loads(r.content)['valid'] == res
class TestBulkValidationTask(BulkValidationTest):
def test_validate(self):
self.start_validation()
res = ValidationResult.objects.get()
self.assertCloseToNow(res.completed)
assert not res.task_error
validation = json.loads(res.validation)
assert res.errors == 1
assert validation['messages'][0]['id'] == ['main', 'prepare_package',
'not_found']
assert res.valid is False
assert res.warnings == 0, [mess['message']
for mess in validation['messages']]
assert res.notices == 0
assert validation['errors'] == 1
self.assertCloseToNow(res.validation_job.completed)
assert res.validation_job.stats['total'] == 1
assert res.validation_job.stats['completed'] == 1
assert res.validation_job.stats['passing'] == 0
assert res.validation_job.stats['failing'] == 1
assert res.validation_job.stats['errors'] == 0
assert len(mail.outbox) == 1
assert mail.outbox[0].subject == (
'Behold! Validation results for Firefox %s->%s'
% (self.curr_max.version, self.new_max.version))
assert mail.outbox[0].to == ['fliggy@mozilla.com']
@mock.patch('validator.validate.validate')
def test_validator_bulk_compat_flag(self, validate):
try:
self.start_validation()
except Exception:
# We only care about the call to `validate()`, not the result.
pass
assert validate.call_args[1].get('compat_test')
@mock.patch('olympia.zadmin.tasks.run_validator')
def test_task_error(self, run_validator):
run_validator.side_effect = RuntimeError('validation error')
try:
self.start_validation()
except:
# the real test is how it's handled, below...
pass
res = ValidationResult.objects.get()
err = res.task_error.strip()
assert err.endswith('RuntimeError: validation error'), (
'Unexpected: %s' % err)
self.assertCloseToNow(res.completed)
assert res.validation_job.stats['total'] == 1
assert res.validation_job.stats['errors'] == 1
assert res.validation_job.stats['passing'] == 0
assert res.validation_job.stats['failing'] == 0
@mock.patch('olympia.zadmin.tasks.run_validator')
def test_validate_for_appversions(self, run_validator):
data = {
"errors": 1,
"warnings": 50,
"notices": 1,
"messages": [],
"compatibility_summary": {
"errors": 0,
"warnings": 0,
"notices": 0
},
"metadata": {}
}
run_validator.return_value = json.dumps(data)
self.start_validation()
assert run_validator.called
assert run_validator.call_args[1]['for_appversions'] == (
{amo.FIREFOX.guid: [self.new_max.version]})
@mock.patch('olympia.zadmin.tasks.run_validator')
def test_validate_all_tiers(self, run_validator):
run_validator.return_value = json.dumps(VALIDATOR_SKELETON_RESULTS)
res = self.create_result(self.create_job(), self.create_file(), **{})
tasks.bulk_validate_file(res.id)
assert run_validator.called
assert run_validator.call_args[1]['test_all_tiers']
@mock.patch('olympia.zadmin.tasks.run_validator')
def test_merge_with_compat_summary(self, run_validator):
data = {
"errors": 1,
"detected_type": "extension",
"success": False,
"warnings": 50,
"notices": 1,
"ending_tier": 5,
"messages": [
{"description": "A global function was called ...",
"tier": 3,
"message": "Global called in dangerous manner",
"uid": "de93a48831454e0b9d965642f6d6bf8f",
"id": [],
"compatibility_type": None,
"for_appversions": None,
"type": "warning"},
{"description": ("...no longer indicate the language "
"of Firefox's UI..."),
"tier": 5,
"message": "navigator.language may not behave as expected",
"uid": "f44c1930887c4d9e8bd2403d4fe0253a",
"id": [],
"compatibility_type": "error",
"for_appversions": {
"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}": ["4.2a1pre",
"5.0a2",
"6.0a1"]},
"type": "warning"}],
"compatibility_summary": {
"notices": 1,
"errors": 6,
"warnings": 0},
"metadata": {
"version": "1.0",
"name": "FastestFox",
"id": "<id>"}}
run_validator.return_value = json.dumps(data)
res = self.create_result(self.create_job(), self.create_file(), **{})
tasks.bulk_validate_file(res.id)
assert run_validator.called
res = ValidationResult.objects.get(pk=res.pk)
assert res.errors == (
data['errors'] + data['compatibility_summary']['errors'])
assert res.warnings == (
data['warnings'] + data['compatibility_summary']['warnings'])
assert res.notices == (
data['notices'] + data['compatibility_summary']['notices'])
@mock.patch('validator.validate.validate')
def test_app_version_overrides(self, validate):
validate.return_value = json.dumps(VALIDATOR_SKELETON_RESULTS)
self.start_validation(new_max='3.7a4')
assert validate.called
overrides = validate.call_args[1]['overrides']
assert overrides['targetapp_minVersion'] == {amo.FIREFOX.guid: '3.7a4'}
assert overrides['targetapp_maxVersion'] == {amo.FIREFOX.guid: '3.7a4'}
def create_version(self, addon, statuses, version_str=None):
max = self.max
if version_str:
max = AppVersion.objects.filter(version=version_str)[0]
version = Version.objects.create(addon=addon)
ApplicationsVersions.objects.create(application=self.application,
min=self.min, max=max,
version=version)
for status in statuses:
File.objects.create(status=status, version=version)
return version
def find_files(self, job_kwargs=None):
if not job_kwargs:
job_kwargs = {}
job = self.create_job(**job_kwargs)
find_files(job)
return list(job.result_set.values_list('file_id', flat=True))
def test_getting_disabled(self):
self.addon.update(status=amo.STATUS_DISABLED)
assert len(self.find_files()) == 0
def test_getting_deleted(self):
self.addon.update(status=amo.STATUS_DELETED)
assert len(self.find_files()) == 0
def test_getting_status(self):
self.create_version(self.addon, [amo.STATUS_PUBLIC,
amo.STATUS_NOMINATED])
ids = self.find_files()
assert len(ids) == 2
def test_getting_latest_public(self):
old_version = self.create_version(self.addon, [amo.STATUS_PUBLIC])
self.create_version(self.addon, [amo.STATUS_NULL])
ids = self.find_files()
assert len(ids) == 1
assert old_version.files.all()[0].pk == ids[0]
def test_getting_latest_public_order(self):
self.create_version(self.addon, [amo.STATUS_PURGATORY])
new_version = self.create_version(self.addon, [amo.STATUS_PUBLIC])
ids = self.find_files()
assert len(ids) == 1
assert new_version.files.all()[0].pk == ids[0]
def delete_orig_version(self, fixup=True):
# Because deleting versions resets the status...
self.version.delete()
# Don't really care what status this is, as long
# as it gets past the first SQL query.
self.addon.update(status=amo.STATUS_PUBLIC)
def test_no_versions(self):
self.delete_orig_version()
assert len(self.find_files()) == 0
def test_no_files(self):
self.version.files.all().delete()
self.addon.update(status=amo.STATUS_PUBLIC)
assert len(self.find_files()) == 0
def test_not_public(self):
version = self.create_version(self.addon, [amo.STATUS_LITE])
self.delete_orig_version()
ids = self.find_files()
assert len(ids) == 1
assert version.files.all()[0].pk == ids[0]
def test_not_public_and_newer(self):
self.create_version(self.addon, [amo.STATUS_LITE])
new_version = self.create_version(self.addon, [amo.STATUS_LITE])
self.delete_orig_version()
ids = self.find_files()
assert len(ids) == 1
assert new_version.files.all()[0].pk == ids[0]
def test_not_public_w_beta(self):
self.create_version(self.addon, [amo.STATUS_LITE])
self.create_version(self.addon, [amo.STATUS_BETA])
self.delete_orig_version()
ids = self.find_files()
assert len(ids) == 2
def test_not_public_w_multiple_files(self):
self.create_version(self.addon, [amo.STATUS_BETA])
new_version = self.create_version(self.addon, [amo.STATUS_LITE,
amo.STATUS_BETA])
self.delete_orig_version()
ids = self.find_files()
assert len(ids) == 2
assert sorted([v.id for v in new_version.files.all()]) == sorted(ids)
def test_not_prelim_w_multiple_files(self):
self.create_version(self.addon, [amo.STATUS_BETA])
self.create_version(self.addon, [amo.STATUS_BETA,
amo.STATUS_NOMINATED])
self.delete_orig_version()
ids = self.find_files()
assert len(ids) == 3
def test_public_partial(self):
self.create_version(self.addon, [amo.STATUS_PUBLIC])
new_version = self.create_version(self.addon, [amo.STATUS_BETA,
amo.STATUS_DISABLED])
ids = self.find_files()
assert len(ids) == 2
assert new_version.files.all()[1].pk not in ids
def test_getting_w_unreviewed(self):
old_version = self.create_version(self.addon, [amo.STATUS_PUBLIC])
new_version = self.create_version(self.addon, [amo.STATUS_UNREVIEWED])
ids = self.find_files()
assert len(ids) == 2
old_version_pk = old_version.files.all()[0].pk
new_version_pk = new_version.files.all()[0].pk
assert sorted([old_version_pk, new_version_pk]) == sorted(ids)
def test_multiple_files(self):
self.create_version(self.addon, [amo.STATUS_PUBLIC, amo.STATUS_PUBLIC,
amo.STATUS_PUBLIC])
ids = self.find_files()
assert len(ids) == 3
def test_multiple_public(self):
self.create_version(self.addon, [amo.STATUS_PUBLIC])
new_version = self.create_version(self.addon, [amo.STATUS_PUBLIC])
ids = self.find_files()
assert len(ids) == 1
assert new_version.files.all()[0].pk == ids[0]
def test_multiple_addons(self):
addon = Addon.objects.create(type=amo.ADDON_EXTENSION)
self.create_version(addon, [amo.STATUS_PURGATORY])
ids = self.find_files()
assert len(ids) == 1
assert self.version.files.all()[0].pk == ids[0]
def test_no_app(self):
version = self.create_version(self.addon, [amo.STATUS_LITE])
self.delete_orig_version()
version.apps.all().delete()
ids = self.find_files()
assert len(ids) == 0
def test_wrong_version(self):
self.create_version(self.addon, [amo.STATUS_LITE],
version_str='4.0b2pre')
self.delete_orig_version()
ids = self.find_files()
assert len(ids) == 0
def test_version_slightly_newer_than_current(self):
# addon matching current app/version but with a newer public version
# that is within range of the target app/version.
# See bug 658739.
self.create_version(self.addon, [amo.STATUS_PUBLIC],
version_str='3.7a2')
newer = self.create_version(self.addon, [amo.STATUS_PUBLIC],
version_str='3.7a3')
kw = dict(curr_max_version=self.appversion('3.7a2'),
target_version=self.appversion('3.7a4'))
ids = self.find_files(job_kwargs=kw)
assert newer.files.all()[0].pk == ids[0]
def test_version_compatible_with_newer_app(self):
# addon with a newer public version that is already compatible with
# an app/version higher than the target.
# See bug 658739.
self.create_version(self.addon, [amo.STATUS_PUBLIC],
version_str='3.7a2')
# A version that supports a newer Firefox than what we're targeting
self.create_version(self.addon, [amo.STATUS_PUBLIC],
version_str='3.7a4')
kw = dict(curr_max_version=self.appversion('3.7a2'),
target_version=self.appversion('3.7a3'))
ids = self.find_files(job_kwargs=kw)
assert len(ids) == 0
def test_version_compatible_with_target_app(self):
self.create_version(self.addon, [amo.STATUS_PUBLIC],
version_str='3.7a2')
# Already has a version that supports target:
self.create_version(self.addon, [amo.STATUS_PUBLIC],
version_str='3.7a3')
kw = dict(curr_max_version=self.appversion('3.7a2'),
target_version=self.appversion('3.7a3'))
ids = self.find_files(job_kwargs=kw)
assert len(ids) == 0
def test_version_webextension(self):
self.version.files.update(is_webextension=True)
assert not self.find_files()
class TestTallyValidationErrors(BulkValidationTest):
def setUp(self):
super(TestTallyValidationErrors, self).setUp()
self.data = {
"errors": 1,
"warnings": 1,
"notices": 0,
"messages": [
{"message": "message one",
"description": ["message one long"],
"id": ["path", "to", "test_one"],
"uid": "de93a48831454e0b9d965642f6d6bf8f",
"type": "error"},
{"message": "message two",
"description": "message two long",
"id": ["path", "to", "test_two"],
"uid": "f44c1930887c4d9e8bd2403d4fe0253a",
"compatibility_type": "error",
"type": "warning"}],
"metadata": {},
"compatibility_summary": {
"errors": 1,
"warnings": 1,
"notices": 0}}
def csv(self, job_id):
r = self.client.get(reverse('zadmin.validation_tally_csv',
args=[job_id]))
assert r.status_code == 200
rdr = csv.reader(StringIO(r.content))
header = rdr.next()
rows = sorted((r for r in rdr), key=lambda r: r[0])
return header, rows
@mock.patch('olympia.zadmin.tasks.run_validator')
def test_csv(self, run_validator):
run_validator.return_value = json.dumps(self.data)
self.start_validation()
res = ValidationResult.objects.get()
assert res.task_error is None
header, rows = self.csv(res.validation_job.pk)
assert header == ['message_id', 'message', 'long_message',
'type', 'addons_affected']
assert rows.pop(0) == ['path.to.test_one',
'message one', 'message one long', 'error', '1']
assert rows.pop(0) == ['path.to.test_two',
'message two', 'message two long', 'error', '1']
def test_count_per_addon(self):
job = self.create_job()
data_str = json.dumps(self.data)
for i in range(3):
tasks.tally_validation_results(job.pk, data_str)
header, rows = self.csv(job.pk)
assert rows.pop(0) == ['path.to.test_one',
'message one', 'message one long', 'error', '3']
assert rows.pop(0) == ['path.to.test_two',
'message two', 'message two long', 'error', '3']
def test_nested_list_messages(self):
job = self.create_job()
self.data['messages'] = [{
"message": "message one",
"description": ["message one long", ["something nested"]],
"id": ["path", "to", "test_one"],
"uid": "de93a48831454e0b9d965642f6d6bf8f",
"type": "error",
}]
data_str = json.dumps(self.data)
# This was raising an exception. bug 733845
tasks.tally_validation_results(job.pk, data_str)
class TestEmailPreview(TestCase):
fixtures = ['base/addon_3615', 'base/users']
def setUp(self):
super(TestEmailPreview, self).setUp()
assert self.client.login(username='admin@mozilla.com',
password='password')
addon = Addon.objects.get(pk=3615)
self.topic = EmailPreviewTopic(addon)
def test_csv(self):
self.topic.send_mail('the subject', u'Hello Ivan Krsti\u0107',
from_email='admin@mozilla.org',
recipient_list=['funnyguy@mozilla.org'])
r = self.client.get(reverse('zadmin.email_preview_csv',
args=[self.topic.topic]))
assert r.status_code == 200
rdr = csv.reader(StringIO(r.content))
assert rdr.next() == ['from_email', 'recipient_list', 'subject',
'body']
assert rdr.next() == ['admin@mozilla.org', 'funnyguy@mozilla.org',
'the subject', 'Hello Ivan Krsti\xc4\x87']
class TestMonthlyPick(TestCase):
fixtures = ['base/addon_3615', 'base/users']
def setUp(self):
super(TestMonthlyPick, self).setUp()
assert self.client.login(username='admin@mozilla.com',
password='password')
self.url = reverse('zadmin.monthly_pick')
addon = Addon.objects.get(pk=3615)
MonthlyPick.objects.create(addon=addon,
locale='zh-CN',
blurb="test data",
image="http://www.google.com")
self.f = self.client.get(self.url).context['form'].initial_forms[0]
self.initial = self.f.initial
def test_form_initial(self):
assert self.initial['addon'] == 3615
assert self.initial['locale'] == 'zh-CN'
assert self.initial['blurb'] == 'test data'
assert self.initial['image'] == 'http://www.google.com'
def test_success_insert(self):
dupe = initial(self.f)
del dupe['id']
dupe.update(locale='fr')
data = formset(initial(self.f), dupe, initial_count=1)
self.client.post(self.url, data)
assert MonthlyPick.objects.count() == 2
assert MonthlyPick.objects.all()[1].locale == 'fr'
def test_insert_no_image(self):
dupe = initial(self.f)
dupe.update(id='', image='', locale='en-US')
data = formset(initial(self.f), dupe, initial_count=1)
self.client.post(self.url, data)
assert MonthlyPick.objects.count() == 2
assert MonthlyPick.objects.all()[1].image == ''
def test_success_insert_no_locale(self):
dupe = initial(self.f)
del dupe['id']
del dupe['locale']
data = formset(initial(self.f), dupe, initial_count=1)
self.client.post(self.url, data)
assert MonthlyPick.objects.count() == 2
assert MonthlyPick.objects.all()[1].locale == ''
def test_insert_long_blurb(self):
dupe = initial(self.f)
dupe.update(id='', blurb='x' * 201, locale='en-US')
data = formset(initial(self.f), dupe, initial_count=1)
r = self.client.post(self.url, data)
assert r.context['form'].errors[1]['blurb'][0] == (
'Ensure this value has at most 200 characters (it has 201).')
def test_success_update(self):
d = initial(self.f)
d.update(locale='fr')
r = self.client.post(self.url, formset(d, initial_count=1))
assert r.status_code == 302
assert MonthlyPick.objects.all()[0].locale == 'fr'
def test_success_delete(self):
d = initial(self.f)
d.update(DELETE=True)
self.client.post(self.url, formset(d, initial_count=1))
assert MonthlyPick.objects.count() == 0
def test_require_login(self):
self.client.logout()
r = self.client.get(self.url)
assert r.status_code == 302
class TestFeatures(TestCase):
fixtures = ['base/users', 'base/collections', 'base/addon_3615.json']
def setUp(self):
super(TestFeatures, self).setUp()
assert self.client.login(username='admin@mozilla.com',
password='password')
self.url = reverse('zadmin.features')
FeaturedCollection.objects.create(application=amo.FIREFOX.id,
locale='zh-CN', collection_id=80)
self.f = self.client.get(self.url).context['form'].initial_forms[0]
self.initial = self.f.initial
def test_form_initial(self):
assert self.initial['application'] == amo.FIREFOX.id
assert self.initial['locale'] == 'zh-CN'
assert self.initial['collection'] == 80
def test_form_attrs(self):
r = self.client.get(self.url)
assert r.status_code == 200
doc = pq(r.content)
assert doc('#features tr').attr('data-app') == str(amo.FIREFOX.id)
assert doc('#features td.app').hasClass(amo.FIREFOX.short)
assert doc('#features td.collection.loading').attr(
'data-collection') == '80'
assert doc('#features .collection-ac.js-hidden')
assert not doc('#features .collection-ac[disabled]')
def test_disabled_autocomplete_errors(self):
"""If any collection errors, autocomplete field should be enabled."""
d = dict(application=amo.FIREFOX.id, collection=999)
data = formset(self.initial, d, initial_count=1)
r = self.client.post(self.url, data)
doc = pq(r.content)
assert not doc('#features .collection-ac[disabled]')
def test_required_app(self):
d = dict(locale='zh-CN', collection=80)
data = formset(self.initial, d, initial_count=1)
r = self.client.post(self.url, data)
assert r.status_code == 200
assert r.context['form'].errors[0]['application'] == (
['This field is required.'])
assert r.context['form'].errors[0]['collection'] == (
['Invalid collection for this application.'])
def test_bad_app(self):
d = dict(application=999, collection=80)
data = formset(self.initial, d, initial_count=1)
r = self.client.post(self.url, data)
assert r.context['form'].errors[0]['application'] == [
'Select a valid choice. 999 is not one of the available choices.']
def test_bad_collection_for_app(self):
d = dict(application=amo.THUNDERBIRD.id, collection=80)
data = formset(self.initial, d, initial_count=1)
r = self.client.post(self.url, data)
assert r.context['form'].errors[0]['collection'] == (
['Invalid collection for this application.'])
def test_optional_locale(self):
d = dict(application=amo.FIREFOX.id, collection=80)
data = formset(self.initial, d, initial_count=1)
r = self.client.post(self.url, data)
assert r.context['form'].errors == [{}]
def test_bad_locale(self):
d = dict(application=amo.FIREFOX.id, locale='klingon', collection=80)
data = formset(self.initial, d, initial_count=1)
r = self.client.post(self.url, data)
assert r.context['form'].errors[0]['locale'] == (
['Select a valid choice. klingon is not one of the available '
'choices.'])
def test_required_collection(self):
d = dict(application=amo.FIREFOX.id)
data = formset(self.initial, d, initial_count=1)
r = self.client.post(self.url, data)
assert r.context['form'].errors[0]['collection'] == (
['This field is required.'])
def test_bad_collection(self):
d = dict(application=amo.FIREFOX.id, collection=999)
data = formset(self.initial, d, initial_count=1)
r = self.client.post(self.url, data)
assert r.context['form'].errors[0]['collection'] == (
['Invalid collection for this application.'])
def test_success_insert(self):
dupe = initial(self.f)
del dupe['id']
dupe.update(locale='fr')
data = formset(initial(self.f), dupe, initial_count=1)
self.client.post(self.url, data)
assert FeaturedCollection.objects.count() == 2
assert FeaturedCollection.objects.all()[1].locale == 'fr'
def test_success_update(self):
d = initial(self.f)
d.update(locale='fr')
r = self.client.post(self.url, formset(d, initial_count=1))
assert r.status_code == 302
assert FeaturedCollection.objects.all()[0].locale == 'fr'
def test_success_delete(self):
d = initial(self.f)
d.update(DELETE=True)
self.client.post(self.url, formset(d, initial_count=1))
assert FeaturedCollection.objects.count() == 0
class TestLookup(TestCase):
fixtures = ['base/users']
def setUp(self):
super(TestLookup, self).setUp()
assert self.client.login(username='admin@mozilla.com',
password='password')
self.user = UserProfile.objects.get(pk=999)
self.url = reverse('zadmin.search', args=['users', 'userprofile'])
def test_logged_out(self):
self.client.logout()
assert self.client.get('%s?q=admin' % self.url).status_code == 403
def check_results(self, q, expected):
res = self.client.get(urlparams(self.url, q=q))
assert res.status_code == 200
content = json.loads(res.content)
assert len(content) == len(expected)
ids = [int(c['value']) for c in content]
emails = [u'%s' % c['label'] for c in content]
for d in expected:
id = d['value']
email = u'%s' % d['label']
assert id in ids, (
'Expected user ID "%s" not found' % id)
assert email in emails, (
'Expected username "%s" not found' % email)
def test_lookup_wrong_model(self):
self.url = reverse('zadmin.search', args=['doesnt', 'exist'])
res = self.client.get(urlparams(self.url, q=''))
assert res.status_code == 404
def test_lookup_empty(self):
users = UserProfile.objects.values('id', 'email')
self.check_results('', [dict(
value=u['id'], label=u['email']) for u in users])
def test_lookup_by_id(self):
self.check_results(self.user.id, [dict(value=self.user.id,
label=self.user.email)])
def test_lookup_by_email(self):
self.check_results(self.user.email, [dict(value=self.user.id,
label=self.user.email)])
def test_lookup_by_username(self):
self.check_results(self.user.username, [dict(value=self.user.id,
label=self.user.email)])
class TestAddonSearch(amo.tests.ESTestCase):
fixtures = ['base/users', 'base/addon_3615']
def setUp(self):
super(TestAddonSearch, self).setUp()
self.reindex(Addon)
assert self.client.login(username='admin@mozilla.com',
password='password')
self.url = reverse('zadmin.addon-search')
def test_lookup_addon(self):
res = self.client.get(urlparams(self.url, q='delicious'))
# There's only one result, so it should just forward us to that page.
assert res.status_code == 302
class TestAddonAdmin(TestCase):
fixtures = ['base/users', 'base/addon_3615']
def setUp(self):
super(TestAddonAdmin, self).setUp()
assert self.client.login(username='admin@mozilla.com',
password='password')
self.url = reverse('admin:addons_addon_changelist')
def test_basic(self):
res = self.client.get(self.url)
doc = pq(res.content)
rows = doc('#result_list tbody tr')
assert rows.length == 1
assert rows.find('a').attr('href') == (
'/en-US/admin/models/addons/addon/3615/')
class TestAddonManagement(TestCase):
fixtures = ['base/addon_3615', 'base/users']
def setUp(self):
super(TestAddonManagement, self).setUp()
self.addon = Addon.objects.get(pk=3615)
self.url = reverse('zadmin.addon_manage', args=[self.addon.slug])
self.client.login(username='admin@mozilla.com', password='password')
def test_can_manage_unlisted_addons(self):
"""Unlisted addons can be managed too."""
self.addon.update(is_listed=False)
assert self.client.get(self.url).status_code == 200
def _form_data(self, data=None):
initial_data = {
'status': '4',
'form-0-status': '4',
'form-0-id': '67442',
'form-TOTAL_FORMS': '1',
'form-INITIAL_FORMS': '1',
}
if data:
initial_data.update(data)
return initial_data
def test_addon_status_change(self):
data = self._form_data({'status': '3'})
r = self.client.post(self.url, data, follow=True)
assert r.status_code == 200
addon = Addon.objects.get(pk=3615)
assert addon.status == 3
def test_addon_file_status_change(self):
data = self._form_data({'form-0-status': '1'})
r = self.client.post(self.url, data, follow=True)
assert r.status_code == 200
file = File.objects.get(pk=67442)
assert file.status == 1
def test_addon_deleted_file_status_change(self):
file = File.objects.get(pk=67442)
file.version.update(deleted=True)
data = self._form_data({'form-0-status': '1'})
r = self.client.post(self.url, data, follow=True)
# Form errors are silently suppressed.
assert r.status_code == 200
# But no change.
assert file.status == 4
@mock.patch.object(File, 'file_path',
amo.tests.AMOPaths().file_fixture_path(
'delicious_bookmarks-2.1.106-fx.xpi'))
def test_regenerate_hash(self):
version = Version.objects.create(addon_id=3615)
file = File.objects.create(
filename='delicious_bookmarks-2.1.106-fx.xpi', version=version)
r = self.client.post(reverse('zadmin.recalc_hash', args=[file.id]))
assert json.loads(r.content)[u'success'] == 1
file = File.objects.get(pk=file.id)
assert file.size, 'File size should not be zero'
assert file.hash, 'File hash should not be empty'
@mock.patch.object(File, 'file_path',
amo.tests.AMOPaths().file_fixture_path(
'delicious_bookmarks-2.1.106-fx.xpi'))
def test_regenerate_hash_get(self):
""" Don't allow GET """
version = Version.objects.create(addon_id=3615)
file = File.objects.create(
filename='delicious_bookmarks-2.1.106-fx.xpi', version=version)
r = self.client.get(reverse('zadmin.recalc_hash', args=[file.id]))
assert r.status_code == 405 # GET out of here
class TestCompat(amo.tests.ESTestCase):
fixtures = ['base/users']
def setUp(self):
super(TestCompat, self).setUp()
self.url = reverse('zadmin.compat')
self.client.login(username='admin@mozilla.com', password='password')
self.app = amo.FIREFOX
self.app_version = amo.COMPAT[0]['main']
self.addon = self.populate(guid='xxx')
self.generate_reports(self.addon, good=0, bad=0, app=self.app,
app_version=self.app_version)
def update(self):
compatibility_report()
self.refresh()
def populate(self, **kw):
now = datetime.now()
name = 'Addon %s' % now
kw.update(guid=name)
addon = amo.tests.addon_factory(name=name, **kw)
UpdateCount.objects.create(addon=addon, count=10, date=now)
return addon
def generate_reports(self, addon, good, bad, app, app_version):
defaults = dict(guid=addon.guid, app_guid=app.guid,
app_version=app_version)
for x in xrange(good):
CompatReport.objects.create(works_properly=True, **defaults)
for x in xrange(bad):
CompatReport.objects.create(works_properly=False, **defaults)
self.update()
def get_pq(self, **kw):
r = self.client.get(self.url, kw)
assert r.status_code == 200
return pq(r.content)('#compat-results')
def test_defaults(self):
r = self.client.get(self.url)
assert r.status_code == 200
assert r.context['app'] == self.app
assert r.context['version'] == self.app_version
table = pq(r.content)('#compat-results')
assert table.length == 1
assert table.find('.no-results').length == 1
def check_row(self, tr, addon, good, bad, percentage, app, app_version):
assert tr.length == 1
version = addon.current_version.version
name = tr.find('.name')
assert name.find('.version').text() == 'v' + version
assert name.remove('.version').text() == unicode(addon.name)
assert name.find('a').attr('href') == addon.get_url_path()
assert tr.find('.maxver').text() == (
addon.compatible_apps[app].max.version)
incompat = tr.find('.incompat')
assert incompat.find('.bad').text() == str(bad)
assert incompat.find('.total').text() == str(good + bad)
percentage += '%'
assert percentage in incompat.text(), (
'Expected incompatibility to be %r' % percentage)
assert tr.find('.version a').attr('href') == (
reverse('devhub.versions.edit',
args=[addon.slug, addon.current_version.id]))
assert tr.find('.reports a').attr('href') == (
reverse('compat.reporter_detail', args=[addon.guid]))
form = tr.find('.overrides form')
assert form.attr('action') == reverse(
'admin:addons_compatoverride_add')
self.check_field(form, '_compat_ranges-TOTAL_FORMS', '1')
self.check_field(form, '_compat_ranges-INITIAL_FORMS', '0')
self.check_field(form, '_continue', '1')
self.check_field(form, '_confirm', '1')
self.check_field(form, 'addon', str(addon.id))
self.check_field(form, 'guid', addon.guid)
compat_field = '_compat_ranges-0-%s'
self.check_field(form, compat_field % 'min_version', '0')
self.check_field(form, compat_field % 'max_version', version)
self.check_field(form, compat_field % 'app', str(app.id))
self.check_field(form, compat_field % 'min_app_version',
app_version + 'a1')
self.check_field(form, compat_field % 'max_app_version',
app_version + '*')
def check_field(self, form, name, val):
assert form.find('input[name="%s"]' % name).val() == val
def test_firefox_hosted(self):
addon = self.populate()
self.generate_reports(addon, good=0, bad=11, app=self.app,
app_version=self.app_version)
tr = self.get_pq().find('tr[data-guid="%s"]' % addon.guid)
self.check_row(tr, addon, good=0, bad=11, percentage='100.0',
app=self.app, app_version=self.app_version)
# Add an override for this current app version.
compat = CompatOverride.objects.create(addon=addon, guid=addon.guid)
CompatOverrideRange.objects.create(
compat=compat,
app=amo.FIREFOX.id, min_app_version=self.app_version + 'a1',
max_app_version=self.app_version + '*')
# Check that there is an override for this current app version.
tr = self.get_pq().find('tr[data-guid="%s"]' % addon.guid)
assert tr.find('.overrides a').attr('href') == (
reverse('admin:addons_compatoverride_change', args=[compat.id]))
def test_non_default_version(self):
app_version = amo.COMPAT[2]['main']
addon = self.populate()
self.generate_reports(addon, good=0, bad=11, app=self.app,
app_version=app_version)
pq = self.get_pq()
assert pq.find('tr[data-guid="%s"]' % addon.guid).length == 0
appver = '%s-%s' % (self.app.id, app_version)
tr = self.get_pq(appver=appver)('tr[data-guid="%s"]' % addon.guid)
self.check_row(tr, addon, good=0, bad=11, percentage='100.0',
app=self.app, app_version=app_version)
def test_minor_versions(self):
addon = self.populate()
self.generate_reports(addon, good=0, bad=1, app=self.app,
app_version=self.app_version)
self.generate_reports(addon, good=1, bad=2, app=self.app,
app_version=self.app_version + 'a2')
tr = self.get_pq(ratio=0.0, minimum=0).find('tr[data-guid="%s"]' %
addon.guid)
self.check_row(tr, addon, good=1, bad=3, percentage='75.0',
app=self.app, app_version=self.app_version)
def test_ratio(self):
addon = self.populate()
self.generate_reports(addon, good=11, bad=11, app=self.app,
app_version=self.app_version)
# Should not show up for > 80%.
pq = self.get_pq()
assert pq.find('tr[data-guid="%s"]' % addon.guid).length == 0
# Should not show up for > 50%.
tr = self.get_pq(ratio=.5).find('tr[data-guid="%s"]' % addon.guid)
assert tr.length == 0
# Should show up for > 40%.
tr = self.get_pq(ratio=.4).find('tr[data-guid="%s"]' % addon.guid)
assert tr.length == 1
def test_min_incompatible(self):
addon = self.populate()
self.generate_reports(addon, good=0, bad=11, app=self.app,
app_version=self.app_version)
# Should show up for >= 10.
pq = self.get_pq()
assert pq.find('tr[data-guid="%s"]' % addon.guid).length == 1
# Should show up for >= 0.
tr = self.get_pq(minimum=0).find('tr[data-guid="%s"]' % addon.guid)
assert tr.length == 1
# Should not show up for >= 20.
tr = self.get_pq(minimum=20).find('tr[data-guid="%s"]' % addon.guid)
assert tr.length == 0
class TestMemcache(TestCase):
fixtures = ['base/addon_3615', 'base/users']
def setUp(self):
super(TestMemcache, self).setUp()
self.url = reverse('zadmin.memcache')
cache.set('foo', 'bar')
self.client.login(username='admin@mozilla.com', password='password')
def test_login(self):
self.client.logout()
assert self.client.get(self.url).status_code == 302
def test_can_clear(self):
self.client.post(self.url, {'yes': 'True'})
assert cache.get('foo') is None
def test_cant_clear(self):
self.client.post(self.url, {'yes': 'False'})
assert cache.get('foo') == 'bar'
class TestElastic(amo.tests.ESTestCase):
fixtures = ['base/addon_3615', 'base/users']
def setUp(self):
super(TestElastic, self).setUp()
self.url = reverse('zadmin.elastic')
self.client.login(username='admin@mozilla.com', password='password')
def test_login(self):
self.client.logout()
self.assert3xx(
self.client.get(self.url),
reverse('users.login') + '?to=/en-US/admin/elastic')
class TestEmailDevs(TestCase):
fixtures = ['base/addon_3615', 'base/users']
def setUp(self):
super(TestEmailDevs, self).setUp()
self.login('admin')
self.addon = Addon.objects.get(pk=3615)
def post(self, recipients='eula', subject='subject', message='msg',
preview_only=False):
return self.client.post(reverse('zadmin.email_devs'),
dict(recipients=recipients, subject=subject,
message=message,
preview_only=preview_only))
def test_preview(self):
res = self.post(preview_only=True)
self.assertNoFormErrors(res)
preview = EmailPreviewTopic(topic='email-devs')
assert [e.recipient_list for e in preview.filter()] == ['del@icio.us']
assert len(mail.outbox) == 0
def test_actual(self):
subject = 'about eulas'
message = 'message about eulas'
res = self.post(subject=subject, message=message)
self.assertNoFormErrors(res)
self.assert3xx(res, reverse('zadmin.email_devs'))
assert len(mail.outbox) == 1
assert mail.outbox[0].subject == subject
assert mail.outbox[0].body == message
assert mail.outbox[0].to == ['del@icio.us']
assert mail.outbox[0].from_email == settings.DEFAULT_FROM_EMAIL
def test_only_eulas(self):
self.addon.update(eula=None)
res = self.post()
self.assertNoFormErrors(res)
assert len(mail.outbox) == 0
def test_sdk_devs(self):
(File.objects.filter(version__addon=self.addon)
.update(jetpack_version='1.5'))
res = self.post(recipients='sdk')
self.assertNoFormErrors(res)
assert len(mail.outbox) == 1
assert mail.outbox[0].to == ['del@icio.us']
def test_only_sdk_devs(self):
res = self.post(recipients='sdk')
self.assertNoFormErrors(res)
assert len(mail.outbox) == 0
def test_only_extensions(self):
self.addon.update(type=amo.ADDON_EXTENSION)
res = self.post(recipients='all_extensions')
self.assertNoFormErrors(res)
assert len(mail.outbox) == 1
def test_ignore_deleted_always(self):
self.addon.update(status=amo.STATUS_DELETED)
for name, label in DevMailerForm._choices:
res = self.post(recipients=name)
self.assertNoFormErrors(res)
assert len(mail.outbox) == 0
def test_exclude_pending_for_addons(self):
self.addon.update(status=amo.STATUS_PENDING)
for name, label in DevMailerForm._choices:
if name in ('payments', 'desktop_apps'):
continue
res = self.post(recipients=name)
self.assertNoFormErrors(res)
assert len(mail.outbox) == 0
def test_exclude_fxa_migrated(self):
user = self.addon.authors.get()
user.update(fxa_id='yup')
res = self.post(recipients='fxa')
self.assertNoFormErrors(res)
assert len(mail.outbox) == 0
def test_include_fxa_not_migrated(self):
res = self.post(recipients='fxa')
user = self.addon.authors.get()
self.assertNoFormErrors(res)
assert len(mail.outbox) == 1
user = self.addon.authors.get()
user.update(fxa_id='')
res = self.post(recipients='fxa')
self.assertNoFormErrors(res)
assert len(mail.outbox) == 2
class TestFileDownload(TestCase):
fixtures = ['base/users']
def setUp(self):
super(TestFileDownload, self).setUp()
assert self.client.login(username='admin@mozilla.com',
password='password')
self.file = open(get_image_path('animated.png'), 'rb')
resp = self.client.post(reverse('devhub.upload'),
{'upload': self.file})
assert resp.status_code == 302
self.upload = FileUpload.objects.get()
self.url = reverse('zadmin.download_file', args=[self.upload.uuid])
def test_download(self):
"""Test that downloading file_upload objects works."""
resp = self.client.get(self.url)
assert resp.status_code == 200
assert resp.content == self.file.read()
class TestPerms(TestCase):
fixtures = ['base/users']
FILE_ID = '1234567890abcdef1234567890abcdef'
def assert_status(self, view, status, **kw):
"""Check that requesting the named view returns the expected status."""
assert self.client.get(reverse(view, kwargs=kw)).status_code == status
def test_admin_user(self):
# Admin should see views with Django's perm decorator and our own.
assert self.client.login(username='admin@mozilla.com',
password='password')
self.assert_status('zadmin.index', 200)
self.assert_status('zadmin.settings', 200)
self.assert_status('zadmin.langpacks', 200)
self.assert_status('zadmin.download_file', 404, uuid=self.FILE_ID)
self.assert_status('zadmin.addon-search', 200)
self.assert_status('zadmin.monthly_pick', 200)
self.assert_status('zadmin.features', 200)
self.assert_status('discovery.module_admin', 200)
def test_staff_user(self):
# Staff users have some privileges.
user = UserProfile.objects.get(email='regular@mozilla.com')
group = Group.objects.create(name='Staff', rules='AdminTools:View')
GroupUser.objects.create(group=group, user=user)
assert self.client.login(username='regular@mozilla.com',
password='password')
self.assert_status('zadmin.index', 200)
self.assert_status('zadmin.settings', 200)
self.assert_status('zadmin.langpacks', 200)
self.assert_status('zadmin.download_file', 404, uuid=self.FILE_ID)
self.assert_status('zadmin.addon-search', 200)
self.assert_status('zadmin.monthly_pick', 200)
self.assert_status('zadmin.features', 200)
self.assert_status('discovery.module_admin', 200)
def test_sr_reviewers_user(self):
# Sr Reviewers users have only a few privileges.
user = UserProfile.objects.get(email='regular@mozilla.com')
group = Group.objects.create(name='Sr Reviewer',
rules='ReviewerAdminTools:View')
GroupUser.objects.create(group=group, user=user)
assert self.client.login(username='regular@mozilla.com',
password='password')
self.assert_status('zadmin.index', 200)
self.assert_status('zadmin.langpacks', 200)
self.assert_status('zadmin.download_file', 404, uuid=self.FILE_ID)
self.assert_status('zadmin.addon-search', 200)
self.assert_status('zadmin.settings', 403)
def test_bulk_compat_user(self):
# Bulk Compatibility Updaters only have access to /admin/validation/*.
user = UserProfile.objects.get(email='regular@mozilla.com')
group = Group.objects.create(name='Bulk Compatibility Updaters',
rules='BulkValidationAdminTools:View')
GroupUser.objects.create(group=group, user=user)
assert self.client.login(username='regular@mozilla.com',
password='password')
self.assert_status('zadmin.index', 200)
self.assert_status('zadmin.validation', 200)
self.assert_status('zadmin.langpacks', 403)
self.assert_status('zadmin.download_file', 403, uuid=self.FILE_ID)
self.assert_status('zadmin.addon-search', 403)
self.assert_status('zadmin.settings', 403)
def test_unprivileged_user(self):
# Unprivileged user.
assert self.client.login(username='regular@mozilla.com',
password='password')
self.assert_status('zadmin.index', 403)
self.assert_status('zadmin.settings', 403)
self.assert_status('zadmin.langpacks', 403)
self.assert_status('zadmin.download_file', 403, uuid=self.FILE_ID)
self.assert_status('zadmin.addon-search', 403)
self.assert_status('zadmin.monthly_pick', 403)
self.assert_status('zadmin.features', 403)
self.assert_status('discovery.module_admin', 403)
# Anonymous users should also get a 403.
self.client.logout()
self.assert3xx(self.client.get(reverse('zadmin.index')),
reverse('users.login') + '?to=/en-US/admin/')
|
andymckay/addons-server
|
src/olympia/zadmin/tests/test_views.py
|
Python
|
bsd-3-clause
| 77,618
|
from dasdocc.conf import base
|
JohnRandom/django-aggregator
|
dasdocc/conf/staging.py
|
Python
|
bsd-3-clause
| 29
|
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Preprocessed version of "ndnboost/mpl/less.hpp" header
// -- DO NOT modify by hand!
namespace ndnboost { namespace mpl {
template<
typename Tag1
, typename Tag2
, NDNBOOST_MPL_AUX_NTTP_DECL(int, tag1_) = NDNBOOST_MPL_AUX_MSVC_VALUE_WKND(Tag1)::value
, NDNBOOST_MPL_AUX_NTTP_DECL(int, tag2_) = NDNBOOST_MPL_AUX_MSVC_VALUE_WKND(Tag2)::value
>
struct less_impl
: if_c<
( tag1_ > tag2_ )
, aux::cast2nd_impl< less_impl< Tag1,Tag1 >,Tag1, Tag2 >
, aux::cast1st_impl< less_impl< Tag2,Tag2 >,Tag1, Tag2 >
>::type
{
};
/// for Digital Mars C++/compilers with no CTPS/TTP support
template<> struct less_impl< na,na >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
NDNBOOST_STATIC_CONSTANT(int, value = 0);
};
};
template<> struct less_impl< na,integral_c_tag >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
NDNBOOST_STATIC_CONSTANT(int, value = 0);
};
};
template<> struct less_impl< integral_c_tag,na >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
NDNBOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename T > struct less_tag
{
typedef typename T::tag type;
};
template<
typename NDNBOOST_MPL_AUX_NA_PARAM(N1)
, typename NDNBOOST_MPL_AUX_NA_PARAM(N2)
>
struct less
: aux::msvc_eti_base< typename apply_wrap2<
less_impl<
typename less_tag<N1>::type
, typename less_tag<N2>::type
>
, N1
, N2
>::type >::type
{
NDNBOOST_MPL_AUX_LAMBDA_SUPPORT(2, less, (N1, N2))
};
NDNBOOST_MPL_AUX_NA_SPEC2(2, 2, less)
}}
namespace ndnboost { namespace mpl {
template<>
struct less_impl< integral_c_tag,integral_c_tag >
{
template< typename N1, typename N2 > struct apply
{
NDNBOOST_STATIC_CONSTANT(bool, value =
( NDNBOOST_MPL_AUX_VALUE_WKND(N2)::value >
NDNBOOST_MPL_AUX_VALUE_WKND(N1)::value )
);
typedef bool_<value> type;
};
};
}}
|
cawka/packaging-ndn-cpp
|
include/ndnboost/mpl/aux_/preprocessed/msvc60/less.hpp
|
C++
|
bsd-3-clause
| 2,340
|
import keyedcache
import logging
log = logging.getLogger(__name__)
class CachedObjectMixin(object):
"""Provides basic object keyedcache for any objects using this as a mixin.
The class name of the object should be unambiguous.
"""
def cache_delete(self, *args, **kwargs):
key = self.cache_key(*args, **kwargs)
log.debug("clearing cache for %s", key)
keyedcache.cache_delete(key, children=True)
def cache_get(self, *args, **kwargs):
key = self.cache_key(*args, **kwargs)
return keyedcache.cache_get(key)
def cache_key(self, *args, **kwargs):
keys = [self.__class__.__name__, self]
keys.extend(args)
return keyedcache.cache_key(keys, **kwargs)
def cache_reset(self):
self.cache_delete()
self.cache_set()
def cache_set(self, *args, **kwargs):
val = kwargs.pop('value', self)
key = self.cache_key(*args, **kwargs)
keyedcache.cache_set(key, value=val)
def is_cached(self, *args, **kwargs):
return keyedcache.is_cached(self.cache_key(*args, **kwargs))
# Unused functions find_by_id, find_by_key, find_by_slug are coming from
# Satchmo but are currently unused also there.
def find_by_id(cls, groupkey, objectid, raises=False):
"""A helper function to look up an object by id"""
ob = None
try:
ob = keyedcache.cache_get(groupkey, objectid)
except keyedcache.NotCachedError as e:
try:
ob = cls.objects.get(pk=objectid)
keyedcache.cache_set(e.key, value=ob)
except cls.DoesNotExist:
log.debug("No such %s: %s", groupkey, objectid)
if raises:
raise cls.DoesNotExist
return ob
def find_by_key(cls, groupkey, key, raises=False):
"""A helper function to look up an object by key"""
ob = None
try:
ob = keyedcache.cache_get(groupkey, key)
except keyedcache.NotCachedError as e:
try:
ob = cls.objects.get(key__exact=key)
keyedcache.cache_set(e.key, value=ob)
except cls.DoesNotExist:
log.debug("No such %s: %s", groupkey, key)
if raises:
raise
return ob
def find_by_slug(cls, groupkey, slug, raises=False):
"""A helper function to look up an object by slug"""
ob = None
try:
ob = keyedcache.cache_get(groupkey, slug)
except keyedcache.NotCachedError as e:
try:
ob = cls.objects.get(slug__exact=slug)
keyedcache.cache_set(e.key, value=ob)
except cls.DoesNotExist:
log.debug("No such %s: %s", groupkey, slug)
if raises:
raise
return ob
|
aronysidoro/django-livesettings
|
live/keyedcache/models.py
|
Python
|
bsd-3-clause
| 2,736
|
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef WEBRTC_VIDEO_ENGINE_TEST_LIBVIETEST_INCLUDE_VIE_TO_FILE_RENDERER_H_
#define WEBRTC_VIDEO_ENGINE_TEST_LIBVIETEST_INCLUDE_VIE_TO_FILE_RENDERER_H_
#include <stdio.h>
#include <string.h>
#include <list>
#include <string>
#include "webrtc/base/constructormagic.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/video_engine/include/vie_render.h"
namespace webrtc {
class CriticalSectionWrapper;
class EventWrapper;
class ThreadWrapper;
}; // namespace webrtc
namespace test {
struct Frame;
}; // namespace test
class ViEToFileRenderer: public webrtc::ExternalRenderer {
public:
ViEToFileRenderer();
virtual ~ViEToFileRenderer();
// Returns false if we fail opening the output filename for writing.
bool PrepareForRendering(const std::string& output_path,
const std::string& output_filename);
// Closes the output file.
void StopRendering();
// Deletes the closed output file from the file system. This is one option
// after calling StopRendering, the other being KeepOutputFile. This file
// renderer will forget about the file after this call and can be used again.
bool DeleteOutputFile();
// Renames the closed output file to its previous name with the provided
// prefix prepended. This file renderer will forget about the file after this
// call and can be used again.
bool SaveOutputFile(const std::string& prefix);
// Implementation of ExternalRenderer:
int FrameSizeChange(unsigned int width, unsigned int height,
unsigned int number_of_streams) OVERRIDE;
int DeliverFrame(unsigned char* buffer,
size_t buffer_size,
uint32_t time_stamp,
int64_t ntp_time_ms,
int64_t render_time,
void* handle) OVERRIDE;
int DeliverI420Frame(const webrtc::I420VideoFrame& webrtc_frame) OVERRIDE;
bool IsTextureSupported() OVERRIDE;
const std::string GetFullOutputPath() const;
private:
typedef std::list<test::Frame*> FrameQueue;
// Returns a frame with the specified |buffer_size|. Tries to avoid allocating
// new frames by reusing frames from |free_frame_queue_|.
test::Frame* NewFrame(size_t buffer_size);
static bool RunRenderThread(void* obj);
void ForgetOutputFile();
bool ProcessRenderQueue();
FILE* output_file_;
std::string output_path_;
std::string output_filename_;
webrtc::scoped_ptr<webrtc::ThreadWrapper> thread_;
webrtc::scoped_ptr<webrtc::CriticalSectionWrapper> frame_queue_cs_;
webrtc::scoped_ptr<webrtc::EventWrapper> frame_render_event_;
FrameQueue render_queue_;
FrameQueue free_frame_queue_;
};
#endif // WEBRTC_VIDEO_ENGINE_TEST_LIBVIETEST_INCLUDE_VIE_TO_FILE_RENDERER_H_
|
yuxw75/temp
|
video_engine/test/libvietest/include/vie_to_file_renderer.h
|
C
|
bsd-3-clause
| 3,169
|
tinyMCE.addI18n('ru.paste_dlg',{
text_title:"\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u0441\u043E\u0447\u0435\u0442\u0430\u043D\u0438\u0435 \u043A\u043B\u0430\u0432\u0438\u0448 CTRL+V \u0447\u0442\u043E\u0431\u044B \u0432\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0442\u0435\u043A\u0441\u0442 \u0432 \u043E\u043A\u043D\u043E.",
text_linebreaks:"\u0421\u043E\u0445\u0440\u0430\u043D\u044F\u0442\u044C \u0440\u0430\u0437\u0440\u044B\u0432\u044B \u0441\u0442\u0440\u043E\u043A",
word_title:"\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u0441\u043E\u0447\u0435\u0442\u0430\u043D\u0438\u0435 \u043A\u043B\u0430\u0432\u0438\u0448 CTRL+V \u0447\u0442\u043E\u0431\u044B \u0432\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0442\u0435\u043A\u0441\u0442 \u0432 \u043E\u043A\u043D\u043E."
});
|
SunboX/fotocommunity
|
jsparty/tiny_mce2/plugins/paste/langs/ru_dlg.js
|
JavaScript
|
bsd-3-clause
| 831
|
# -*- coding: utf-8 -*-
"""
pygments.styles.manni
~~~~~~~~~~~~~~~~~~~~~
A colorful style, inspired by the terminal highlighting style.
This is a port of the style used in the `php port`_ of pygments
by Manni. The style is called 'default' there.
:copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic, Whitespace
class ManniStyle(Style):
"""
A colorful style, inspired by the terminal highlighting style.
"""
background_color = '#f0f3f3'
styles = {
Whitespace: '#bbbbbb',
Comment: 'italic #0099FF',
Comment.Preproc: 'noitalic #009999',
Comment.Special: 'bold',
Keyword: 'bold #006699',
Keyword.Pseudo: 'nobold',
Keyword.Type: '#007788',
Operator: '#555555',
Operator.Word: 'bold #000000',
Name.Builtin: '#336666',
Name.Function: '#CC00FF',
Name.Class: 'bold #00AA88',
Name.Namespace: 'bold #00CCFF',
Name.Exception: 'bold #CC0000',
Name.Variable: '#003333',
Name.Constant: '#336600',
Name.Label: '#9999FF',
Name.Entity: 'bold #999999',
Name.Attribute: '#330099',
Name.Tag: 'bold #330099',
Name.Decorator: '#9999FF',
String: '#CC3300',
String.Doc: 'italic',
String.Interpol: '#AA0000',
String.Escape: 'bold #CC3300',
String.Regex: '#33AAAA',
String.Symbol: '#FFCC33',
String.Other: '#CC3300',
Number: '#FF6600',
Generic.Heading: 'bold #003300',
Generic.Subheading: 'bold #003300',
Generic.Deleted: 'border:#CC0000 bg:#FFCCCC',
Generic.Inserted: 'border:#00CC00 bg:#CCFFCC',
Generic.Error: '#FF0000',
Generic.Emph: 'italic',
Generic.Strong: 'bold',
Generic.Prompt: 'bold #000099',
Generic.Output: '#AAAAAA',
Generic.Traceback: '#99CC66',
Error: 'bg:#FFAAAA #AA0000'
}
|
wakatime/wakatime
|
wakatime/packages/py27/pygments/styles/manni.py
|
Python
|
bsd-3-clause
| 2,374
|
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Queue
* @subpackage Stomp
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/**
* @namespace
*/
namespace Zend\Queue\Stomp;
use Zend\Queue\Exception as QueueException;
/**
* This class represents a Stomp Frame
*
* @uses \Zend\Queue\Exception
* @uses \Zend\Queue\Stomp\StompFrame
* @category Zend
* @package Zend_Queue
* @subpackage Stomp
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Frame implements StompFrame
{
const END_OF_FRAME = "\x00\n";
const CONTENT_LENGTH = 'content-length';
const EOL = "\n";
/**
* Headers for the frame
*
* @var array
*/
protected $_headers = array();
/**
* The command for the frame
*
* @var string
*/
protected $_command = null;
/**
* The body of the frame
*
* @var string
*/
protected $_body = null;
/**
* Do the content-length automatically?
*/
protected $_autoContentLength = null;
/**
* Constructor
*/
public function __construct()
{
$this->setHeaders(array());
$this->setBody(null);
$this->setCommand(null);
$this->setAutoContentLength(true);
}
/**
* get the status of the auto content length
*
* If AutoContentLength is true this code will automatically put the
* content-length header in, even if it is already set by the user.
*
* This is done to make the message sending more reliable.
*
* @return boolean
*/
public function getAutoContentLength()
{
return $this->_autoContentLength;
}
/**
* setAutoContentLength()
*
* Set the value on or off.
*
* @param boolean $auto
* @return $this;
* @throws \Zend\Queue\Exception
*/
public function setAutoContentLength($auto)
{
if (!is_bool($auto)) {
throw new QueueException('$auto is not a boolean');
}
$this->_autoContentLength = $auto;
return $this;
}
/**
* Get the headers
*
* @return array
*/
public function getHeaders()
{
return $this->_headers;
}
/**
* Set the headers
*
* Throws an exception if the array values are not strings.
*
* @param array $headers
* @return $this
* @throws \Zend\Queue\Exception
*/
public function setHeaders(array $headers)
{
foreach ($headers as $header => $value) {
$this->setHeader($header, $value);
}
return $this;
}
/**
* Sets a value for a header
*
* @param string $header
* @param string $value
* @return \Zend\Queue\Stomp\Frame
* @throws \Zend\Queue\Exception
*/
public function setHeader($header, $value) {
if (!is_string($header)) {
throw new QueueException('$header is not a string: ' . print_r($header, true));
}
if (!is_scalar($value)) {
throw new QueueException('$value is not a string: ' . print_r($value, true));
}
$this->_headers[$header] = $value;
return $this;
}
/**
* Returns a value for a header
*
* Returns false if the header does not exist.
*
* @param string $header
* @return string|false
* @throws \Zend\Queue\Exception
*/
public function getHeader($header)
{
if (!is_string($header)) {
throw new QueueException('$header is not a string');
}
return isset($this->_headers[$header])
? $this->_headers[$header]
: false;
}
/**
* Return the body for this frame
*
* Returns false if the body does not exist
*
* @return false|string
*/
public function getBody()
{
return $this->_body === null
? false
: $this->_body;
}
/**
* Set the body for this frame
*
* Set to null for no body.
*
* @param string|null $body
* @return \Zend\Queue\Stomp\Frame
* @throws \Zend\Queue\Exception
*/
public function setBody($body)
{
if (!is_string($body) && $body !== null) {
throw new QueueException('$body is not a string or null');
}
$this->_body = $body;
return $this;
}
/**
* Return the command for this frame
*
* Return false if the command does not exist
*
* @return string|false
*/
public function getCommand()
{
return $this->_command === null
? false
: $this->_command;
}
/**
* Set the body for this frame
*
* @param string|null
* @return \Zend\Queue\Stomp\Frame
* @throws \Zend\Queue\Exception
*/
public function setCommand($command)
{
if (!is_string($command) && $command !== null) {
throw new QueueException('$command is not a string or null');
}
$this->_command = $command;
return $this;
}
/**
* Takes the current parameters and returns a Stomp Frame
*
* @return string
* @throws \Zend\Queue\Exception
*/
public function toFrame()
{
if ($this->getCommand() === false) {
throw new QueueException('You must set the command');
}
$command = $this->getCommand();
$headers = $this->getHeaders();
$body = $this->getBody();
$frame = '';
// add a content-length to the SEND command.
// @see http://stomp.codehaus.org/Protocol
if ($this->getAutoContentLength()) {
$headers[self::CONTENT_LENGTH] = strlen($this->getBody());
}
// Command
$frame = $command . self::EOL;
// Headers
foreach ($headers as $key=>$value) {
$frame .= $key . ': ' . $value . self::EOL;
}
// Seperator
$frame .= self::EOL; // blank line required by protocol
// add the body if any
if ($body !== false) {
$frame .= $body;
}
$frame .= self::END_OF_FRAME;
return $frame;
}
/**
* @see toFrame()
* @return string
*/
public function __toString()
{
try {
$return = $this->toFrame();
} catch (QueueException $e) {
$return = '';
}
return $return;
}
/**
* Extract the Command from a response string frame or returns false
*
* @param string $frame - a stomp frame
* @return string|false
*/
public static function extractCommand($frame)
{
// todo: Commands are in caps per spec, this is not checked here
if (preg_match("|^([A-Z]+)\n|i", $frame, $m) == 1) {
return $m[1];
}
return false;
}
/**
* Extract the headers from a response string
*
* @param string $frame - a stromp frame
* @return array
*/
public static function extractHeaders($frame)
{
$parts = preg_split('|(?:\r?\n){2}\n|m', $frame, 2);
if (!isset($parts[0])) {
return array();
}
if (!preg_match_all("|([\w-]+):\s*(.+)\n|", $parts[0], $m, PREG_SET_ORDER)) {
return array();
}
$headers = array();
foreach ($m as $header) {
$headers[mb_strtolower($header[1])] = $header[2];
}
return $headers;
}
/**
* Extract the body from a response string
*
* @param string $frame - a stomp frame
* @return string
* @throws \Zend\Queue\Exception when the body is badly formatted
*/
public static function extractBody($frame)
{
$parts = preg_split('|(?:\r?\n){2}|m', $frame, 2);
if (!isset($parts[1])) {
return '';
}
if (substr($parts[1], -2) != self::END_OF_FRAME) {
throw new QueueException('badly formatted body not frame terminated');
}
return substr($parts[1], 0, -2);
}
/**
* Accepts a frame and deconstructs the frame into its component parts
*
* @param string $frame - a stomp frame
* @return $this
*/
public function fromFrame($frame)
{
if (!is_string($frame)) {
throw new QueueException('$frame is not a string');
}
$this->setCommand(self::extractCommand($frame));
$this->setHeaders(self::extractHeaders($frame));
$this->setBody(self::extractBody($frame));
return $this;
}
}
|
Techlightenment/zf2
|
library/Zend/Queue/Stomp/Frame.php
|
PHP
|
bsd-3-clause
| 9,318
|
<?php
/**
* @name ElkArte Forum
* @copyright ElkArte Forum contributors
* @license BSD http://opensource.org/licenses/BSD-3-Clause
*
* This file contains code covered by:
* copyright: 2011 Simple Machines (http://www.simplemachines.org)
* license: BSD, See included LICENSE.TXT for terms and conditions.
*
* @version 1.1
*
*/
/**
* Announce a topic
*/
function template_announce()
{
global $context, $txt, $scripturl;
echo '
<div id="announcement">
<form action="', $scripturl, '?action=announce;sa=send" method="post" accept-charset="UTF-8">
<h2 class="category_header">', $txt['announce_title'], '</h2>
<div class="information">
', $txt['announce_desc'], '
</div>
<div class="content">
<p>
', $txt['announce_this_topic'], ' <a href="', $scripturl, '?topic=', $context['current_topic'], '.0">', $context['topic_subject'], '</a>
</p>
<ul>';
foreach ($context['groups'] as $group)
echo '
<li>
<label for="who_', $group['id'], '"><input type="checkbox" name="who[', $group['id'], ']" id="who_', $group['id'], '" value="', $group['id'], '" checked="checked" /> ', $group['name'], '</label> <em>(', $group['member_count'], ')</em>
</li>';
echo '
<li>
<label for="checkall"><input type="checkbox" id="checkall" onclick="invertAll(this, this.form);" checked="checked" /> <em>', $txt['check_all'], '</em></label>
</li>
</ul>
<hr />
<div class="submitbutton">
<input type="submit" value="', $txt['sendtopic_send'], '" />
<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
<input type="hidden" name="topic" value="', $context['current_topic'], '" />
<input type="hidden" name="move" value="', $context['move'], '" />
<input type="hidden" name="goback" value="', $context['go_back'], '" />
</div>
</div>
</form>
</div>';
}
/**
* Send an announcement out in increments
* Shows a progress bar with continue button
* autoSubmitted with JS
*/
function template_announcement_send()
{
global $context, $txt, $scripturl;
echo '
<div id="announcement">
<form action="' . $scripturl . '?action=announce;sa=send" method="post" accept-charset="UTF-8" name="autoSubmit" id="autoSubmit">
<div class="content">
<p class="infobox">', $txt['announce_sending'], ' <a href="', $scripturl, '?topic=', $context['current_topic'], '.0" target="_blank" class="new_win">: ', $context['topic_subject'], '</a></p>
<div class="progress_bar">
<div class="full_bar">', $context['percentage_done'], '% ', $txt['announce_done'], '</div>
<div class="green_percent" style="width: ', $context['percentage_done'], '%;"> </div>
</div>
<hr />
<div class="submitbutton">
<input type="submit" name="cont" value="', $txt['announce_continue'], '" />
<input type="hidden" name="', $context['session_var'], '" value="', $context['session_id'], '" />
<input type="hidden" name="topic" value="', $context['current_topic'], '" />
<input type="hidden" name="move" value="', $context['move'], '" />
<input type="hidden" name="goback" value="', $context['go_back'], '" />
<input type="hidden" name="start" value="', $context['start'], '" />
<input type="hidden" name="membergroups" value="', $context['membergroups'], '" />
</div>
</div>
</form>
</div>
<script>
doAutoSubmit(3, ', JavaScriptEscape($txt['announce_continue']), ');
</script>';
}
|
nwsw/Elkarte
|
themes/default/Announce.template.php
|
PHP
|
bsd-3-clause
| 3,478
|
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\RuleAction */
$this->title = Yii::t('app', 'Update {modelClass}: ', [
'modelClass' => 'Rule Action',
]) . ' ' . $model->id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Rule Actions'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="rule-action-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
|
hvos234/raspberrypi.home
|
views/rule-action/update.php
|
PHP
|
bsd-3-clause
| 630
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.summary — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="../_static/material.css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" />
<script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.transform_jacobian" href="statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.transform_jacobian.html" />
<link rel="prev" title="statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.smooth" href="statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.smooth.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.summary" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.13.2</span>
<span class="md-header-nav__topic"> statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.summary </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="get" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../../versions-v2.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../statespace.html" class="md-tabs__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a></li>
<li class="md-tabs__item"><a href="statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.html" class="md-tabs__link">statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.13.2</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a>
</li>
<li class="md-nav__item">
<a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a>
</li>
<li class="md-nav__item">
<a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.summary.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<section id="statsmodels-tsa-statespace-dynamic-factor-mq-dynamicfactormq-summary">
<h1 id="generated-statsmodels-tsa-statespace-dynamic-factor-mq-dynamicfactormq-summary--page-root">statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.summary<a class="headerlink" href="#generated-statsmodels-tsa-statespace-dynamic-factor-mq-dynamicfactormq-summary--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py method">
<dt class="sig sig-object py" id="statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.summary">
<span class="sig-prename descclassname"><span class="pre">DynamicFactorMQ.</span></span><span class="sig-name descname"><span class="pre">summary</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">truncate_endog_names</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/tsa/statespace/dynamic_factor_mq.html#DynamicFactorMQ.summary"><span class="viewcode-link"><span class="pre">[source]</span></span></a><a class="headerlink" href="#statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.summary" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a summary table describing the model.</p>
<dl class="field-list">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><dl>
<dt><strong>truncate_endog_names</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/functions.html#int" title="(in Python v3.10)"><code class="docutils literal notranslate"><span class="pre">int</span></code></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>The number of characters to show for names of observed variables.
Default is 24 if there is more than one observed variable, or
an unlimited number of there is only one.</p>
</dd>
</dl>
</dd>
</dl>
</dd></dl>
</section>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.smooth.html" title="statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.smooth"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.smooth </span>
</div>
</a>
<a href="statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.transform_jacobian.html" title="statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.transform_jacobian"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.transform_jacobian </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Feb 08, 2022.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 4.4.0.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html>
|
statsmodels/statsmodels.github.io
|
v0.13.2/generated/statsmodels.tsa.statespace.dynamic_factor_mq.DynamicFactorMQ.summary.html
|
HTML
|
bsd-3-clause
| 19,208
|
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function
from future.builtins import zip
from six import StringIO
import unittest
import warnings
from functools import partial
from skbio import (read, write, Sequence, DNA, RNA, Protein,
SequenceCollection, Alignment)
from skbio.io import FASTQFormatError
from skbio.io.fastq import (
_fastq_sniffer, _fastq_to_generator, _fastq_to_sequence_collection,
_fastq_to_alignment, _generator_to_fastq, _sequence_collection_to_fastq,
_alignment_to_fastq)
from skbio.util import get_data_path
import numpy as np
# Note: the example FASTQ files with file extension .fastq are taken from the
# following open-access publication's supplementary data:
#
# P.J.A. Cock, C.J. Fields, N. Goto, M.L. Heuer and P.M. Rice (2009). The
# Sanger FASTQ file format for sequences with quality scores, and the
# Solexa/Illumina FASTQ variants.
#
# See licenses/fastq-example-files-readme.txt for the original README that
# accompanied these files, which includes the terms of use and detailed
# description of the files.
#
# The example files bearing the original filenames have not been modified from
# their original form.
def _drop_kwargs(kwargs, *args):
for arg in args:
if arg in kwargs:
kwargs.pop(arg)
class TestSniffer(unittest.TestCase):
def setUp(self):
self.positives = [get_data_path(e) for e in [
'fastq_multi_seq_sanger',
'fastq_multi_blank_between_records',
'fastq_multi_ws_lines_between_records',
'fastq_multi_blank_end_of_file',
'fastq_multi_ws_lines_end_of_file',
'fastq_multi_whitespace_stripping',
'fastq_blank_lines',
'fastq_whitespace_only_lines',
'fastq_single_seq_illumina1.3',
'fastq_wrapping_as_illumina_no_description',
'fastq_wrapping_as_sanger_no_description',
'fastq_wrapping_original_sanger_no_description',
'fastq_writer_illumina1.3_defaults',
'fastq_writer_sanger_defaults',
'fastq_writer_sanger_non_defaults',
'fastq_5_blanks_start_of_file',
'fastq_5_ws_lines_start_of_file',
'illumina_full_range_as_illumina.fastq',
'illumina_full_range_as_sanger.fastq',
'illumina_full_range_original_illumina.fastq',
'longreads_as_illumina.fastq',
'longreads_as_sanger.fastq',
'longreads_original_sanger.fastq',
'misc_dna_as_illumina.fastq',
'misc_dna_as_sanger.fastq',
'misc_dna_original_sanger.fastq',
'misc_rna_as_illumina.fastq',
'misc_rna_as_sanger.fastq',
'misc_rna_original_sanger.fastq',
'sanger_full_range_as_illumina.fastq',
'sanger_full_range_as_sanger.fastq',
'sanger_full_range_original_sanger.fastq',
'solexa_full_range_original_solexa.fastq',
'wrapping_as_illumina.fastq',
'wrapping_as_sanger.fastq',
'wrapping_original_sanger.fastq'
]]
self.negatives = [get_data_path(e) for e in [
'empty',
'whitespace_only',
'fastq_multi_blank_start_of_file',
'fastq_multi_ws_lines_start_of_file',
'fastq_invalid_blank_after_header',
'fastq_invalid_blank_after_seq',
'fastq_invalid_blank_after_plus',
'fastq_invalid_blank_within_seq',
'fastq_invalid_blank_within_qual',
'fastq_invalid_ws_line_after_header',
'fastq_invalid_ws_line_after_seq',
'fastq_invalid_ws_line_after_plus',
'fastq_invalid_ws_line_within_seq',
'fastq_invalid_ws_line_within_qual',
'fastq_invalid_missing_header',
'fastq_invalid_missing_seq_data',
'error_diff_ids.fastq',
'error_double_qual.fastq',
'error_double_seq.fastq',
'error_long_qual.fastq',
'error_no_qual.fastq',
'error_qual_del.fastq',
'error_qual_escape.fastq',
'error_qual_null.fastq',
'error_qual_space.fastq',
'error_qual_tab.fastq',
'error_qual_unit_sep.fastq',
'error_qual_vtab.fastq',
'error_short_qual.fastq',
'error_spaces.fastq',
'error_tabs.fastq',
'error_trunc_at_seq.fastq',
'error_trunc_at_plus.fastq',
'error_trunc_at_qual.fastq',
'error_trunc_in_title.fastq',
'error_trunc_in_seq.fastq',
'error_trunc_in_plus.fastq',
'error_trunc_in_qual.fastq',
]]
def test_positives(self):
for fp in self.positives:
self.assertEqual(_fastq_sniffer(fp), (True, {}))
def test_negatives(self):
for fp in self.negatives:
self.assertEqual(_fastq_sniffer(fp), (False, {}))
class TestReaders(unittest.TestCase):
def setUp(self):
self.valid_configurations = [
([get_data_path('empty'),
get_data_path('whitespace_only')],
[{},
{'variant': 'illumina1.8'},
{'phred_offset': 33,
'constructor': DNA}],
[]),
([get_data_path('fastq_single_seq_illumina1.3')], [
{'variant': 'illumina1.3'},
{'phred_offset': 64},
{'variant': 'illumina1.3',
'constructor': Protein},
], [
('', 'bar\t baz', 'aCGT', [33, 34, 35, 36])
]),
([get_data_path('fastq_multi_seq_sanger'),
get_data_path('fastq_whitespace_only_lines'),
get_data_path('fastq_blank_lines'),
get_data_path('fastq_multi_blank_between_records'),
get_data_path('fastq_multi_ws_lines_between_records'),
get_data_path('fastq_multi_blank_end_of_file'),
get_data_path('fastq_multi_ws_lines_end_of_file'),
get_data_path('fastq_multi_blank_start_of_file'),
get_data_path('fastq_multi_ws_lines_start_of_file'),
get_data_path('fastq_multi_whitespace_stripping')], [
{'variant': 'sanger'},
{'phred_offset': 33, 'seq_num': 2},
{'variant': 'sanger',
'constructor': partial(RNA, validate=False),
'seq_num': 3},
], [
('foo', 'bar baz', 'AACCGG',
[16, 17, 18, 19, 20, 21]),
('bar', 'baz foo', 'TTGGCC',
[23, 22, 21, 20, 19, 18]),
('baz', 'foo bar', 'GATTTC',
[20, 21, 22, 23, 24, 18])
]),
]
self.invalid_files = [(get_data_path(e[0]), e[1], e[2]) for e in [
('fastq_invalid_blank_after_header', FASTQFormatError,
'blank or whitespace-only line.*after header.*in FASTQ'),
('fastq_invalid_blank_after_seq', FASTQFormatError,
"blank or whitespace-only line.*before '\+' in FASTQ"),
('fastq_invalid_blank_after_plus', FASTQFormatError,
"blank or whitespace-only line.*after '\+'.*in FASTQ"),
('fastq_invalid_blank_within_seq', FASTQFormatError,
'blank or whitespace-only line.*within sequence.*FASTQ'),
('fastq_invalid_blank_within_qual', FASTQFormatError,
"blank or whitespace-only line.*within quality scores.*in FASTQ"),
('fastq_invalid_ws_line_after_header', FASTQFormatError,
'blank or whitespace-only line.*after header.*in FASTQ'),
('fastq_invalid_ws_line_after_seq', FASTQFormatError,
"blank or whitespace-only line.*before '\+' in FASTQ"),
('fastq_invalid_ws_line_after_plus', FASTQFormatError,
"blank or whitespace-only line.*after '\+'.*in FASTQ"),
('fastq_invalid_ws_line_within_seq', FASTQFormatError,
'blank or whitespace-only line.*within sequence.*FASTQ'),
('fastq_invalid_ws_line_within_qual', FASTQFormatError,
"blank or whitespace-only line.*within quality scores.*in FASTQ"),
('fastq_invalid_missing_header', FASTQFormatError,
"sequence.*header.*start of file: 'seq1 desc1'"),
('fastq_invalid_missing_seq_data', FASTQFormatError,
'without sequence data'),
('error_diff_ids.fastq', FASTQFormatError,
"header lines do not match: "
"'SLXA-B3_649_FC8437_R1_1_1_850_123' != "
"'SLXA-B3_649_FC8437_R1_1_1_850_124'"),
('error_double_qual.fastq', FASTQFormatError,
"Extra quality.*'\+SLXA-B3_649_FC8437_R1_1_1_850_123'"),
('error_double_seq.fastq', FASTQFormatError,
'FASTQ record that is missing a quality \(\+\) header line'),
('error_long_qual.fastq', FASTQFormatError, "Extra quality.*'Y'"),
('error_no_qual.fastq', FASTQFormatError,
"blank or whitespace-only line.*after '\+'.*in FASTQ"),
('error_qual_del.fastq', ValueError,
'Decoded Phred score.*out of range'),
('error_qual_escape.fastq', ValueError,
'Decoded Phred score.*out of range'),
('error_qual_null.fastq', ValueError,
'Decoded Phred score.*out of range'),
('error_qual_space.fastq', ValueError,
'Decoded Phred score.*out of range'),
('error_qual_tab.fastq', ValueError,
'Decoded Phred score.*out of range'),
('error_qual_unit_sep.fastq', ValueError,
'Decoded Phred score.*out of range'),
('error_qual_vtab.fastq', ValueError,
'Decoded Phred score.*out of range'),
('error_short_qual.fastq', FASTQFormatError,
"Extra quality.*'SLXA-B3_649_FC8437_R1_1_1_362_549'"),
('error_spaces.fastq', FASTQFormatError,
"whitespace.*sequence data: 'GATGTGCAA TACCTTTGTA GAGGAA'"),
('error_tabs.fastq', FASTQFormatError,
r"whitespace.*sequence data: 'GATGTGCAA\\tTACCTTTGTA\\tGAGGAA'"),
('error_trunc_at_seq.fastq', FASTQFormatError,
'incomplete/truncated.*FASTQ'),
('error_trunc_at_plus.fastq', FASTQFormatError,
'incomplete/truncated.*FASTQ'),
('error_trunc_at_qual.fastq', FASTQFormatError,
'incomplete/truncated.*end of file'),
('error_trunc_in_title.fastq', FASTQFormatError,
'incomplete/truncated.*end of file'),
('error_trunc_in_seq.fastq', FASTQFormatError,
'incomplete/truncated.*end of file'),
('error_trunc_in_plus.fastq', FASTQFormatError,
"header lines do not match: "
"'SLXA-B3_649_FC8437_R1_1_1_183_714' != 'SLXA-B3_649_FC'"),
('error_trunc_in_qual.fastq', FASTQFormatError,
'incomplete/truncated.*end of file')
]]
def test_fastq_to_generator_valid_files(self):
for valid_files, kwargs, components in self.valid_configurations:
for valid in valid_files:
for observed_kwargs in kwargs:
_drop_kwargs(observed_kwargs, 'seq_num')
constructor = observed_kwargs.get('constructor', Sequence)
# Can't use partials for this because the read
# function below can't operate on partials
expected_kwargs = {}
if hasattr(constructor, 'lowercase'):
expected_kwargs['lowercase'] = 'introns'
observed_kwargs['lowercase'] = 'introns'
expected = [constructor(c[2],
metadata={'id': c[0],
'description': c[1]},
positional_metadata={'quality': np.array(c[3],
dtype=np.uint8)},
**expected_kwargs)
for c in components]
observed = list(_fastq_to_generator(valid,
**observed_kwargs))
self.assertEqual(len(expected), len(observed))
for o, e in zip(observed, expected):
self.assertEqual(o, e)
def test_fastq_to_generator_invalid_files_all_variants(self):
# files that should be invalid for all variants, as well as custom
# phred offsets
for fp, error_type, error_msg_regex in self.invalid_files:
for variant in 'sanger', 'illumina1.3', 'illumina1.8':
with self.assertRaisesRegexp(error_type, error_msg_regex):
list(_fastq_to_generator(fp, variant=variant))
for offset in 33, 64, 40, 77:
with self.assertRaisesRegexp(error_type, error_msg_regex):
list(_fastq_to_generator(fp, phred_offset=offset))
def test_fastq_to_generator_invalid_files_illumina(self):
# files that should be invalid for illumina1.3 and illumina1.8 variants
fps = [get_data_path(fp) for fp in
['sanger_full_range_original_sanger.fastq',
'solexa_full_range_original_solexa.fastq']]
for fp in fps:
with self.assertRaisesRegexp(ValueError, 'out of range \[0, 62\]'):
list(_fastq_to_generator(fp, variant='illumina1.3'))
with self.assertRaisesRegexp(ValueError, 'out of range \[0, 62\]'):
list(_fastq_to_generator(fp, variant='illumina1.8'))
def test_fastq_to_generator_solexa(self):
# solexa support isn't implemented yet. should raise error even with
# valid solexa file
with self.assertRaises(NotImplementedError):
list(_fastq_to_generator(
get_data_path('solexa_full_range_original_solexa.fastq'),
variant='solexa'))
def test_fastq_to_sequence(self):
for constructor in [Sequence, DNA, RNA, Protein]:
for valid_files, kwargs, components in self.valid_configurations:
for valid in valid_files:
# skip empty file case since we cannot read a specific
# sequencefrom an empty file
if len(components) == 0:
continue
for observed_kwargs in kwargs:
expected_kwargs = {}
# TODO:
# some of the test files contain characters which are
# invalid for RNA, so don't validate for now. Need to
# fix this
if constructor is RNA:
observed_kwargs['validate'] = False
expected_kwargs['validate'] = False
_drop_kwargs(observed_kwargs, 'constructor')
# Can't use partials for this because the read
# function below can't operate on partials
if hasattr(constructor, 'lowercase'):
expected_kwargs['lowercase'] = 'introns'
observed_kwargs['lowercase'] = 'introns'
seq_num = observed_kwargs.get('seq_num', 1)
c = components[seq_num - 1]
expected = \
constructor(
c[2], metadata={'id': c[0],
'description': c[1]},
positional_metadata={'quality': np.array(c[3],
dtype=np.uint8)},
**expected_kwargs)
observed = read(valid, into=constructor,
format='fastq', verify=False,
**observed_kwargs)
self.assertEqual(observed, expected)
def test_fastq_to_sequence_collection(self):
for valid_files, kwargs, components in self.valid_configurations:
for valid in valid_files:
for observed_kwargs in kwargs:
_drop_kwargs(observed_kwargs, 'seq_num')
constructor = observed_kwargs.get('constructor', Sequence)
# Can't use partials for this because the read
# function below can't operate on partials
expected_kwargs = {}
if hasattr(constructor, 'lowercase'):
expected_kwargs['lowercase'] = 'introns'
observed_kwargs['lowercase'] = 'introns'
expected = SequenceCollection(
[constructor(
c[2], metadata={'id': c[0], 'description': c[1]},
positional_metadata={'quality': np.array(c[3],
np.uint8)},
**expected_kwargs)
for c in components])
observed = _fastq_to_sequence_collection(valid,
**observed_kwargs)
self.assertEqual(observed, expected)
def test_fastq_to_alignment(self):
for valid_files, kwargs, components in self.valid_configurations:
for valid in valid_files:
for observed_kwargs in kwargs:
_drop_kwargs(observed_kwargs, 'seq_num')
constructor = observed_kwargs.get('constructor', Sequence)
# Can't use partials for this because the read
# function below can't operate on partials
expected_kwargs = {}
if hasattr(constructor, 'lowercase'):
expected_kwargs['lowercase'] = 'introns'
observed_kwargs['lowercase'] = 'introns'
expected = Alignment(
[constructor(
c[2], metadata={'id': c[0],
'description': c[1]},
positional_metadata={'quality': np.array(c[3],
dtype=np.uint8)},
**expected_kwargs)
for c in components])
observed = _fastq_to_alignment(valid, **observed_kwargs)
self.assertEqual(observed, expected)
class TestWriters(unittest.TestCase):
def setUp(self):
self.valid_files = [
([
('f o o', 'bar\n\nbaz', 'AaCcGg',
[16, 17, 18, 19, 20, 21]),
('bar', 'baz foo', 'TtGgCc',
[23, 22, 21, 20, 19, 18]),
('ba\n\t\tz', 'foo bar', 'gAtTtC',
[20, 21, 22, 23, 24, 18])
], [
({'variant': 'sanger'},
get_data_path('fastq_writer_sanger_defaults')),
({'phred_offset': 33},
get_data_path('fastq_writer_sanger_defaults')),
({'variant': 'illumina1.8'},
get_data_path('fastq_writer_sanger_defaults')),
({'variant': 'illumina1.3'},
get_data_path('fastq_writer_illumina1.3_defaults')),
({'variant': 'sanger', 'id_whitespace_replacement': '%',
'description_newline_replacement': '^'},
get_data_path('fastq_writer_sanger_non_defaults'))
]),
]
def test_generator_to_fastq_kwargs_passed(self):
for components, kwargs_expected_fp in self.valid_files:
for kwargs, expected_fp in kwargs_expected_fp:
def gen():
for c in components:
yield Sequence(
c[2], metadata={'id': c[0], 'description': c[1]},
positional_metadata={'quality': c[3]})
fh = StringIO()
_generator_to_fastq(gen(), fh, **kwargs)
observed = fh.getvalue()
fh.close()
with open(expected_fp, 'U') as f:
expected = f.read()
self.assertEqual(observed, expected)
def test_sequence_to_fastq_kwargs_passed(self):
for constructor in [Sequence, DNA, RNA, Protein]:
for components, kwargs_expected_fp in self.valid_files:
for expected_kwargs, expected_fp in kwargs_expected_fp:
observed_kwargs = {}
# TODO:
# some of the test files contain characters which are
# invalid for RNA, so don't validate for now. Need to
# fix this
if constructor is RNA:
observed_kwargs['validate'] = False
# Can't use partials for this because the read
# function below can't operate on partials
if hasattr(constructor, 'lowercase'):
expected_kwargs['lowercase'] = 'introns'
observed_kwargs['lowercase'] = 'introns'
fh = StringIO()
for c in components:
obj = constructor(
c[2],
metadata={'id': c[0], 'description': c[1]},
positional_metadata={'quality': c[3]},
**observed_kwargs)
write(obj, into=fh, format='fastq', **expected_kwargs)
observed = fh.getvalue()
fh.close()
with open(expected_fp, 'U') as f:
expected = f.read()
self.assertEqual(observed, expected)
def test_sequence_collection_to_fastq_kwargs_passed(self):
for components, kwargs_expected_fp in self.valid_files:
for kwargs, expected_fp in kwargs_expected_fp:
obj = SequenceCollection([
DNA(c[2], metadata={'id': c[0], 'description': c[1]},
positional_metadata={'quality': c[3]},
lowercase='introns')
for c in components])
fh = StringIO()
kwargs['lowercase'] = 'introns'
_sequence_collection_to_fastq(obj, fh, **kwargs)
observed = fh.getvalue()
fh.close()
with open(expected_fp, 'U') as f:
expected = f.read()
self.assertEqual(observed, expected)
def test_alignment_to_fastq_kwargs_passed(self):
for components, kwargs_expected_fp in self.valid_files:
for kwargs, expected_fp in kwargs_expected_fp:
obj = Alignment([
Protein(c[2], metadata={'id': c[0], 'description': c[1]},
positional_metadata={'quality': c[3]},
lowercase='introns')
for c in components])
fh = StringIO()
kwargs['lowercase'] = 'introns'
_alignment_to_fastq(obj, fh, **kwargs)
observed = fh.getvalue()
fh.close()
with open(expected_fp, 'U') as f:
expected = f.read()
self.assertEqual(observed, expected)
def test_generator_to_fastq_no_qual(self):
def gen():
yield Sequence('ACGT',
metadata={'id': 'foo', 'description': 'bar'},
positional_metadata={'quality': range(4)})
yield Sequence('ACG', metadata={'id': 'foo', 'description': 'bar'})
with self.assertRaisesRegexp(ValueError, '2nd.*quality scores'):
_generator_to_fastq(gen(), StringIO(), variant='illumina1.8')
class TestConversions(unittest.TestCase):
def setUp(self):
self.conversions = [
(get_data_path('empty'),
get_data_path('empty'), [
({'variant': 'sanger'}, {'phred_offset': 42}),
]),
(get_data_path('longreads_original_sanger.fastq'),
get_data_path('longreads_as_sanger.fastq'), [
({'variant': 'sanger'}, {'variant': 'sanger'}),
({'phred_offset': 33}, {'variant': 'sanger'}),
({'variant': 'sanger'}, {'phred_offset': 33})
]),
(get_data_path('longreads_original_sanger.fastq'),
get_data_path('longreads_as_illumina.fastq'), [
({'variant': 'sanger'}, {'variant': 'illumina1.3'}),
({'phred_offset': 33}, {'variant': 'illumina1.3'}),
({'variant': 'sanger'}, {'phred_offset': 64})
]),
(get_data_path('wrapping_original_sanger.fastq'),
get_data_path('wrapping_as_sanger.fastq'), [
({'variant': 'sanger'}, {'variant': 'sanger'}),
({'phred_offset': 33}, {'variant': 'sanger'}),
({'variant': 'sanger'}, {'phred_offset': 33})
]),
(get_data_path('wrapping_original_sanger.fastq'),
get_data_path('wrapping_as_illumina.fastq'), [
({'variant': 'sanger'}, {'variant': 'illumina1.3'}),
({'phred_offset': 33}, {'variant': 'illumina1.3'}),
({'variant': 'sanger'}, {'phred_offset': 64})
]),
(get_data_path('sanger_full_range_original_sanger.fastq'),
get_data_path('sanger_full_range_as_sanger.fastq'), [
({'variant': 'sanger'}, {'variant': 'sanger'}),
({'phred_offset': 33}, {'variant': 'sanger'}),
({'variant': 'sanger'}, {'phred_offset': 33})
]),
(get_data_path('sanger_full_range_original_sanger.fastq'),
get_data_path('sanger_full_range_as_illumina.fastq'), [
({'variant': 'sanger'}, {'variant': 'illumina1.3'}),
({'phred_offset': 33}, {'variant': 'illumina1.3'}),
({'variant': 'sanger'}, {'phred_offset': 64})
]),
(get_data_path('illumina_full_range_original_illumina.fastq'),
get_data_path('illumina_full_range_as_illumina.fastq'), [
({'variant': 'illumina1.3'}, {'variant': 'illumina1.3'}),
({'phred_offset': 64}, {'variant': 'illumina1.3'}),
({'variant': 'illumina1.3'}, {'phred_offset': 64})
]),
(get_data_path('illumina_full_range_original_illumina.fastq'),
get_data_path('illumina_full_range_as_sanger.fastq'), [
({'variant': 'illumina1.3'}, {'variant': 'sanger'}),
({'phred_offset': 64}, {'variant': 'sanger'}),
({'variant': 'illumina1.3'}, {'phred_offset': 33})
]),
(get_data_path('misc_dna_original_sanger.fastq'),
get_data_path('misc_dna_as_sanger.fastq'), [
({'variant': 'sanger'}, {'variant': 'sanger'}),
({'phred_offset': 33}, {'variant': 'sanger'}),
({'variant': 'sanger'}, {'phred_offset': 33})
]),
(get_data_path('misc_dna_original_sanger.fastq'),
get_data_path('misc_dna_as_illumina.fastq'), [
({'variant': 'sanger'}, {'variant': 'illumina1.3'}),
({'phred_offset': 33}, {'variant': 'illumina1.3'}),
({'variant': 'sanger'}, {'phred_offset': 64})
]),
(get_data_path('misc_rna_original_sanger.fastq'),
get_data_path('misc_rna_as_sanger.fastq'), [
({'variant': 'sanger'}, {'variant': 'sanger'}),
({'phred_offset': 33}, {'variant': 'sanger'}),
({'variant': 'sanger'}, {'phred_offset': 33})
]),
(get_data_path('misc_rna_original_sanger.fastq'),
get_data_path('misc_rna_as_illumina.fastq'), [
({'variant': 'sanger'}, {'variant': 'illumina1.3'}),
({'phred_offset': 33}, {'variant': 'illumina1.3'}),
({'variant': 'sanger'}, {'phred_offset': 64})
]),
(get_data_path('fastq_wrapping_original_sanger_no_description'),
get_data_path('fastq_wrapping_as_sanger_no_description'), [
({'variant': 'sanger'}, {'variant': 'sanger'}),
({'phred_offset': 33}, {'variant': 'sanger'}),
({'variant': 'sanger'}, {'phred_offset': 33})
]),
(get_data_path('fastq_wrapping_original_sanger_no_description'),
get_data_path('fastq_wrapping_as_illumina_no_description'), [
({'variant': 'sanger'}, {'variant': 'illumina1.3'}),
({'phred_offset': 33}, {'variant': 'illumina1.3'}),
({'variant': 'sanger'}, {'phred_offset': 64})
]),
]
def test_conversion(self):
for from_fp, to_fp, kwargs in self.conversions:
for from_kwargs, to_kwargs in kwargs:
read_gen = _fastq_to_generator(from_fp, **from_kwargs)
fh = StringIO()
# will issue warning when truncating quality scores
with warnings.catch_warnings(record=True):
warnings.simplefilter("ignore")
_generator_to_fastq(read_gen, fh, **to_kwargs)
obs = fh.getvalue()
fh.close()
with open(to_fp, 'U') as fh:
exp = fh.read()
self.assertEqual(obs, exp)
if __name__ == '__main__':
unittest.main()
|
Achuth17/scikit-bio
|
skbio/io/tests/test_fastq.py
|
Python
|
bsd-3-clause
| 30,554
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- qtpropertybrowser-2.5_1-opensource/src/qtpropertymanager.cpp -->
<head>
<title>List of All Members for QtTimePropertyManager</title>
<link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><img src="images/qt-logo.png" align="left" width="57" height="67" border="0" /></td>
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a></td>
</tr></table><h1 class="title">List of All Members for QtTimePropertyManager</h1>
<p>This is the complete list of members for <a href="qttimepropertymanager.html">QtTimePropertyManager</a>, including inherited members.</p>
<p><table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr><td width="45%" valign="top"><ul>
<li><div class="fn"></div><a href="qttimepropertymanager.html#QtTimePropertyManager">QtTimePropertyManager</a> ( QObject * )</li>
<li><div class="fn"></div><a href="qttimepropertymanager.html#dtor.QtTimePropertyManager">~QtTimePropertyManager</a> ()</li>
<li><div class="fn"></div><a href="qtabstractpropertymanager.html#addProperty">addProperty</a> ( const QString & ) : QtProperty *</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#blockSignals">blockSignals</a> ( bool )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#childEvent">childEvent</a> ( QChildEvent * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#children">children</a> () const</li>
<li><div class="fn"></div><a href="qtabstractpropertymanager.html#clear">clear</a> () const</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#connect">connect</a> ( const QObject *, const char *, const QObject *, const char *, Qt::ConnectionType )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#connect-2">connect</a> ( const QObject *, const char *, const char *, Qt::ConnectionType ) const</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#connectNotify">connectNotify</a> ( const char * )</li>
<li><div class="fn"></div><a href="qtabstractpropertymanager.html#createProperty">createProperty</a> () : QtProperty *</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#customEvent">customEvent</a> ( QEvent * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#d_ptr-var">d_ptr</a> : </li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#deleteLater">deleteLater</a> ()</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#destroyed">destroyed</a> ( QObject * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#disconnect">disconnect</a> ( const QObject *, const char *, const QObject *, const char * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#disconnect-2">disconnect</a> ( const char *, const QObject *, const char * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#disconnect-3">disconnect</a> ( const QObject *, const char * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#disconnectNotify">disconnectNotify</a> ( const char * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#dumpObjectInfo">dumpObjectInfo</a> ()</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#dumpObjectTree">dumpObjectTree</a> ()</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#dynamicPropertyNames">dynamicPropertyNames</a> () const</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#event">event</a> ( QEvent * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#eventFilter">eventFilter</a> ( QObject *, QEvent * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#findChild">findChild</a> ( const QString & ) const</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#findChildren">findChildren</a> ( const QString & ) const</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#findChildren-2">findChildren</a> ( const QRegExp & ) const</li>
<li><div class="fn"></div><a href="qtabstractpropertymanager.html#hasValue">hasValue</a> ( const QtProperty * ) const : bool</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#inherits">inherits</a> ( const char * ) const</li>
<li><div class="fn"></div><a href="qtabstractpropertymanager.html#initializeProperty">initializeProperty</a> ( QtProperty * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#installEventFilter">installEventFilter</a> ( QObject * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#isWidgetType">isWidgetType</a> () const</li>
</ul></td><td valign="top"><ul>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#killTimer">killTimer</a> ( int )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#metaObject">metaObject</a> () const</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#moveToThread">moveToThread</a> ( QThread * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#objectName-prop">objectName</a> () const</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#parent">parent</a> () const</li>
<li><div class="fn"></div><a href="qtabstractpropertymanager.html#properties">properties</a> () const : QSet<QtProperty *></li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#property">property</a> ( const char * ) const</li>
<li><div class="fn"></div><a href="qtabstractpropertymanager.html#propertyChanged">propertyChanged</a> ( QtProperty * )</li>
<li><div class="fn"></div><a href="qtabstractpropertymanager.html#propertyDestroyed">propertyDestroyed</a> ( QtProperty * )</li>
<li><div class="fn"></div><a href="qtabstractpropertymanager.html#propertyInserted">propertyInserted</a> ( QtProperty *, QtProperty *, QtProperty * )</li>
<li><div class="fn"></div><a href="qtabstractpropertymanager.html#propertyRemoved">propertyRemoved</a> ( QtProperty *, QtProperty * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#receivers">receivers</a> ( const char * ) const</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#removeEventFilter">removeEventFilter</a> ( QObject * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#sender">sender</a> () const</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#objectName-prop">setObjectName</a> ( const QString & )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#setParent">setParent</a> ( QObject * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#setProperty">setProperty</a> ( const char *, const QVariant & )</li>
<li><div class="fn"></div><a href="qttimepropertymanager.html#setValue">setValue</a> ( QtProperty *, const QTime & )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#signalsBlocked">signalsBlocked</a> () const</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#startTimer">startTimer</a> ( int )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#staticMetaObject-var">staticMetaObject</a> : </li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#staticQtMetaObject-var">staticQtMetaObject</a> : </li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#thread">thread</a> () const</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#timerEvent">timerEvent</a> ( QTimerEvent * )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#tr">tr</a> ( const char *, const char *, int )</li>
<li><div class="fn"></div><a href="http://qt.nokia.com/doc/4.5/qobject.html#trUtf8">trUtf8</a> ( const char *, const char *, int )</li>
<li><div class="fn"></div><a href="qtabstractpropertymanager.html#uninitializeProperty">uninitializeProperty</a> ( QtProperty * )</li>
<li><div class="fn"></div><a href="qttimepropertymanager.html#value">value</a> ( const QtProperty * ) const : QTime</li>
<li><div class="fn"></div><a href="qttimepropertymanager.html#valueChanged">valueChanged</a> ( QtProperty *, const QTime & )</li>
<li><div class="fn"></div><a href="qtabstractpropertymanager.html#valueIcon">valueIcon</a> ( const QtProperty * ) const : QIcon</li>
<li><div class="fn"></div><a href="qtabstractpropertymanager.html#valueText">valueText</a> ( const QtProperty * ) const : QString</li>
</ul>
</td></tr>
</table></p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%" align="left">Copyright © 2009 Nokia Corporation and/or its subsidiary(-ies)</td>
<td width="40%" align="center"><a href="http://qt.nokia.com/doc/trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt Solutions</div></td>
</tr></table></div></address></body>
</html>
|
kulibali/neurolab
|
src/thirdparty/qtpropertybrowser/qtpropertybrowser-2.5_1-opensource/doc/html/qttimepropertymanager-members.html
|
HTML
|
bsd-3-clause
| 9,760
|
# 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 'UserInfo.avatar'
db.add_column('canvas_userinfo', 'avatar', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['canvas.Content'], null=True), keep_default=False)
def backwards(self, orm):
# Deleting field 'UserInfo.avatar'
db.delete_column('canvas_userinfo', 'avatar_id')
models = {
'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': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", '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': '254', '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'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'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'})
},
'canvas.apiapp': {
'Meta': {'object_name': 'APIApp'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
},
'canvas.apiauthtoken': {
'Meta': {'unique_together': "(('user', 'app'),)", 'object_name': 'APIAuthToken'},
'app': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.APIApp']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'token': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'canvas.bestof': {
'Meta': {'object_name': 'BestOf'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'best_of'", 'null': 'True', 'blank': 'True', 'to': "orm['canvas.Category']"}),
'chosen_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'best_of'", 'to': "orm['canvas.Comment']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'timestamp': ('canvas.util.UnixTimestampField', [], {})
},
'canvas.category': {
'Meta': {'object_name': 'Category'},
'description': ('django.db.models.fields.CharField', [], {'max_length': '140'}),
'founded': ('django.db.models.fields.FloatField', [], {'default': '1298956320'}),
'founder': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'founded_groups'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'moderators': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'moderated_categories'", 'symmetrical': 'False', 'to': "orm['auth.User']"}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'}),
'visibility': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'canvas.comment': {
'Meta': {'object_name': 'Comment'},
'anonymous': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'comments'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}),
'category': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'comments'", 'null': 'True', 'blank': 'True', 'to': "orm['canvas.Category']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ip': ('django.db.models.fields.IPAddressField', [], {'default': "'0.0.0.0'", 'max_length': '15'}),
'judged': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'ot_hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'parent_comment': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'replies'", 'null': 'True', 'blank': 'True', 'to': "orm['canvas.Comment']"}),
'parent_content': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'comments'", 'null': 'True', 'to': "orm['canvas.Content']"}),
'replied_comment': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['canvas.Comment']", 'null': 'True', 'blank': 'True'}),
'reply_content': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'used_in_comments'", 'null': 'True', 'to': "orm['canvas.Content']"}),
'reply_text': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'blank': 'True'}),
'score': ('django.db.models.fields.FloatField', [], {'default': '0', 'db_index': 'True'}),
'timestamp': ('canvas.util.UnixTimestampField', [], {'default': '0'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '140', 'blank': 'True'}),
'visibility': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'canvas.commentflag': {
'Meta': {'object_name': 'CommentFlag'},
'comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'flags'", 'to': "orm['canvas.Comment']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ip': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}),
'timestamp': ('canvas.util.UnixTimestampField', [], {}),
'type_id': ('django.db.models.fields.IntegerField', [], {}),
'undone': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'flags'", 'to': "orm['auth.User']"})
},
'canvas.commentmoderationlog': {
'Meta': {'object_name': 'CommentModerationLog'},
'comment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Comment']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'moderator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}),
'note': ('django.db.models.fields.TextField', [], {}),
'timestamp': ('canvas.util.UnixTimestampField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'moderated_comments_log'", 'to': "orm['auth.User']"}),
'visibility': ('django.db.models.fields.IntegerField', [], {})
},
'canvas.commentpin': {
'Meta': {'object_name': 'CommentPin'},
'auto': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'comment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Comment']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'timestamp': ('canvas.util.UnixTimestampField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'canvas.commentsticker': {
'Meta': {'object_name': 'CommentSticker'},
'comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'stickers'", 'to': "orm['canvas.Comment']"}),
'epic_message': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '140', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ip': ('django.db.models.fields.IPAddressField', [], {'max_length': '15'}),
'timestamp': ('canvas.util.UnixTimestampField', [], {}),
'type_id': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'})
},
'canvas.commentstickerlog': {
'Meta': {'object_name': 'CommentStickerLog'},
'comment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Comment']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'canvas.content': {
'Meta': {'object_name': 'Content'},
'alpha': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'animated': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.CharField', [], {'max_length': '40', 'primary_key': 'True'}),
'ip': ('django.db.models.fields.IPAddressField', [], {'default': "'0.0.0.0'", 'max_length': '15'}),
'remix_of': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'remixes'", 'null': 'True', 'to': "orm['canvas.Content']"}),
'remix_text': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1000', 'blank': 'True'}),
'source_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '4000', 'blank': 'True'}),
'stamps_used': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'used_as_stamp'", 'blank': 'True', 'to': "orm['canvas.Content']"}),
'timestamp': ('canvas.util.UnixTimestampField', [], {}),
'url_mapping': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.ContentUrlMapping']", 'null': 'True', 'blank': 'True'}),
'visibility': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'canvas.contenturlmapping': {
'Meta': {'object_name': 'ContentUrlMapping'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'canvas.emailunsubscribe': {
'Meta': {'object_name': 'EmailUnsubscribe'},
'email': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'canvas.externalcontent': {
'Meta': {'object_name': 'ExternalContent'},
'_data': ('django.db.models.fields.TextField', [], {'default': "'{}'"}),
'content_type': ('django.db.models.fields.CharField', [], {'max_length': '2'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'parent_comment': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'external_content'", 'to': "orm['canvas.Comment']"}),
'source_url': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '4000', 'null': 'True', 'blank': 'True'})
},
'canvas.facebookinvite': {
'Meta': {'object_name': 'FacebookInvite'},
'fb_message_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'invited_fbid': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'invitee': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'facebook_invited_from'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}),
'inviter': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'facebook_sent_invites'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"})
},
'canvas.facebookuser': {
'Meta': {'object_name': 'FacebookUser'},
'email': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'fb_uid': ('django.db.models.fields.BigIntegerField', [], {'unique': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'gender': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_invited': ('canvas.util.UnixTimestampField', [], {'default': '0'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'null': 'True', 'blank': 'True'})
},
'canvas.followcategory': {
'Meta': {'unique_together': "(('user', 'category'),)", 'object_name': 'FollowCategory'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'followers'", 'to': "orm['canvas.Category']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'following'", 'to': "orm['auth.User']"})
},
'canvas.invitecode': {
'Meta': {'object_name': 'InviteCode'},
'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'invitee': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'invited_from'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"}),
'inviter': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'sent_invites'", 'null': 'True', 'blank': 'True', 'to': "orm['auth.User']"})
},
'canvas.remixplugin': {
'Meta': {'object_name': 'RemixPlugin'},
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
's3md5': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'timestamp': ('canvas.util.UnixTimestampField', [], {'default': '0'})
},
'canvas.stashcontent': {
'Meta': {'object_name': 'StashContent'},
'content': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Content']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'canvas.userinfo': {
'Meta': {'object_name': 'UserInfo'},
'avatar': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Content']", 'null': 'True'}),
'bio_text': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'blank': 'True'}),
'enable_timeline': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'enable_timeline_posts': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'facebook_id': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'free_invites': ('django.db.models.fields.IntegerField', [], {'default': '10'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'invite_bypass': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}),
'is_qa': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'post_anonymously': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'profile_image': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['canvas.Comment']", 'null': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'canvas.usermoderationlog': {
'Meta': {'object_name': 'UserModerationLog'},
'action': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'moderator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}),
'note': ('django.db.models.fields.TextField', [], {}),
'timestamp': ('canvas.util.UnixTimestampField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'moderation_log'", 'to': "orm['auth.User']"})
},
'canvas.userwarning': {
'Meta': {'object_name': 'UserWarning'},
'comment': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['canvas.Comment']", 'null': 'True', 'blank': 'True'}),
'confirmed': ('canvas.util.UnixTimestampField', [], {'default': '0'}),
'custom_message': ('django.db.models.fields.TextField', [], {}),
'disable_user': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'issued': ('canvas.util.UnixTimestampField', [], {}),
'stock_message': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_warnings'", 'to': "orm['auth.User']"}),
'viewed': ('canvas.util.UnixTimestampField', [], {'default': '0'})
},
'canvas.welcomeemailrecipient': {
'Meta': {'object_name': 'WelcomeEmailRecipient'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'recipient': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'canvas_auth.user': {
'Meta': {'object_name': 'User', 'db_table': "'auth_user'", '_ormbases': ['auth.User'], 'proxy': 'True'}
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", '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'})
}
}
complete_apps = ['canvas']
|
canvasnetworks/canvas
|
website/canvas/migrations/0163_auto__add_field_userinfo_avatar.py
|
Python
|
bsd-3-clause
| 21,325
|
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/animation/EffectInput.h"
#include "bindings/core/v8/Dictionary.h"
#include "core/animation/AnimationInputHelpers.h"
#include "core/animation/KeyframeEffectModel.h"
#include "core/animation/StringKeyframe.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "wtf/NonCopyingSort.h"
namespace blink {
PassRefPtrWillBeRawPtr<AnimationEffect> EffectInput::convert(Element* element, const Vector<Dictionary>& keyframeDictionaryVector, ExceptionState& exceptionState)
{
// FIXME: Remove the dependency on element.
if (!element)
return nullptr;
StyleSheetContents* styleSheetContents = element->document().elementSheet().contents();
StringKeyframeVector keyframes;
double lastOffset = 0;
for (size_t i = 0; i < keyframeDictionaryVector.size(); ++i) {
RefPtrWillBeRawPtr<StringKeyframe> keyframe = StringKeyframe::create();
ScriptValue scriptValue;
bool frameHasOffset = DictionaryHelper::get(keyframeDictionaryVector[i], "offset", scriptValue) && !scriptValue.isNull();
if (frameHasOffset) {
double offset;
DictionaryHelper::get(keyframeDictionaryVector[i], "offset", offset);
// Keyframes with offsets outside the range [0.0, 1.0] are an error.
if (std::isnan(offset)) {
exceptionState.throwDOMException(InvalidModificationError, "Non numeric offset provided");
}
if (offset < 0 || offset > 1) {
exceptionState.throwDOMException(InvalidModificationError, "Offsets provided outside the range [0, 1]");
return nullptr;
}
if (offset < lastOffset) {
exceptionState.throwDOMException(InvalidModificationError, "Keyframes with specified offsets are not sorted");
return nullptr;
}
lastOffset = offset;
keyframe->setOffset(offset);
}
keyframes.append(keyframe);
String compositeString;
DictionaryHelper::get(keyframeDictionaryVector[i], "composite", compositeString);
if (compositeString == "add")
keyframe->setComposite(AnimationEffect::CompositeAdd);
String timingFunctionString;
if (DictionaryHelper::get(keyframeDictionaryVector[i], "easing", timingFunctionString)) {
if (RefPtr<TimingFunction> timingFunction = AnimationInputHelpers::parseTimingFunction(timingFunctionString))
keyframe->setEasing(timingFunction);
}
Vector<String> keyframeProperties;
keyframeDictionaryVector[i].getPropertyNames(keyframeProperties);
for (size_t j = 0; j < keyframeProperties.size(); ++j) {
String property = keyframeProperties[j];
CSSPropertyID id = AnimationInputHelpers::keyframeAttributeToCSSPropertyID(property);
if (id == CSSPropertyInvalid)
continue;
String value;
DictionaryHelper::get(keyframeDictionaryVector[i], property, value);
keyframe->setPropertyValue(id, value, styleSheetContents);
}
}
RefPtrWillBeRawPtr<StringKeyframeEffectModel> keyframeEffectModel = StringKeyframeEffectModel::create(keyframes);
if (!keyframeEffectModel->isReplaceOnly()) {
exceptionState.throwDOMException(NotSupportedError, "Partial keyframes are not supported.");
return nullptr;
}
keyframeEffectModel->forceConversionsToAnimatableValues(element);
return keyframeEffectModel;
}
} // namespace blink
|
smilusingjavascript/blink
|
Source/core/animation/EffectInput.cpp
|
C++
|
bsd-3-clause
| 5,187
|
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "user_group".
*
* @property integer $id
* @property integer $owner_id
* @property string $participants
* @property string $title
* @property string $description
*/
class UserGroup extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'user_group';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['owner_id', 'title', 'description'], 'required'],
[['owner_id'], 'integer'],
[['participants', 'description'], 'string'],
[['title'], 'string', 'max' => 255]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'owner_id' => 'Owner ID',
'participants' => 'Participants',
'title' => 'Title',
'description' => 'Description',
];
}
}
|
jflash49/TSS
|
common/models/UserGroup.php
|
PHP
|
bsd-3-clause
| 1,031
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync_file_system/syncable_file_system_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "chrome/browser/sync_file_system/local/canned_syncable_file_system.h"
#include "chrome/browser/sync_file_system/local/local_file_sync_context.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/browser/fileapi/external_mount_points.h"
#include "webkit/common/fileapi/file_system_types.h"
using storage::ExternalMountPoints;
using storage::FileSystemURL;
namespace sync_file_system {
namespace {
const char kSyncableFileSystemRootURI[] =
"filesystem:http://www.example.com/external/syncfs/";
const char kNonRegisteredFileSystemRootURI[] =
"filesystem:http://www.example.com/external/non_registered/";
const char kNonSyncableFileSystemRootURI[] =
"filesystem:http://www.example.com/temporary/";
const char kOrigin[] = "http://www.example.com/";
const base::FilePath::CharType kPath[] = FILE_PATH_LITERAL("dir/file");
FileSystemURL CreateFileSystemURL(const std::string& url) {
return ExternalMountPoints::GetSystemInstance()->CrackURL(GURL(url));
}
base::FilePath CreateNormalizedFilePath(const base::FilePath::CharType* path) {
return base::FilePath(path).NormalizePathSeparators();
}
} // namespace
TEST(SyncableFileSystemUtilTest, GetSyncableFileSystemRootURI) {
const GURL root = GetSyncableFileSystemRootURI(GURL(kOrigin));
EXPECT_TRUE(root.is_valid());
EXPECT_EQ(GURL(kSyncableFileSystemRootURI), root);
}
TEST(SyncableFileSystemUtilTest, CreateSyncableFileSystemURL) {
RegisterSyncableFileSystem();
const base::FilePath path(kPath);
const FileSystemURL expected_url =
CreateFileSystemURL(kSyncableFileSystemRootURI + path.AsUTF8Unsafe());
const FileSystemURL url = CreateSyncableFileSystemURL(GURL(kOrigin), path);
EXPECT_TRUE(url.is_valid());
EXPECT_EQ(expected_url, url);
RevokeSyncableFileSystem();
}
TEST(SyncableFileSystemUtilTest,
SerializeAndDesirializeSyncableFileSystemURL) {
RegisterSyncableFileSystem();
const std::string expected_url_str = kSyncableFileSystemRootURI +
CreateNormalizedFilePath(kPath).AsUTF8Unsafe();
const FileSystemURL expected_url = CreateFileSystemURL(expected_url_str);
const FileSystemURL url = CreateSyncableFileSystemURL(
GURL(kOrigin), base::FilePath(kPath));
std::string serialized;
EXPECT_TRUE(SerializeSyncableFileSystemURL(url, &serialized));
EXPECT_EQ(expected_url_str, serialized);
FileSystemURL deserialized;
EXPECT_TRUE(DeserializeSyncableFileSystemURL(serialized, &deserialized));
EXPECT_TRUE(deserialized.is_valid());
EXPECT_EQ(expected_url, deserialized);
RevokeSyncableFileSystem();
}
TEST(SyncableFileSystemUtilTest,
FailInSerializingAndDeserializingSyncableFileSystemURL) {
RegisterSyncableFileSystem();
const base::FilePath normalized_path = CreateNormalizedFilePath(kPath);
const std::string non_registered_url =
kNonRegisteredFileSystemRootURI + normalized_path.AsUTF8Unsafe();
const std::string non_syncable_url =
kNonSyncableFileSystemRootURI + normalized_path.AsUTF8Unsafe();
// Expected to fail in serializing URLs of non-registered filesystem and
// non-syncable filesystem.
std::string serialized;
EXPECT_FALSE(SerializeSyncableFileSystemURL(
CreateFileSystemURL(non_registered_url), &serialized));
EXPECT_FALSE(SerializeSyncableFileSystemURL(
CreateFileSystemURL(non_syncable_url), &serialized));
// Expected to fail in deserializing a string that represents URLs of
// non-registered filesystem and non-syncable filesystem.
FileSystemURL deserialized;
EXPECT_FALSE(DeserializeSyncableFileSystemURL(
non_registered_url, &deserialized));
EXPECT_FALSE(DeserializeSyncableFileSystemURL(
non_syncable_url, &deserialized));
RevokeSyncableFileSystem();
}
TEST(SyncableFileSystemUtilTest, SyncableFileSystemURL_IsParent) {
RegisterSyncableFileSystem();
const std::string root1 = sync_file_system::GetSyncableFileSystemRootURI(
GURL("http://foo.com")).spec();
const std::string root2 = sync_file_system::GetSyncableFileSystemRootURI(
GURL("http://bar.com")).spec();
const std::string parent("dir");
const std::string child("dir/child");
// True case.
EXPECT_TRUE(CreateFileSystemURL(root1 + parent).IsParent(
CreateFileSystemURL(root1 + child)));
EXPECT_TRUE(CreateFileSystemURL(root2 + parent).IsParent(
CreateFileSystemURL(root2 + child)));
// False case: different origin.
EXPECT_FALSE(CreateFileSystemURL(root1 + parent).IsParent(
CreateFileSystemURL(root2 + child)));
EXPECT_FALSE(CreateFileSystemURL(root2 + parent).IsParent(
CreateFileSystemURL(root1 + child)));
RevokeSyncableFileSystem();
}
} // namespace sync_file_system
|
7kbird/chrome
|
chrome/browser/sync_file_system/syncable_file_system_util_unittest.cc
|
C++
|
bsd-3-clause
| 5,010
|
package io
import (
"fmt"
"os"
)
func Info(args ...interface{}) {
fmt.Print("\033[1m-----> ")
args = append(args, "\033[0m")
fmt.Println(args...)
}
func Infof(format string, args ...interface{}) {
fmt.Print("\033[1m-----> ")
fmt.Printf(format+"\033[0m", args...)
}
func Print(args ...interface{}) {
fmt.Print(" ")
fmt.Println(args...)
}
func Printf(format string, args ...interface{}) {
fmt.Print(" ")
fmt.Printf(format, args...)
}
func Warnf(format string, args ...interface{}) {
fmt.Print(" ! ")
fmt.Printf(format, args...)
}
func Error(args ...interface{}) {
fmt.Print(" ! ")
fmt.Println(args...)
os.Exit(1)
}
|
Zyko0/heroku2scalingo
|
io/io.go
|
GO
|
bsd-3-clause
| 656
|
{% extends 'base/main_section_base.html' %}
{% load staticfiles %}
{% block extra_css %}
<style type="text/css">
.panel-body {
padding: 0;
}
</style>
{% endblock %}
{% block extra_head %}
<link rel="stylesheet" href="{% static 'assets/css/bootstrap-tables2.css' %}" />
{% endblock %}
|
Swappsco/koalixerp
|
crm_core/templates/base/table_view_base.html
|
HTML
|
bsd-3-clause
| 313
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://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"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.20"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>PMDK C++ bindings: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">PMDK C++ bindings
 <span id="projectnumber">1.6.1</span>
</div>
<div id="projectbrief">This is the C++ bindings documentation for PMDK's libpmemobj.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.20 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><b>pmem</b></li><li class="navelem"><b>obj</b></li><li class="navelem"><b>experimental</b></li><li class="navelem"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html">v</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">pmem::obj::experimental::v< T > Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html">pmem::obj::experimental::v< T ></a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html#a8b44166a7c90911e77b743fa1865b2a9">get</a>(Args &&... args) noexcept</td><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html">pmem::obj::experimental::v< T ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html#a120dfff82d94acb45cf17f116bf5353b">operator T&</a>() noexcept</td><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html">pmem::obj::experimental::v< T ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html#a0161523cc8f39d49f84c68834391469b">operator=</a>(const T &rhs)</td><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html">pmem::obj::experimental::v< T ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html#a5f63c286ad436f16866ef0db2f64805c">operator=</a>(v &rhs)</td><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html">pmem::obj::experimental::v< T ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html#a90ad8ec78f4680d01a28859f2b897f7c">operator=</a>(v< Y > &rhs)</td><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html">pmem::obj::experimental::v< T ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html#a67a6969b1b326bc8a95d0d6183c446f5">swap</a>(v &other)</td><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html">pmem::obj::experimental::v< T ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html#a06b3e62f73d57551228c244800e0a3eb">unsafe_get</a>()</td><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html">pmem::obj::experimental::v< T ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html#a7bfacf258a99eb8755c6d7eba89a55d3">v</a>() noexcept</td><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html">pmem::obj::experimental::v< T ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html#aa0b1d230b1a37bb70d91353ae3034582">~v</a>()</td><td class="entry"><a class="el" href="classpmem_1_1obj_1_1experimental_1_1v.html">pmem::obj::experimental::v< T ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by <a href="http://www.doxygen.org/index.html"><img class="footer" src="doxygen.svg" width="104" height="31" alt="doxygen"/></a> 1.8.20
</small></address>
</body>
</html>
|
pbalcer/pbalcer.github.io
|
content/libpmemobj-cpp/v1.6/doxygen/classpmem_1_1obj_1_1experimental_1_1v-members.html
|
HTML
|
bsd-3-clause
| 6,683
|
#include "ResourceGUI.h"
#include "IO/XmlWorld.h"
#include "utils/stringutils.h"
#include "utils/ioutils.h"
ResourceGUIBackend::ResourceGUIBackend(RobotWorld* world,ResourceManager* library)
:WorldGUIBackend(world),resources(library)
{
}
inline bool LoadResources(const char* fn,ResourceTree& lib)
{
size_t origsize = lib.topLevel.size();
if(!lib.LoadFolder(fn)) {
lib.TreeFromLibrary();
fprintf(stderr,"Warning, couldn't load library %s\n",fn);
return false;
}
else {
printf("Loaded %d items from %s\n",lib.topLevel.size()-origsize,fn);
return true;
}
return false;
}
inline bool LoadResources(TiXmlElement* e,ResourceTree& lib)
{
size_t origsize = lib.topLevel.size();
if(!lib.library.Load(e)) {
fprintf(stderr,"Warning, couldn't load library from XML\n");
lib.TreeFromLibrary();
return false;
}
else {
lib.TreeFromLibrary();
printf("Loaded %d items from XML\n",lib.topLevel.size()-origsize);
return true;
}
return false;
}
inline bool LoadItem(const char* fn,ResourceTree& lib)
{
ResourceNodePtr r=lib.LoadFile(fn);
if(r != NULL) {
printf("Loaded %s as type %s\n",fn,r->Type());
return true;
}
else {
fprintf(stderr,"Couldn't load resource file %s\n",fn);
return false;
}
}
bool ResourceGUIBackend::LoadCommandLine(int argc,const char** argv)
{
for(int i=1;i<argc;i++) {
if(argv[i][0] == '-') {
if(0==strcmp(argv[i],"-l")) {
LoadResources(argv[i+1],*resources);
i++;
}
else {
printf("Unknown option %s",argv[i]);
return 0;
}
}
else {
const char* ext=FileExtension(argv[i]);
if(0==strcmp(ext,"xml")) {
TiXmlDocument doc;
if(!doc.LoadFile(argv[i])) {
printf("Error loading XML file %s\n",argv[i]);
return false;
}
if(0 == strcmp(doc.RootElement()->Value(),"world")) {
XmlWorld xmlWorld;
if(!xmlWorld.Load(doc.RootElement(),GetFilePath(argv[i]))) {
printf("Error loading world file %s\n",argv[i]);
return 0;
}
if(!xmlWorld.GetWorld(*world)) {
printf("Error loading world from %s\n",argv[i]);
return 0;
}
}
else if(0 == strcmp(doc.RootElement()->Value(),"resource_library")) {
LoadResources(doc.RootElement(),*resources);
}
else {
if(!LoadItem(argv[i],*resources))
return 0;
}
}
else {
//try loading into the world
const char* ext = FileExtension(argv[i]);
if(world->CanLoadElementExt(ext) && world->LoadElement(argv[i])>= 0) {
//loaded successfully
}
else {
//failed, now try resource library load
if(!LoadItem(argv[i],*resources))
return 0;
}
}
}
}
return true;
}
ResourceNodePtr ResourceGUIBackend::Add(ResourcePtr r)
{
if(resources == NULL) return NULL;
ResourceNode* parent = (resources->selected != NULL ? resources->selected->parent : NULL);
if(r->name.empty()) {
stringstream ss;
if(parent == NULL){
ss<<r->Type()<<"["<<resources->topLevel.size()<<"]";
}
else{
ss<<r->Type()<<"["<<parent->children.size()<<"]";
}
r->name = ss.str();
}
//last_added = resources->AddChildOfSelected(r);
if(parent == NULL)
last_added = resources->Add(r);
else
last_added = parent->AddChild(r);
//SendCommand("new_resource", r->Type()+string(" ")+r->name);
SendCommand("new_resource", last_added->Identifier());
return last_added;
}
ResourceNodePtr ResourceGUIBackend::Add(const string& name,const string& type)
{
if(resources->library.knownTypes.count(type)==0) return NULL;
ResourcePtr r=resources->library.knownTypes[type][0]->Make();
r->name = name;
return Add(r);
}
void ResourceGUIBackend::SaveCur(const string& file)
{
resources->SaveSelected(file);
}
bool ResourceGUIBackend::LoadNew(const string& file)
{
return resources->LoadFile(file) != NULL;
}
void ResourceGUIBackend::SaveAll(const string& path)
{
resources->SaveFolder(path);
}
bool ResourceGUIBackend::LoadAll(const string& path)
{
if(!resources->LoadFolder(path)) {
fprintf(stderr,"Error loading resources from %s\n",path.c_str());
return false;
}
else {
fprintf(stderr,"Loaded all resources from %s\n",path.c_str());
return true;
}
return false;
}
void ResourceGUIBackend::SetLastActive()
{
if(last_added == NULL) {
resources->selected = NULL;
}
else {
resources->selected = last_added;
}
}
void ResourceGUIBackend::SetActive(const string& identifier)
{
resources->Select(identifier);
}
void ResourceGUIBackend::SetPathTime(double time){
viewResource.pathTime = time;
}
bool ResourceGUIBackend::OnCommand(const string& cmd,const string& args)
{
if(cmd == "set_resource") {
resources->Select(args);
return true;
}
else if(cmd == "get_resource") {
stringstream ss;
ss<<resources->selected->Identifier();
SendCommand("current_resource",ss.str());
return true;
}
else if(cmd == "set_resource_name") {
if(resources->selected) resources->selected->resource->name = args;
printf("Updating name to %s\n",args.c_str());
}
else if(cmd == "delete_resource") {
resources->DeleteSelected();
}
else if(cmd == "add_resource") {
string type,name;
stringstream ss(args);
if(!SafeInputString(ss,type)) {
cout<<"Error reading resource type from args \""<<args<<"\""<<endl;
return true;
}
if(!SafeInputString(ss,name)) {
cout<<"Error reading resource name from args \""<<args<<"\""<<endl;
return true;
}
last_added = Add(name,type);
}
else if(cmd == "load_resource") {
if(LoadNew(args)) {
SendCommand("new_resource",last_added->Identifier());
}
}
else if(cmd == "save_resource") {
SaveCur(args);
}
else if(cmd == "load_resource_dir") {
if(LoadAll(args)) {
SendCommand("refresh_resources","");
}
}
else if(cmd == "save_resource_dir") {
SaveAll(args);
}
else if(cmd == "convert") {
ResourcePtr r=CurrentResource();
ResourcePtr res = CastResource(r,args.c_str());
if(!res) {
fprintf(stderr,"Conversion failed\n");
return true;
}
res->name = r->name;
Add(res);
SetLastActive();
}
else if(cmd == "extract") {
ResourcePtr r=CurrentResource();
if(!r) return true;
vector<ResourcePtr> res = ExtractResources(r,args.c_str());
for(size_t i=0;i<res.size();i++){
Add(res[i]);
}
if(!res.empty())
SetLastActive();
}
else if(cmd == "set_path_time") {
stringstream ss(args);
double time;
ss>>time;
SetPathTime(time);
SendRefresh();
}
else {
return WorldGUIBackend::OnCommand(cmd,args);
}
return true;
}
ResourcePtr ResourceGUIBackend::CurrentResource()
{
if(resources && resources->selected)
return resources->selected->resource;
else return 0;
}
void ResourceGUIBackend::RenderCurResource()
{
/*
ResourcePtr current = CurrentResource();
if(current)
viewResource.DrawGL(current);
*/
//separate open?
viewResource.SetRobot(world->robots[0].robot);
if(resources && resources->selected)
viewResource.DrawGL(resources->selected->resource);
}
|
bbgw/Klampt
|
Interface/ResourceGUI.cpp
|
C++
|
bsd-3-clause
| 7,104
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.