code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
/*
* Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 6439826 6411930 6380018 6392177
* @summary Exception issuing Diagnostic while processing generated errant code
*/
import java.io.*;
import java.util.*;
import javax.annotation.processing.*;
import javax.lang.model.*;
import javax.lang.model.element.*;
import javax.tools.*;
import com.sun.source.util.*;
import com.sun.tools.javac.api.*;
import static javax.lang.model.util.ElementFilter.*;
@SupportedAnnotationTypes("*")
@SupportedSourceVersion(SourceVersion.RELEASE_6 )
public class T6439826 extends AbstractProcessor {
public static void main(String... args) {
String testSrc = System.getProperty("test.src", ".");
String testClasses = System.getProperty("test.classes");
JavacTool tool = JavacTool.create();
MyDiagListener dl = new MyDiagListener();
StandardJavaFileManager fm = tool.getStandardFileManager(dl, null, null);
Iterable<? extends JavaFileObject> files =
fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, T6439826.class.getName()+".java")));
Iterable<String> opts = Arrays.asList("-proc:only",
"-processor", "T6439826",
"-processorpath", testClasses);
StringWriter out = new StringWriter();
JavacTask task = tool.getTask(out, fm, dl, opts, null, files);
task.call();
String s = out.toString();
System.err.print(s);
// Expect the following 2 diagnostics, and no output to log
// Foo.java:1: illegal character: \35
// Foo.java:1: reached end of file while parsing
System.err.println(dl.count + " diagnostics; " + s.length() + " characters");
if (dl.count != 2 || s.length() != 0)
throw new AssertionError("unexpected output from compiler");
}
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
Set<? extends TypeElement> elems = typesIn(roundEnv.getRootElements());
for (TypeElement e: elems) {
if (e.getSimpleName().toString().equals(T6439826.class.getName()))
writeBadFile();
}
return false;
}
private void writeBadFile() {
Filer filer = processingEnv.getFiler();
Messager messager = processingEnv.getMessager();
try {
Writer out = filer.createSourceFile("Foo").openWriter();
out.write("class Foo #"); // write a file that generates a scanner error
out.close();
} catch (IOException e) {
messager.printMessage(Diagnostic.Kind.ERROR, e.toString());
}
}
static class MyDiagListener implements DiagnosticListener {
public void report(Diagnostic d) {
System.err.println(d);
count++;
}
public int count;
}
}
| unktomi/form-follows-function | mjavac/langtools/test/tools/javac/processing/T6439826.java | Java | gpl-2.0 | 3,965 |
/*
* Hydrogen
* Copyright(c) 2002-2008 by Alex >Comix< Cominu [comix@users.sourceforge.net]
*
* http://www.hydrogen-music.org
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY, without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "SoundLibraryDatastructures.h"
#include "SoundLibraryImportDialog.h"
#include "SoundLibraryRepositoryDialog.h"
#include "SoundLibraryPanel.h"
#include "../widgets/DownloadWidget.h"
#include "../HydrogenApp.h"
#include "../InstrumentRack.h"
#include <hydrogen/LocalFileMng.h>
#include <hydrogen/h2_exception.h>
#include <hydrogen/Preferences.h>
#include <hydrogen/basics/drumkit.h>
#include <hydrogen/helpers/filesystem.h>
#include <QTreeWidget>
#include <QDomDocument>
#include <QMessageBox>
#include <QHeaderView>
#include <QFileDialog>
#include <QCryptographicHash>
#include <memory>
const char* SoundLibraryImportDialog::__class_name = "SoundLibraryImportDialog";
SoundLibraryImportDialog::SoundLibraryImportDialog( QWidget* pParent, bool OnlineImport )
: QDialog( pParent )
, Object( __class_name )
{
setupUi( this );
INFOLOG( "INIT" );
setWindowTitle( trUtf8( "Sound Library import" ) );
setFixedSize( width(), height() );
QStringList headers;
headers << trUtf8( "Sound library" ) << trUtf8( "Status" );
QTreeWidgetItem* header = new QTreeWidgetItem( headers );
m_pDrumkitTree->setHeaderItem( header );
m_pDrumkitTree->header()->resizeSection( 0, 200 );
connect( m_pDrumkitTree, SIGNAL( currentItemChanged ( QTreeWidgetItem*, QTreeWidgetItem* ) ), this, SLOT( soundLibraryItemChanged( QTreeWidgetItem*, QTreeWidgetItem* ) ) );
connect( repositoryCombo, SIGNAL(currentIndexChanged(int)), this, SLOT( onRepositoryComboBoxIndexChanged(int) ));
SoundLibraryNameLbl->setText( "" );
SoundLibraryInfoLbl->setText( "" );
DownloadBtn->setEnabled( false );
InstallBtn->setEnabled (false );
updateRepositoryCombo();
if( OnlineImport)
tabWidget->setCurrentIndex( 0 );
else
tabWidget->setCurrentIndex( 1 );
}
SoundLibraryImportDialog::~SoundLibraryImportDialog()
{
INFOLOG( "DESTROY" );
}
//update combo box
void SoundLibraryImportDialog::updateRepositoryCombo()
{
H2Core::Preferences* pref = H2Core::Preferences::get_instance();
/*
Read serverList from config and put servers into the comboBox
*/
if( pref->sServerList.size() == 0 ) {
pref->sServerList.push_back( "http://www.hydrogen-music.org/feeds/drumkit_list.php" );
}
repositoryCombo->clear();
std::list<QString>::const_iterator cur_Server;
for( cur_Server = pref->sServerList.begin(); cur_Server != pref->sServerList.end(); ++cur_Server ) {
repositoryCombo->insertItem( 0, *cur_Server );
}
reloadRepositoryData();
}
void SoundLibraryImportDialog::onRepositoryComboBoxIndexChanged(int i)
{
UNUSED(i);
if(!repositoryCombo->currentText().isEmpty())
{
QString cacheFile = getCachedFilename();
if( !H2Core::Filesystem::file_exists( cacheFile, true ) )
{
SoundLibraryImportDialog::on_UpdateListBtn_clicked();
}
reloadRepositoryData();
}
}
///
/// Edit the server list
///
void SoundLibraryImportDialog::on_EditListBtn_clicked()
{
SoundLibraryRepositoryDialog repoDialog( this );
repoDialog.exec();
updateRepositoryCombo();
}
void SoundLibraryImportDialog::clearImageCache()
{
// Note: After a kit is installed the list refreshes and this gets called to
// clear the image cache - maybe we want to keep the cache in this case?
QString cacheDir = H2Core::Filesystem::repositories_cache_dir() ;
INFOLOG("Deleting cached image files from " + cacheDir.toLocal8Bit() );
QDir dir( cacheDir );
dir.setNameFilters(QStringList() << "*.png");
dir.setFilter(QDir::Files);
foreach(QString dirFile, dir.entryList())
{
if ( !dir.remove(dirFile) )
{
WARNINGLOG("Error removing image file(s) from cache.");
}
}
}
QString SoundLibraryImportDialog::getCachedFilename()
{
QString cacheDir = H2Core::Filesystem::repositories_cache_dir();
QString serverMd5 = QString(QCryptographicHash::hash(( repositoryCombo->currentText().toLatin1() ),QCryptographicHash::Md5).toHex());
QString cacheFile = cacheDir + "/" + serverMd5;
return cacheFile;
}
QString SoundLibraryImportDialog::getCachedImageFilename()
{
QString cacheDir = H2Core::Filesystem::repositories_cache_dir();
QString kitNameMd5 = QString(QCryptographicHash::hash(( SoundLibraryNameLbl->text().toLatin1() ),QCryptographicHash::Md5).toHex());
QString cacheFile = cacheDir + "/" + kitNameMd5 + ".png";
return cacheFile;
}
void SoundLibraryImportDialog::writeCachedData(const QString& fileName, const QString& data)
{
if( data.isEmpty() )
{
return;
}
QFile outFile( fileName );
if( !outFile.open( QIODevice::WriteOnly | QIODevice::Text ) )
{
ERRORLOG( "Failed to open file for writing repository cache." );
return;
}
QTextStream stream( &outFile );
stream << data;
outFile.close();
}
void SoundLibraryImportDialog::writeCachedImage( const QString& imageFile, QPixmap& pixmap )
{
QString cacheFile = getCachedImageFilename() ;
QFile outFile( cacheFile );
if( !outFile.open( QIODevice::WriteOnly ) )
{
ERRORLOG( "Failed to open file for writing repository image cache." );
return;
}
pixmap.save(&outFile);
outFile.close();
}
QString SoundLibraryImportDialog::readCachedData(const QString& fileName)
{
QString content;
QFile inFile( fileName );
if( !inFile.open( QIODevice::ReadOnly | QIODevice::Text ) )
{
ERRORLOG( "Failed to open file for reading." );
return content;
}
QDomDocument document;
if( !document.setContent( &inFile ) )
{
inFile.close();
return content;
}
inFile.close();
content = document.toString();
return content;
}
QString SoundLibraryImportDialog::readCachedImage( const QString& imageFile )
{
QString cacheFile = getCachedImageFilename() ;
QFile file( cacheFile );
if( !file.exists() )
{
// no image in cache, just return NULL
return NULL;
}
return cacheFile;
}
void SoundLibraryImportDialog::reloadRepositoryData()
{
QString sDrumkitXML;
QString cacheFile = getCachedFilename();
if(H2Core::Filesystem::file_exists(cacheFile,true))
{
sDrumkitXML = readCachedData(cacheFile);
}
m_soundLibraryList.clear();
QDomDocument dom;
dom.setContent( sDrumkitXML );
QDomNode drumkitNode = dom.documentElement().firstChild();
while ( !drumkitNode.isNull() ) {
if( !drumkitNode.toElement().isNull() ) {
if ( drumkitNode.toElement().tagName() == "drumkit" || drumkitNode.toElement().tagName() == "song" || drumkitNode.toElement().tagName() == "pattern" ) {
SoundLibraryInfo soundLibInfo;
if ( drumkitNode.toElement().tagName() =="song" ) {
soundLibInfo.setType( "song" );
}
if ( drumkitNode.toElement().tagName() =="drumkit" ) {
soundLibInfo.setType( "drumkit" );
}
if ( drumkitNode.toElement().tagName() =="pattern" ) {
soundLibInfo.setType( "pattern" );
}
QDomElement nameNode = drumkitNode.firstChildElement( "name" );
if ( !nameNode.isNull() ) {
soundLibInfo.setName( nameNode.text() );
}
QDomElement urlNode = drumkitNode.firstChildElement( "url" );
if ( !urlNode.isNull() ) {
soundLibInfo.setUrl( urlNode.text() );
}
QDomElement infoNode = drumkitNode.firstChildElement( "info" );
if ( !infoNode.isNull() ) {
soundLibInfo.setInfo( infoNode.text() );
}
QDomElement authorNode = drumkitNode.firstChildElement( "author" );
if ( !authorNode.isNull() ) {
soundLibInfo.setAuthor( authorNode.text() );
}
QDomElement licenseNode = drumkitNode.firstChildElement( "license" );
if ( !licenseNode.isNull() ) {
soundLibInfo.setLicense( licenseNode.text() );
}
QDomElement imageNode = drumkitNode.firstChildElement( "image" );
if ( !imageNode.isNull() ) {
soundLibInfo.setImage( imageNode.text() );
}
QDomElement imageLicenseNode = drumkitNode.firstChildElement( "imageLicense" );
if ( !imageLicenseNode.isNull() ) {
soundLibInfo.setImageLicense( imageLicenseNode.text() );
}
m_soundLibraryList.push_back( soundLibInfo );
}
}
drumkitNode = drumkitNode.nextSibling();
}
updateSoundLibraryList();
}
///
/// Download and update the drumkit list
///
void SoundLibraryImportDialog::on_UpdateListBtn_clicked()
{
QApplication::setOverrideCursor(Qt::WaitCursor);
DownloadWidget drumkitList( this, trUtf8( "Updating SoundLibrary list..." ), repositoryCombo->currentText() );
drumkitList.exec();
QString sDrumkitXML = drumkitList.get_xml_content();
/*
* Hydrogen creates the following cache hierarchy to cache
* the content of server lists:
*
* CACHE_DIR
* +-----repositories
* +-----serverlist_$(md5(SERVER_NAME))
*/
QString cacheFile = getCachedFilename();
writeCachedData(cacheFile, sDrumkitXML);
reloadRepositoryData();
QApplication::restoreOverrideCursor();
}
void SoundLibraryImportDialog::updateSoundLibraryList()
{
// build the sound library tree
m_pDrumkitTree->clear();
m_pDrumkitsItem = new QTreeWidgetItem( m_pDrumkitTree );
m_pDrumkitsItem->setText( 0, trUtf8( "Drumkits" ) );
m_pDrumkitTree->setItemExpanded( m_pDrumkitsItem, true );
m_pSongItem = new QTreeWidgetItem( m_pDrumkitTree );
m_pSongItem->setText( 0, trUtf8( "Songs" ) );
m_pDrumkitTree->setItemExpanded( m_pSongItem, true );
m_pPatternItem = new QTreeWidgetItem( m_pDrumkitTree );
m_pPatternItem->setText( 0, trUtf8( "Patterns" ) );
m_pDrumkitTree->setItemExpanded( m_pPatternItem, true );
for ( uint i = 0; i < m_soundLibraryList.size(); ++i ) {
QString sLibraryName = m_soundLibraryList[ i ].getName();
QTreeWidgetItem* pDrumkitItem = NULL;
if ( m_soundLibraryList[ i ].getType() == "song" ) {
pDrumkitItem = new QTreeWidgetItem( m_pSongItem );
}
if ( m_soundLibraryList[ i ].getType() == "drumkit" ) {
pDrumkitItem = new QTreeWidgetItem( m_pDrumkitsItem );
}
if ( m_soundLibraryList[ i ].getType() == "pattern" ) {
pDrumkitItem = new QTreeWidgetItem( m_pPatternItem );
}
if ( isSoundLibraryItemAlreadyInstalled( m_soundLibraryList[ i ] ) ) {
pDrumkitItem->setText( 0, sLibraryName );
pDrumkitItem->setText( 1, trUtf8( "Installed" ) );
}
else {
pDrumkitItem->setText( 0, sLibraryName );
pDrumkitItem->setText( 1, trUtf8( "New" ) );
}
}
// Also clear out the image cache
clearImageCache();
}
/// Is the SoundLibrary already installed?
bool SoundLibraryImportDialog::isSoundLibraryItemAlreadyInstalled( SoundLibraryInfo sInfo )
{
// check if the filename matchs with an already installed soundlibrary directory.
// The filename used in the Soundlibrary URL must be the same of the unpacked directory.
// E.g: V-Synth_VariBreaks.h2drumkit must contain the V-Synth_VariBreaks directory once unpacked.
// Many drumkit are broken now (wrong filenames) and MUST be fixed!
QString sName = QFileInfo( sInfo.getUrl() ).fileName();
sName = sName.left( sName.lastIndexOf( "." ) );
if ( sInfo.getType() == "drumkit" ) {
if ( H2Core::Filesystem::drumkit_exists(sName) )
return true;
}
if ( sInfo.getType() == "pattern" ) {
return SoundLibraryDatabase::get_instance()->isPatternInstalled( sInfo.getName() );
}
if ( sInfo.getType() == "song" ) {
if ( H2Core::Filesystem::song_exists(sName) )
return true;
}
return false;
}
void SoundLibraryImportDialog::loadImage(QString img )
{
QPixmap pixmap;
pixmap.load( img ) ;
writeCachedImage( drumkitImageLabel->text(), pixmap );
showImage( pixmap );
}
void SoundLibraryImportDialog::showImage( QPixmap pixmap )
{
int x = (int) drumkitImageLabel->size().width();
int y = drumkitImageLabel->size().height();
float labelAspect = (float) x / y;
float imageAspect = (float) pixmap.width() / pixmap.height();
if ( ( x < pixmap.width() ) || ( y < pixmap.height() ) )
{
if ( labelAspect >= imageAspect )
{
// image is taller or the same as label frame
pixmap = pixmap.scaledToHeight( y );
}
else
{
// image is wider than label frame
pixmap = pixmap.scaledToWidth( x );
}
}
drumkitImageLabel->setPixmap( pixmap ); // TODO: Check if valid!
}
void SoundLibraryImportDialog::soundLibraryItemChanged( QTreeWidgetItem* current, QTreeWidgetItem* previous )
{
UNUSED( previous );
if ( current ) {
QString selected = current->text(0);
for ( uint i = 0; i < m_soundLibraryList.size(); ++i ) {
if ( m_soundLibraryList[ i ].getName() == selected ) {
SoundLibraryInfo info = m_soundLibraryList[ i ];
//bool alreadyInstalled = isSoundLibraryAlreadyInstalled( info.m_sURL );
SoundLibraryNameLbl->setText( info.getName() );
if( info.getType() == "pattern" ){
SoundLibraryInfoLbl->setText("");
} else {
SoundLibraryInfoLbl->setText( info.getInfo() );
}
AuthorLbl->setText( trUtf8( "Author: %1" ).arg( info.getAuthor() ) );
LicenseLbl->setText( trUtf8( "Drumkit License: %1" ).arg( info.getLicense()) );
ImageLicenseLbl->setText( trUtf8("Image License: %1" ).arg( info.getImageLicense() ) );
// Load the drumkit image
// Clear any image first
drumkitImageLabel->setPixmap( QPixmap() );
drumkitImageLabel->setText( info.getImage() );
if ( info.getImage().length() > 0 )
{
if ( isSoundLibraryItemAlreadyInstalled( info ) )
{
// get image file from local disk
QString sName = QFileInfo( info.getUrl() ).fileName();
sName = sName.left( sName.lastIndexOf( "." ) );
H2Core::Drumkit* drumkitInfo = H2Core::Drumkit::load_by_name( sName, false );
if ( drumkitInfo )
{
// get the image from the local filesystem
QPixmap pixmap ( drumkitInfo->get_path() + "/" + drumkitInfo->get_image() );
INFOLOG("Loaded image " + drumkitInfo->get_image().toLocal8Bit() + " from local filesystem");
showImage( pixmap );
}
else
{
___ERRORLOG ( "Error loading the drumkit" );
}
}
else
{
// Try from the cache
QString cachedFile = readCachedImage( info.getImage() );
if ( cachedFile.length() > 0 )
{
QPixmap pixmap ( cachedFile );
showImage( pixmap );
INFOLOG( "Loaded image " + info.getImage().toLocal8Bit() + " from cache (" + cachedFile + ")" );
}
else
{
// Get the drumkit's directory name from URL
//
// Example: if the server repo URL is: http://www.hydrogen-music.org/feeds/drumkit_list.php
// and the image name from the XML is Roland_TR-808_drum_machine.jpg
// the URL for the image will be: http://www.hydrogen-music.org/feeds/images/Roland_TR-808_drum_machine.jpg
if ( info.getImage().length() > 0 )
{
int lastSlash = info.getUrl().lastIndexOf( QString( "/" ));
QString imageUrl;
QString sLocalFile;
imageUrl = repositoryCombo->currentText().left( repositoryCombo->currentText().lastIndexOf( QString( "/" )) + 1 ) + info.getImage() ;
sLocalFile = QDir::tempPath() + "/" + QFileInfo( imageUrl ).fileName();
DownloadWidget dl( this, trUtf8( "" ), imageUrl, sLocalFile );
dl.exec();
loadImage( sLocalFile );
// Delete the temporary file
QFile::remove( sLocalFile );
}
}
}
}
else
{
// no image file specified in drumkit.xml
INFOLOG( "No image for this kit specified in drumkit.xml on remote server" );
}
DownloadBtn->setEnabled( true );
return;
}
}
}
SoundLibraryNameLbl->setText( "" );
SoundLibraryInfoLbl->setText( "" );
AuthorLbl->setText( "" );
DownloadBtn->setEnabled( false );
}
void SoundLibraryImportDialog::on_DownloadBtn_clicked()
{
QApplication::setOverrideCursor(Qt::WaitCursor);
QString selected = m_pDrumkitTree->currentItem()->text(0);
for ( uint i = 0; i < m_soundLibraryList.size(); ++i ) {
if ( m_soundLibraryList[ i ].getName() == selected ) {
// Download the sound library
QString sURL = m_soundLibraryList[ i ].getUrl();
QString sType = m_soundLibraryList[ i ].getType();
QString sLocalFile;
QString dataDir = H2Core::Preferences::get_instance()->getDataDirectory();
if( sType == "drumkit") {
sLocalFile = QDir::tempPath() + "/" + QFileInfo( sURL ).fileName();
}
if( sType == "song") {
sLocalFile = dataDir + "songs/" + QFileInfo( sURL ).fileName();
}
if( sType == "pattern") {
sLocalFile = dataDir + "patterns/" + QFileInfo( sURL ).fileName();
}
bool Error = false;
for ( int i = 0; i < 30; ++i ) {
DownloadWidget dl( this, trUtf8( "Downloading SoundLibrary..." ), sURL, sLocalFile );
dl.exec();
QUrl redirect_url = dl.get_redirect_url();
if (redirect_url.isEmpty() ) {
// ok, we have all data
Error = dl.get_error();
break;
}
else {
sURL = redirect_url.toEncoded();
Error = dl.get_error();
}
}
//No 'else', error message has been already displayed by DL widget
if(!Error)
{
// install the new soundlibrary
try {
if ( sType == "drumkit" ) {
H2Core::Drumkit::install( sLocalFile );
QApplication::restoreOverrideCursor();
QMessageBox::information( this, "Hydrogen", QString( trUtf8( "SoundLibrary imported in %1" ) ).arg( dataDir ) );
}
if ( sType == "song" || sType == "pattern") {
QApplication::restoreOverrideCursor();
}
}
catch( H2Core::H2Exception ex ) {
QApplication::restoreOverrideCursor();
QMessageBox::warning( this, "Hydrogen", trUtf8( "An error occurred importing the SoundLibrary." ) );
}
}
else
{
QApplication::restoreOverrideCursor();
}
QApplication::setOverrideCursor(Qt::WaitCursor);
// remove the downloaded files..
if( sType == "drumkit" ) {
QDir dir;
dir.remove( sLocalFile );
}
// update the drumkit list
SoundLibraryDatabase::get_instance()->update();
HydrogenApp::get_instance()->getInstrumentRack()->getSoundLibraryPanel()->test_expandedItems();
HydrogenApp::get_instance()->getInstrumentRack()->getSoundLibraryPanel()->updateDrumkitList();
updateSoundLibraryList();
QApplication::restoreOverrideCursor();
return;
}
}
}
void SoundLibraryImportDialog::on_BrowseBtn_clicked()
{
static QString lastUsedDir = QDir::homePath();
QFileDialog fd(this);
fd.setFileMode(QFileDialog::ExistingFile);
fd.setNameFilter( "Hydrogen drumkit (*.h2drumkit)" );
fd.setDirectory( lastUsedDir );
fd.setWindowTitle( trUtf8( "Import drumkit" ) );
QString filename = "";
if (fd.exec() == QDialog::Accepted) {
filename = fd.selectedFiles().first();
}
if (filename != "") {
SoundLibraryPathTxt->setText( filename );
lastUsedDir = fd.directory().absolutePath();
InstallBtn->setEnabled ( true );
}
}
void SoundLibraryImportDialog::on_InstallBtn_clicked()
{
QApplication::setOverrideCursor(Qt::WaitCursor);
QString dataDir = H2Core::Preferences::get_instance()->getDataDirectory();
try {
H2Core::Drumkit::install( SoundLibraryPathTxt->text() );
QMessageBox::information( this, "Hydrogen", QString( trUtf8( "SoundLibrary imported in %1" ).arg( dataDir ) ) );
// update the drumkit list
SoundLibraryDatabase::get_instance()->update();
HydrogenApp::get_instance()->getInstrumentRack()->getSoundLibraryPanel()->test_expandedItems();
HydrogenApp::get_instance()->getInstrumentRack()->getSoundLibraryPanel()->updateDrumkitList();
QApplication::restoreOverrideCursor();
}
catch( H2Core::H2Exception ex ) {
QApplication::restoreOverrideCursor();
QMessageBox::warning( this, "Hydrogen", trUtf8( "An error occurred importing the SoundLibrary." ) );
}
}
void SoundLibraryImportDialog::on_close_btn_clicked()
{
accept();
}
| blablack/hydrogen | src/gui/src/SoundLibrary/SoundLibraryImportDialog.cpp | C++ | gpl-2.0 | 20,246 |
<?php
defined('_JEXEC') or die;
require_once dirname(__FILE__) . '/helper.php';
//this part is for when it's gonna be database driven
$helper = new modPharmecRightBookingHelper();
$service_title = $helper->getCurrentService();
//if we don't have a title, then we need to get a list of services (including the categories)
if(empty($service_title)) {
$list_of_services = $helper->getListOfServices();
}
$document = JFactory::getDocument();
$renderer = $document->loadRenderer('module');
require(JModuleHelper::getLayoutPath('mod_pharmec_right_booking')); | GZamfir/pharmec | modules/mod_pharmec_right_booking/mod_pharmec_right_booking.php | PHP | gpl-2.0 | 557 |
/*
* wifi.cpp
*
* Created on: 24 Oct 2012
* Author: thomas
*/
#include "ns3/core-module.h"
#include "ns3/simulator.h"
#include "ns3/node.h"
#include "ns3/global-value.h"
#include "ns3/wifi-module.h"
#include "ns3/wimax-helper.h"
#include "ns3/point-to-point-helper.h"
#include "ns3/internet-module.h"
#include "ns3/udp-echo-helper.h"
#include "ns3/olsr-module.h"
#include "ns3/flow-monitor.h"
#include "ns3/applications-module.h"
#include "ns3/mobility-module.h"
#include "ns3/inet-socket-address.h"
#include "ns3/csma-module.h"
#include "ns3/fypApp.h"
#include "ns3/flow-monitor-module.h"
#include "ns3/packet-socket-address.h"
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("Wifi");
void packetReceived(Ptr<const Packet>, const Address &);
static void SetPosition(Ptr<Node> node, double x, double y)
{
Ptr<MobilityModel> mobility = node->GetObject<MobilityModel>();
Vector pos = mobility->GetPosition();
pos.x = x;
pos.y = y;
mobility->SetPosition(pos);
}
int main(int argc, char * argv[])
{
CommandLine cmd;
cmd.Parse(argc, argv);
NodeContainer wifiNodes;
wifiNodes.Create(2);
NodeContainer gatewayNode;
gatewayNode.Create(1);
WifiHelper wifi;
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default();
wifiPhy.SetPcapDataLinkType(YansWifiPhyHelper::DLT_IEEE802_11);
YansWifiChannelHelper channel;
channel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel");
channel.AddPropagationLoss("ns3::TwoRayGroundPropagationLossModel", "SystemLoss", DoubleValue(1), "HeightAboveZ", DoubleValue(1.5));
wifiPhy.Set("TxPowerStart", DoubleValue(33));
wifiPhy.Set("TxPowerEnd", DoubleValue(33));
wifiPhy.Set ("TxPowerLevels", UintegerValue(1));
wifiPhy.Set ("TxGain", DoubleValue(0));
wifiPhy.Set ("RxGain", DoubleValue(0));
wifiPhy.Set ("EnergyDetectionThreshold", DoubleValue(-61.8));
wifiPhy.Set ("CcaMode1Threshold", DoubleValue(-64.8));
wifiPhy.SetChannel(channel.Create());
NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default();
wifi.SetStandard(WIFI_PHY_STANDARD_80211b);
wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", StringValue("DsssRate1Mbps"), "ControlMode", StringValue("DsssRate1Mbps"));
Ssid ssid = Ssid("rescue-net");
wifiMac.SetType("ns3::StaWifiMac", "Ssid", SsidValue(ssid), "ActiveProbing", BooleanValue(false));
//wifiNodes.Add(gatewayNode);
NetDeviceContainer wifiStaDevs = wifi.Install(wifiPhy, wifiMac, wifiNodes);
wifiMac.SetType("ns3::ApWifiMac", "Ssid", SsidValue(ssid));
NetDeviceContainer wifiApDev = wifi.Install(wifiPhy, wifiMac, gatewayNode);
InternetStackHelper stack;
stack.Install(gatewayNode);
stack.Install(wifiNodes);
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
Ipv4AddressHelper address;
address.SetBase("10.1.6.0", "255.255.255.0");
Ipv4InterfaceContainer wifiInterfaces = address.Assign(wifiStaDevs);
Ipv4InterfaceContainer wifiApInterface = address.Assign(wifiApDev);
address.SetBase("10.1.3.0", "255.255.255.0");
Ptr<Node> t_node = wifiNodes.Get(0);
Ipv4StaticRoutingHelper helper;
Ptr<Ipv4> ipv4 = t_node->GetObject<Ipv4>();
Ptr<Ipv4StaticRouting> Ipv4stat = helper.GetStaticRouting(ipv4);
Ipv4stat->SetDefaultRoute("10.1.6.3",1,-10);
Ptr<Node> t_node2 = wifiNodes.Get(1);
Ipv4StaticRoutingHelper helper2;
Ptr<Ipv4> ipv42 = t_node2->GetObject<Ipv4>();
Ptr<Ipv4StaticRouting> Ipv4stat2 = helper2.GetStaticRouting(ipv42);
Ipv4stat2->SetDefaultRoute("10.1.6.3",1,-10);
// Install FlowMonitor on all nodes
FlowMonitorHelper flowmon;
Ptr<FlowMonitor> monitor = flowmon.InstallAll();
UdpEchoClientHelper echoClient (wifiApInterface.GetAddress(0), 9);
echoClient.SetAttribute ("MaxPackets", UintegerValue (10000));
echoClient.SetAttribute ("Interval", TimeValue (Seconds (.1)));
echoClient.SetAttribute ("PacketSize", UintegerValue (2048));
ApplicationContainer clientApps = echoClient.Install (wifiNodes.Get (0));
clientApps.Start (Seconds (2.0));
clientApps.Stop (Seconds (9.0));
/*
UdpEchoClientHelper echoClient1 (wifiApInterface.GetAddress (0), 9);
echoClient1.SetAttribute ("MaxPackets", UintegerValue (10000));
echoClient1.SetAttribute ("Interval", TimeValue (Seconds (.15)));
echoClient1.SetAttribute ("PacketSize", UintegerValue (2048));
UdpEchoClientHelper echoClient2 (wifiApInterface.GetAddress(0), 9);
echoClient2.SetAttribute ("MaxPackets", UintegerValue (10000));
echoClient2.SetAttribute ("Interval", TimeValue (Seconds (.15)));
echoClient2.SetAttribute ("PacketSize", UintegerValue (2048));
ApplicationContainer clientApps2 = echoClient2.Install (wifiNodes.Get (0));
clientApps2.Start (Seconds (2.0));
clientApps2.Stop (Seconds (9.0));
UdpEchoServerHelper echoServer(9);
ApplicationContainer serverApps = echoServer.Install(gatewayNode.Get(0));
ApplicationContainer clientApps1 = echoClient1.Install (wifiNodes.Get (1));
clientApps1.Start (Seconds (2.0));
clientApps1.Stop (Seconds (9.0));
// Print per flow statistics
monitor->CheckForLostPackets ();
Ptr<Ipv4FlowClassifier> classifier = DynamicCast<Ipv4FlowClassifier> (flowmon.GetClassifier ());
std::map<FlowId, FlowMonitor::FlowStats> stats = monitor->GetFlowStats ();
for (std::map<FlowId, FlowMonitor::FlowStats>::const_iterator iter = stats.begin (); iter != stats.end (); ++iter)
{
Ipv4FlowClassifier::FiveTuple t = classifier->FindFlow (iter->first);
std::cout << "Flow ID: " << iter->first << " Src Addr " << t.sourceAddress << " Dst Addr " << t.destinationAddress;
std::cout << "Tx Packets = " << iter->second.txPackets;
std::cout << "Rx Packets = " << iter->second.rxPackets;
std::cout << "Throughput: " << iter->second.rxBytes * 8.0 / (iter->second.timeLastRxPacket.GetSeconds()-iter->second.timeFirstTxPacket.GetSeconds()) / 1024 << " Kbps\n";
}
Simulator::Destroy();
*/
PacketSinkHelper sink("ns3::UdpSocketFactory", InetSocketAddress(Ipv4Address::GetAny(), 9));
ApplicationContainer sinkApp = sink.Install(gatewayNode.Get(0));
sinkApp.Start(Seconds(0.1));
sinkApp.Stop(Seconds(12.0));
UdpEchoServerHelper echoServer2(9);
ApplicationContainer serverApps2 = echoServer2.Install(gatewayNode.Get(0));
/*UdpEchoServerHelper echoServer(9);
ApplicationContainer serverApps = echoServer.Install(gatewayNode.Get(0));
*/
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
Ipv4GlobalRoutingHelper::RecomputeRoutingTables();
MobilityHelper mobility;
Ptr<ListPositionAllocator> positionAlloc = CreateObject <ListPositionAllocator>();
positionAlloc->Add(Vector(20,20,0));
//positionAlloc->Add(Vector(1000,0,0));
//positionAlloc->Add(Vector(450,0,0));
mobility.SetPositionAllocator(positionAlloc);
mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
//mobility.Install(hqNode);
//mobility.Install(satelliteNode);
mobility.Install(wifiNodes);
MobilityHelper wimaxMobility;
Ptr<ListPositionAllocator> wimaxPositionAlloc = CreateObject<ListPositionAllocator>();
wimaxPositionAlloc->Add(Vector(20,20,0));
wimaxMobility.SetPositionAllocator(wimaxPositionAlloc);
wimaxMobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
wimaxMobility.Install(gatewayNode);
//wimaxMobility.Install(wimaxNode);
SetPosition(gatewayNode.Get(0), -50, 0);
/*SetPosition(satelliteNode.Get(0), 50, -50.0);
SetPosition(wimaxNode.Get(0), -100, -50.0);
SetPosition(hqNode.Get(0), -50.0, -100.0);*/
SetPosition(wifiNodes.Get(0), -25, 25);
SetPosition(wifiNodes.Get(1), -50, 50);
Simulator::Stop(Seconds(10.0));
Simulator::Run();
// Print per flow statistics
monitor->CheckForLostPackets ();
Ptr<Ipv4FlowClassifier> classifier = DynamicCast<Ipv4FlowClassifier> (flowmon.GetClassifier ());
std::map<FlowId, FlowMonitor::FlowStats> stats = monitor->GetFlowStats ();
for (std::map<FlowId, FlowMonitor::FlowStats>::const_iterator iter = stats.begin (); iter != stats.end (); ++iter)
{
Ipv4FlowClassifier::FiveTuple t = classifier->FindFlow (iter->first);
std::cout << "Flow ID: " << iter->first << " Src Addr " << t.sourceAddress << " Dst Addr " << t.destinationAddress;
std::cout << "Tx Packets = " << iter->second.txPackets;
std::cout << "Rx Packets = " << iter->second.rxPackets;
std::cout << "Throughput: " << iter->second.rxBytes * 8.0 / (iter->second.timeLastRxPacket.GetSeconds()-iter->second.timeFirstTxPacket.GetSeconds()) / 1024 << " Kbps\n";
}
Simulator::Destroy();
}
int packetsRx = 0;
void packetReceived(Ptr<const Packet> p, const Address & addr)
{
if(packetsRx%2==0)
{
std::cout << "Got packet EVEN\n";
}
else
{
std::cout << "Got packet ODD\n";
}
packetsRx++;
}
FYPApp::FYPApp()
{
std::cout << "Hello i am the FYP App.\n";
}
void FYPApp::Setup(Ptr<Node> node)
{
m_node = node;
}
FYPApp::~FYPApp()
{
std::cout << "Killing this instance.\n";
}
bool FYPApp::PacketIntercept(Ptr<Packet> p, const Ipv4Header &)
{
std::cout << "GOT PACEKT!\n";
return true;
}
void FYPApp::StartApplication()
{
Ptr<Ipv4L3Protocol> ipv4Proto = m_node->GetObject<Ipv4L3Protocol> ();
if (ipv4Proto != 0)
{
NS_LOG_INFO ("Ipv4 packet interceptor added");
std::cout << "Added packet interceptor!\n";
ipv4Proto->AddPacketInterceptor (MakeCallback (&FYPApp::PacketIntercept, this), UdpL4Protocol::PROT_NUMBER);
}
else
{
std::cout << "Did not add packet interceptor!\n";
NS_LOG_INFO ("No Ipv4 with packet intercept facility");
}
std::cout << "Starting the application\n";
}
void FYPApp::StopApplication()
{
std::cout << "Stopping the application\n";
}
| kelsteNa/fyp | new.cc | C++ | gpl-2.0 | 9,431 |
<?php
/**
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; under version 2
* of the License (non-upgradable).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Copyright (c) 2013-2014 (original work) Open Assessment Technologies SA (under the project TAO-PRODUCT);
*
* @author Jérôme Bogaerts <jerome@taotesting.com>
* @license GPLv2
*/
namespace qtism\data\storage\xml\marshalling;
use qtism\data\expressions\ItemSubset;
use qtism\data\QtiComponent;
use qtism\common\collections\IdentifierCollection;
use \DOMElement;
/**
* A complex Operator marshaller focusing on the marshalling/unmarshalling process
* of itemSubset QTI operators.
*
* @author Jérôme Bogaerts <jerome@taotesting.com>
*
*/
class ItemSubsetMarshaller extends Marshaller
{
/**
* @see \qtism\data\storage\xml\marshalling\Marshaller::marshall()
*/
protected function marshall(QtiComponent $component)
{
$element = self::getDOMCradle()->createElement($this->getExpectedQtiClassName());
$sectionIdentifier = $component->getSectionIdentifier();
if (!empty($sectionIdentifier)) {
self::setDOMElementAttribute($element, 'sectionIdentifier', $sectionIdentifier);
}
$includeCategories = $component->getIncludeCategories();
if (count($includeCategories) > 0) {
self::setDOMElementAttribute($element, 'includeCategory', implode(' ', $includeCategories->getArrayCopy()));
}
$excludeCategories = $component->getExcludeCategories();
if (count($excludeCategories) > 0) {
self::setDOMElementAttribute($element, 'excludeCategory', implode(' ', $excludeCategories->getArrayCopy()));
}
return $element;
}
/**
* @see \qtism\data\storage\xml\marshalling\Marshaller::unmarshall()
*/
protected function unmarshall(DOMElement $element)
{
$object = new ItemSubset();
if (($sectionIdentifier = static::getDOMElementAttributeAs($element, 'sectionIdentifier')) !== null) {
$object->setSectionIdentifier($sectionIdentifier);
}
if (($includeCategories = static::getDOMElementAttributeAs($element, 'includeCategory')) !== null) {
$includeCategories = new IdentifierCollection(explode("\x20", $includeCategories));
$object->setIncludeCategories($includeCategories);
}
if (($excludeCategories = static::getDOMElementAttributeAs($element, 'excludeCategory')) !== null) {
$excludeCategories = new IdentifierCollection(explode("\x20", $excludeCategories));
$object->setExcludeCategories($excludeCategories);
}
return $object;
}
/**
* @see \qtism\data\storage\xml\marshalling\Marshaller::getExpectedQtiClassName()
*/
public function getExpectedQtiClassName()
{
return 'itemSubset';
}
}
| hutnikau/qti-sdk | src/qtism/data/storage/xml/marshalling/ItemSubsetMarshaller.php | PHP | gpl-2.0 | 3,416 |
<?php
if($_POST){
templatic_load_settings_page();
}
/*
Name : templatic_load_settings_page
Description : redirect user on right tab after save
*/
function templatic_load_settings_page() {
if ( $_POST["settings-submit"] == 'Y' )
{
templatic_save_settings();
$url_parameters = isset($_GET['tab'])? 'updated=true&tab='.$_GET['tab'] : 'updated=true';
$sub_url_parameters = isset($_GET['sub_tab'])? '&sub_tab='.$_GET['sub_tab'] : '';
echo "<script>location.href='".admin_url('admin.php?page=templatic_settings&'.$url_parameters.$sub_url_parameters.'')."'</script>";
}
}
/*
Name : templatic_save_settings
Description : Save all general settings
*/
function templatic_save_settings() {
global $pagenow;
$settings = get_option( "templatic_settings" );
if ( $pagenow == 'admin.php' && $_GET['page'] == 'templatic_settings' )
{
/* POST BLOCKED IP ADDRESSES */
if(isset($_POST['block_ip']) && $_POST['block_ip']!="")
{
/* CALL A FUNCTION TO SAVE IP DATA */
insert_ip_address_data($_POST['block_ip']);
}
if(isset($_REQUEST['sub_tab']) && $_REQUEST['sub_tab']=="widgets")
$_POST['templatic_widgets']=isset($_POST['templatic_widgets'])?$_POST['templatic_widgets']:array();
if(isset($_REQUEST['sub_tab']) && $_REQUEST['sub_tab']=="captcha")
$_POST['user_verification_page']=isset($_POST['user_verification_page'])?$_POST['user_verification_page']:array();
if(isset($_REQUEST['sub_tab']) && $_REQUEST['sub_tab']=="email")
{
$_POST['send_to_frnd']=isset($_POST['send_to_frnd'])?$_POST['send_to_frnd']:'';
$_POST['send_inquiry']=isset($_POST['send_inquiry'])?$_POST['send_inquiry']:'';
}
foreach($_POST as $key=>$val)
{
$settings[$key] = isset($_POST[$key])?$_POST[$key]:'';
update_option('templatic_settings', $settings);
}
}
}
?>
<?php
// general setting tab filter
add_filter('templatic_general_settings_tab', 'general_setting',10);
function general_setting($tabs ) {
$tabs['general']='General settings';
return $tabs;
}
/*
* create action for captcha-setting-data
*/
add_action('templatic_general_setting_data','captcha_setting_data');
function captcha_setting_data($column)
{
$tmpdata = get_option('templatic_settings');
switch($column)
{
case 'captcha':
$user_verification_page = @$tmpdata['user_verification_page'];?>
<p class="description"><?php _e('The settings listed here are common for the whole plugin. You just need to select the forms where you want to enable captcha.',DOMAIN); ?></p>
<tr>
<th><label><?php _e('Enable',DOMAIN);?></label></th>
<td>
<div class="input_wrap"> <input type="radio" id="recaptcha" name="recaptcha" value="recaptcha" <?php if(isset($tmpdata['recaptcha']) && $tmpdata['recaptcha'] == 'recaptcha'){?>checked="checked"<?php }?> /><label for="recaptcha"> <?php _e('WP-reCaptcha',DOMAIN);?></label></div>
<div class="input_wrap"> <input type="radio" id="playthru" name="recaptcha" <?php if(isset($tmpdata['recaptcha']) &&$tmpdata['recaptcha'] == 'playthru'){?> checked="checked"<?php }?> value="playthru" /><label for="playthru"> <?php _e('Playthru',DOMAIN);?></label></div>
<div class="clearfix"></div>
<p class="description"><?php _e('You can use any of these captcha options in your site. You can select one for you from here. You can get the plugins here : <br/> <a href="http://wordpress.org/extend/plugins/are-you-a-human/">Are You a Human</a> <br/> <a href="http://wordpress.org/extend/plugins/wp-recaptcha/">WP-reCaptcha</a>',DOMAIN); ?></p>
</td>
</tr>
<tr>
<th><label><?php _e('Enable User verification on',DOMAIN);?></label></th>
<td class="captcha_chk">
<label><input type='checkbox' name="user_verification_page[]" id="user_verification_page" <?php if(count($user_verification_page) > 0 && in_array('registration', $user_verification_page)){ echo "checked=checked"; } ?> value="registration"/> <?php _e('Registration page',DOMAIN); ?></label><div class="clearfix"></div>
<label><input type='checkbox' name="user_verification_page[]" id="user_verification_page" <?php if(count($user_verification_page) > 0 && in_array('submit', $user_verification_page)){ echo "checked=checked"; } ?> value="submit"/> <?php _e('Submit listing page',DOMAIN); ?></label><div class="clearfix"></div>
<label><input type='checkbox' name="user_verification_page[]" id="user_verification_page" <?php if(count($user_verification_page) > 0 && in_array('claim', $user_verification_page)){ echo "checked=checked"; } ?> value="claim"/> <?php _e('Claim Ownership',DOMAIN); ?></label><div class="clearfix"></div>
<label><input type='checkbox' name="user_verification_page[]" id="user_verification_page" <?php if(count($user_verification_page) > 0 && in_array('emaitofrd', $user_verification_page)){ echo "checked=checked"; } ?> value="emaitofrd"/> <?php _e('Email to Friend',DOMAIN); ?></label><div class="clearfix"></div><div class="clearfix"></div>
<!--<label><input type='checkbox' name="user_verification_page[]" id="user_verification_page" <?php if(count($user_verification_page) > 0 && in_array('sendinquiry', $user_verification_page)){ echo "checked=checked"; } ?> value="sendinquiry"/> <?php //_e('Send Inquiry',DOMAIN); ?></label><div class="clearfix"></div><div class="clearfix"></div>-->
<p class="description"><?php _e('Just check mark the forms where you want to use the captcha.',DOMAIN); ?></p>
</td>
</tr>
<?php
break;
}
}
/*
* Create email setting data action
*/
add_action('templatic_general_setting_data','email_setting_data',10);
function email_setting_data($column)
{
$tmpdata = get_option('templatic_settings');
switch($column)
{
case 'email':
?>
<p class="description"><?php _e('Email settings are common for the whole plugin. Whatever you set here will be common for all the mails sent from your domain.',DOMAIN); ?></p>
<tr>
<td>
<table style="width:60%" class="form-table">
<tr>
<th><label><?php _e('Email',DOMAIN);?></label></th>
<td>
<div class="input_wrap"> <input type="radio" id="php_mail" name="php_mail" value="php_mail" <?php if(isset($tmpdata['php_mail']) && $tmpdata['php_mail'] == 'php_mail'){?>checked="checked"<?php }?> /><label for="php_mail"> <?php _e('PHP Mail',DOMAIN);?></label></div>
<div class="input_wrap"> <input type="radio" id="wp_smtp" name="php_mail" <?php if(isset($tmpdata['php_mail']) && $tmpdata['php_mail'] == 'wp_smtp'){?> checked="checked"<?php }?> value="wp_smtp" /><label for="wp_smtp"> <?php _e('WP SMTP Mail',DOMAIN);?>
</label></div>
<p class="description"><?php _e('This setting allows you to select the mail function you want to use to send emails from your site. You can either select PHP mail or SMTP mail. By default it will send mails by using PHP Mail.',DOMAIN); ?></p>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table style="width:60%" class="form-table">
<tr>
<th><label><?php _e('Enable',DOMAIN);?></label></th>
<td>
<div class="input_wrap"> <input type="checkbox" id="send_to_frnd" name="send_to_frnd" value="send_to_frnd" <?php if(isset($tmpdata['send_to_frnd']) && $tmpdata['send_to_frnd'] == 'send_to_frnd'){?>checked="checked"<?php }?> /><label for="send_to_frnd"> <?php _e('Send to Friend',DOMAIN);?></label></div>
<div class="input_wrap"> <input type="checkbox" id="send_inquiry" name="send_inquiry" <?php if(isset($tmpdata['send_inquiry']) && $tmpdata['send_inquiry'] == 'send_inquiry'){?> checked="checked"<?php }?> value="send_inquiry" /><label for="send_inquiry"> <?php _e('Send Inquiry',DOMAIN);?>
</label>
</div>
<p class="description"><?php _e('This setting allows you to enable Send to Friend and Send Inquiry emails on your site. The link to show this emails will be seen on post detail page after you enable it from here.',DOMAIN); ?></p>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<h3><?php _e('Send email to friend/Send Inquiry Email Content Settings',DOMAIN);?></h3>
<table style="width:60%" class="widefat post">
<thead>
<tr>
<th>
<label for="email_type" class="form-textfield-label"><?php _e('Email Type',DOMAIN); ?></label>
</th>
<th>
<label for="email_sub" class="form-textfield-label"><?php _e('Email Subject',DOMAIN); ?></label>
</th>
<th>
<label for="email_desc" class="form-textfield-label"><?php _e('Email Description',DOMAIN); ?></label>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<label class="form-textfield-label"><?php _e('Send email to friend',DOMAIN); ?></label>
</td>
<td>
<textarea name="mail_friend_sub" style="width:350px; height:130px;"><?php if(isset($tmpdata['mail_friend_sub'])){echo $tmpdata['mail_friend_sub'];}else{echo 'Send to friend';} ?></textarea>
</td>
<td>
<textarea name="mail_friend_description" style="width:350px; height:130px;"><?php if(isset($tmpdata['mail_friend_description'])){echo $tmpdata['mail_friend_description'];}else{echo '<p>Dear [#$to_name#],</p>
<p>[#$frnd_comments#]</p>
<p>Link : <b>[#$post_title#]</b> </p>
<p>From, [#$your_name#]</p>
<p>Sent from -[#$post_url_link#]</p>';}?></textarea>
</td>
</tr>
<tr>
<td>
<label class="form-textfield-label"><?php _e('Send inquiry email',DOMAIN); ?></label>
</td>
<td>
<textarea name="send_inquirey_email_sub" style="width:350px; height:130px;"><?php if(isset($tmpdata['send_inquirey_email_sub'])){echo $tmpdata['send_inquirey_email_sub'];}else{echo 'Inquiry email';}?></textarea>
</td>
<td>
<textarea name="send_inquirey_email_description" style="width:350px; height:130px;"><?php if(isset($tmpdata['send_inquirey_email_description'])){echo $tmpdata['send_inquirey_email_description'];}else{echo '<p>Dear [#to_name#],</p><p>Here is an inquiry for <b>[#post_title#]</b>. </p><p>Below is the message. </p><p><b>Subject : [#frnd_subject#]</b>.</p><p>[#frnd_comments#]</p><p>Thank you,<br /> [#your_name#]</p>';}?></textarea>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<?php
break;
}
}
/*
* Apply filter for get the general setting tabs
* if you want to create new main tab in general setting menu then use 'templatic_general_settings_tab' filter hook and pass the tabs arrya in filter hook function and return tabs array.
*/
@$tabs = apply_filters('templatic_general_settings_tab',$tabs);
echo '<div id="icon-options-general" class="icon32"><br></div>';
echo '<h2 class="nav-tab-wrapper">';
$i=0;
foreach( $tabs as $tab => $name ){
if($i==0)
$tab_key=$tab;
$current_tab=isset($_REQUEST['tab'])?$_REQUEST['tab']:$tab_key;
$class = ( $tab == $current_tab) ? ' nav-tab-active' : '';
echo "<a class='nav-tab$class' href='?page=templatic_settings&tab=$tab'>$name</a>";
$i++;
}
echo '</h2>';
/* Finish the general setting menu main tabs */
/*
* create the general setting sub tabs
*/
if($current_tab=='general'):
$i=0;
/*Add Filter for create the general setting sub tab for Captcha setting */
add_filter('templatic_general_settings_subtabs', 'captcha_setting',12);
function captcha_setting($sub_tabs ) {
$sub_tabs['captcha']='Captcha Settings';
$sub_tabs['email']='Email Settings';
return $sub_tabs;
}
/*Apply filter for create the general setting subtabs */
/*
* if you want to create new subtabs in general setting menu then use 'templatic_general_settings_subtabs' filter hook function and pass the subtabs array in filter hook function and return subtabs array.
*/
@$sub_tabs = apply_filters('templatic_general_settings_subtabs',$sub_tabs);
echo '<h3 class="nav-tab-wrapper">';
foreach($sub_tabs as $key=>$value)
{
if($i==0)
$sab_key=$key;
$current=isset($_REQUEST['sub_tab'])?$_REQUEST['sub_tab']:$sab_key;
$class = (isset($current) && ($key == $current)) ? ' nav-tab-active' : '';
echo "<a id='$key' class='nav-tab$class' href='?page=templatic_settings&tab=general&sub_tab=$key'>$value</a>";
$i++;
}
echo '</h3>';
endif;
?>
<!-- Display the message-->
<?php if(isset($_REQUEST['updated']) && $_REQUEST['updated'] == 'true' ): ?>
<div class="act_success updated" id="message">
<p><?php echo "<strong>Record updated successfully</strong>"; ?> .</p>
</div>
<?php endif; ?>
<!--Finish the display message-->
<div class="templatic_settings">
<form method="post" class="form_style" action="<?php admin_url( 'themes.php?page=templatic_settings' ); ?>">
<table class="form-table">
<?php
$j=0;
$i=0;
foreach( $tabs as $tab => $name ){
if($j==0)
$tab_key=$tab;
if($current_tab=='general'): /* Display the general setting subtabs menu */
//display general s etting tab wise displaydata
foreach($sub_tabs as $key=>$value)
{
if($i==0)
$sab_key=$key;
$current=isset($_REQUEST['sub_tab'])?$_REQUEST['sub_tab']:$sab_key;
if($current==$key)
do_action('templatic_general_setting_data',$key);/*add action hook 'templatic_general_setting_data' for show the subtab data. pass the general setting subtabs key. */
$i++;
}
endif;
if(isset($_REQUEST['tab']) && $_REQUEST['tab']==$tab):
do_action('templatic_general_data',$tab);/* add action hook 'templatic_general_data' for show the general setting tabs data. pass the general setting tabs key. */
endif;
$tab_key="";
$current_tab='';
$j++;
}
?>
</table>
<p class="submit" style="clear: both;">
<input type="submit" name="Submit" class="button-primary" value="Save All Settings" />
<input type="hidden" name="settings-submit" value="Y" />
</p>
</form>
</div> | imshashank/osuevents | wp-content/plugins/Tevolution/tmplconnector/monetize/templatic-generalizaion/general_settings.php | PHP | gpl-2.0 | 15,380 |
<?php $captcha_word = 'DZ5E'; ?> | CoordCulturaDigital-Minc/culturadigital.br | wp-content/plugins/si-captcha-for-wordpress/captcha-secureimage/captcha-temp/pfOxT6CtvmexP9dq.php | PHP | gpl-2.0 | 32 |
/*
* Rvzware based in CAPAWARE 3D
*
* Rvzware is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* Rvzware is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this application; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* The Rvzware development team
*/
#include <sstream>
//#include <stdafx.h>
#include <cpw/entity/Entity.h>
#include <cpw/entity/EntityFactory.h>
#include <cpw/entity/EntityRegistry.h>
#include <cpw/entity/Element3D.h>
#include <cpw/persistent/database/DataBase.h>
#include <cpw/persistent/database/Table.h>
#include <cpw/persistent/database/PersistentDBCallBack.h>
using namespace cpw;
//! DB constructor
/*!
Database constructor.
\param id Identifier
\param class_name Class name
*/
DataBase::DataBase(const cpw::TypeId id,
const std::string &class_name) : cpw::ContainerLayer(id, class_name)
{
db_boConnected=false;//Initially no connection has been stablished
}
//! DB destructor
/*!
Database destructor.
*/
DataBase::~DataBase(void)
{
Disconnect();
}
//! Adds entity to the layer
/*!
Adds entity to the layer
\param entity Entity to be added
*/
int DataBase::Add(Entity *entity)
{
ContainerLayer::Add(entity);
entity->SetPersistentCallBack(new PersistentDBCallBack);
return 0;
}
//! DB Disconnction
/*!
If the connection is currently stablished the connection is finished
*/
void DataBase::Disconnect()
{
//Only if the connection is currently stablished
if (db_boConnected)
{
PQfinish(db_conn);
db_boConnected=false;
}
}
DataBase::DataBase(const DataBase &database) : cpw::ContainerLayer(database)
{
db_boConnected=false;//Initially not connected
Modified();
}
DataBase &DataBase::operator = (const DataBase &database)
{
ContainerLayer::operator =(database);
Modified();
return *this;
}
//! Persistence manager for DB
/*!
Persistence manager for DB
*/
int DataBase::CreatePersistence()
{
ContainerLayer::CreatePersistence();
//Elements to be saved
AddPersistence(std::string("db_host"), db_host);
AddPersistence(std::string("db_user"), db_user);
AddPersistence(std::string("db_passwd"), db_passwd);
AddPersistence(std::string("db_name"), db_name);
//Arrays are managed diversely
AddPersistenceLevel((std::string)"db_tablenames");
for(std::vector<std::string>::iterator i= db_tablenames.begin(); i!=db_tablenames.end(); i++)
{
AddPersistence(std::string("db_tablename"), *i);
}
RemovePersistenceLevel();
AddPersistenceLevel((std::string)"db_columnspertable");
for(std::vector<std::vector<std::string> >::iterator i= db_columnspertable.begin(); i!=db_columnspertable.end(); i++)
{
AddPersistenceLevel((std::string)"db_columns");
for(std::vector<std::string>::iterator j = i->begin(); j != i->end(); j++)
{
AddPersistence(std::string("db_columnname"), *j);
}
RemovePersistenceLevel();
}
RemovePersistenceLevel();
return 0;
}
int DataBase::AdaptPersistence(cpw::Node *root)
{
ContainerLayer::AdaptPersistence(root);
db_host = (root->GetChildValue("db_host"));
db_user = (root->GetChildValue("db_user"));
db_passwd = (root->GetChildValue("db_passwd"));
db_name = (root->GetChildValue("db_name"));
std::vector<cpw::Node *> root_children = root->GetChildren();
std::vector<cpw::Node *>::iterator i;
for(i = root_children.begin(); i != root_children.end(); i++)
{
if ((*i)->GetName() == "db_tablenames")
{
std::vector<cpw::Node *> table_children = (*i)->GetChildren();
std::vector<cpw::Node *>::iterator j;
for(j = table_children.begin(); j != table_children.end(); j++)
{
db_tablenames.push_back((*j)->GetValue());
}
}
}
for(i = root_children.begin(); i != root_children.end(); i++)
{
if ((*i)->GetName() == "db_columnspertable")
{
std::vector<cpw::Node *> tables_children = (*i)->GetChildren();
std::vector<cpw::Node *>::iterator j;
for(j = tables_children.begin(); j != tables_children.end(); j++)
{
std::vector<cpw::Node *> columns_children = (*j)->GetChildren();
std::vector<cpw::Node *>::iterator k;
db_columnspertable.push_back(std::vector<std::string>());
for(k = columns_children.begin(); k != columns_children.end(); k++)
{
db_columnspertable.back().push_back((*k)->GetValue());
}
}
}
}
//Stablishes connection if necessary
SetConnected(OpenConnection());
//Read DB tables
ReadTables();
return 0;
}
//! Gets DB tables
/*!
Gets DB tables returning the available number. It also saves in the database the field names
*/
int DataBase::GetDBTables()
{
//No tables initially contained
int ntables=0;
//Getting the connection id of the DB
PGconn *conn=this->GetDBConn();
//Is the connection is running
if (this->GetConnected())
{
PGresult *res;
int nt;
//The SQL command is composed to get the table information
//A temporal var is used to get table info
std::vector<std::string> tables;
//SQL request
res = PQexec(conn, "select table_name from information_schema.tables where table_schema = 'public' and TABLE_TYPE = 'BASE TABLE'");
//If no NULL answer is got
if(res != NULL)
{
int npos;
ExecStatusType qstatus = PQresultStatus(res);
//Different status require different actions
//Currently only PGRES_TUPLES_OK status is treated
switch(qstatus) {
case PGRES_COMMAND_OK:
//printf("Result completed successfully.\n");
break;
case PGRES_EMPTY_QUERY:
//printf("Empty query sent to server.\n");
break;
case PGRES_TUPLES_OK:
ntables = PQntuples(res);
npos=PQfnumber(res, "table_name");
//Getting table names
for (nt = 0; nt < ntables; nt++)
{
// Get the field values (we ignore possibility they are null!!!!)
tables.push_back(PQgetvalue(res, nt, npos));
}
//Saving table names in the related DB variable
this->SetDBTableNames(tables);
break;
case PGRES_COPY_OUT: // from server
case PGRES_COPY_IN: // to server
// printf("Data copy between server and client in progress.\n");
break;
case PGRES_BAD_RESPONSE:
// printf("Bad response from server.\n");
break;
case PGRES_NONFATAL_ERROR:
// printf("Non-fatal error returned from server.\n");
break;
case PGRES_FATAL_ERROR:
//terminate(PQresultErrorMessage(res),conn);
break;
default:
//terminate("Query status unknown, terminating.\n", conn);
break;
}
}
PQclear(res);
//Gathering information about the different columns or fiels od each table
std::vector<std::vector<std::string> > columnspertable;
std::vector<std::string> columnnames;
//Thos names are obtained for each table
for (nt=0;nt<ntables;nt++)
{
//The SQL request is composed
int ncolumns=0;
std::string str;
str = "SELECT column_name FROM information_schema.columns WHERE table_name = '" + tables.at(nt) + "'";
res = PQexec(conn, str.c_str());
columnnames.clear();
//If there is a good answer
if (PQresultStatus(res) == PGRES_TUPLES_OK)
{
ncolumns=PQntuples(res);
int npos=PQfnumber(res, "column_name");
//Every colukn/field name is read
for (int nc = 0; nc < ncolumns; nc++)
{
// Get the field values (we ignore possibility they are null!!!!)
columnnames.push_back(PQgetvalue(res, nc, npos));
}
//Adding the name to the ttemp var
columnspertable.push_back(columnnames);
}
PQclear(res);
//Saving field info in the DB instance
this->SetDBColumnsperTable(columnspertable);
}
}
//The number of tables is returned
return ntables;
}
//! Gets the records available in a DB table for a given selection of fields
/*!
Gets the records available in a DB table for a given number of fields
\param fields Fields to be returned
\param tablename Table to be consulted
*/
PGresult * DataBase::GetDBRecordsfromTable(std::string &fields, std::string &tablename)
{
//Getting the connection id of the DB
PGconn *conn=this->GetDBConn();
//Is the connection is running
if (this->GetConnected())
{
PGresult *res;
std::string db_row;//temp used to save records
//Temporal vars are used to save columns etc.
std::vector<std::vector<std::string> > columnspertable;
std::vector<std::string> columns;
//The SQL command is composed to get the table information
//SQL request to get the given fields of the selected table
int neltos=0;
std::string str;
str = "SELECT " + fields + " FROM " + tablename;
res = PQexec(conn, str.c_str());
//Is the command was succesful
if (PQresultStatus(res) == PGRES_TUPLES_OK)
{
//Compiles db_row with all the records
for (int i = 0; i < PQntuples(res); i++)
{
db_row.clear();//clear
for (int j = 0; j < PQnfields(res); j++)
{
db_row=db_row + PQgetvalue(res, i, j) + " ";
}
}
return res;
}
PQclear(res);
}
return NULL;
}
//! Inserts a record in the database
/*!
Inserts a record in the database. It should return the proper identifier error but right now it returns 0 (existing file)
\param fields Fields to be written
\param tablename Table to be used
\param values Field values to be written
*/
PersistentError DataBase::InsertDBRecordinTable(std::string &tablename,std::string &fields,std::string &values)
{
//Is connected?
if (GetConnected())
{
PGresult *res;
//the SQL request is composed
std::string str;
//Using the input arguments the request is formed
str = "INSERT INTO " + tablename + "(" + fields + ") VALUES (" + values + ")";
res = PQexec(GetDBConn(), str.c_str());
//If no null answer
if(res != NULL)
{
//Was the command correctly executed?
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "INSERT failed: %s", PQerrorMessage(GetDBConn()));
PQclear(res);
}
else return (cpw::PersistentError)0;
//PQclear(res);//Should it be done always
}
}
return (cpw::PersistentError)-1;
}
//! Remove records satisfying a condition
/*!
Remove records satisfying a condition
\param tablename Table to be used
\param condition Condition to be checked
*/
void DataBase::DeleteDBRecordsinTable(std::string &tablename,std::string &condition)
{
//Getting the connection id of the DB
PGconn *conn=this->GetDBConn();
//I the conenction is running
if (this->GetConnected())
{
//temp vars
PGresult *res;
//SQL request
std::string str;
str = "DELETE FROM " + tablename + condition;
res = PQexec(conn, str.c_str());
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "DELETE failed: %s", PQerrorMessage(conn));
PQclear(res);
}
}
}
//! Creates a table
/*!
Creates a table
\param tablename Table to be used
*/
PersistentError DataBase::CreateDBTable(std::string &tablename)
{
//If the connection is running
if (GetConnected())
{
PGresult *res;
//SQL command composition
std::string str;
//The table is created without fields, those will be added with the first record
str = "CREATE TABLE " + tablename + " ()";
res = PQexec(GetDBConn(), str.c_str());
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "CREATE failed: %s", PQerrorMessage(GetDBConn()));
PQclear(res);
}
else return (cpw::PersistentError)0;
//PQclear(res);//Is necessary?
}
return (cpw::PersistentError)-1;
}
//! Modifies a table
/*!
Modifies a table in terms of fields and their type
\param tablename Table to be used
\param fieldandtype Field and new type
*/
PersistentError DataBase::AlterDBTable(std::string &tablename,std::string &fieldandtype)
{
//If the connection is running
if (GetConnected())
{
PGresult *res;
//The table is modified adding a columns
std::string str;
str = "ALTER TABLE " + tablename + " add " + fieldandtype ;
res = PQexec(GetDBConn(), str.c_str());
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "ALTER failed: %s", PQerrorMessage(GetDBConn()));
PQclear(res);
}
else return (cpw::PersistentError)0;
}
return (cpw::PersistentError)-1;
}
//! Adds a geospatial field to a table
/*!
Modifies a table in terms of fields and their type
\param tablename Table to be used
*/
PersistentError DataBase::AddLocationColumn(std::string &tablename,std::string &columnname)
{
//Is the connection runnning
if (GetConnected())
{
PGresult *res;
//The SQL request is composed
std::string str;
//Currently only a POINT element is considered
//select AddGeometryColumn('nombretabla','utm',4326,'POINT','2')
//This command do not use capital letters to find the table, therefore we have to transform
//the tablename to avoid capitals before composing the SQL request
std::transform(tablename.begin(), tablename.end(), tablename.begin(), tolower);
str = "select AddGeometryColumn('" + tablename + "','" + columnname + "',4326,'POINT','2')";
res = PQexec(GetDBConn(), str.c_str());
//If it did not work
/*if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
fprintf(stderr, "AddGeometryColumn failed: %s", PQerrorMessage(GetDBConn()));
PQclear(res);
}
else*/ return (cpw::PersistentError)0;
}
return (cpw::PersistentError)-1;
}
//! Reads tables and records
/*!
Reads tables and records
*/
void DataBase::ReadTables()
{
//Getting DB tables
int ntables=GetDBTables();
//Reading table contents if any
if (ntables)
{
//Getting table names
std::vector<std::string> tablenames=GetDBTableNames();
//Tables are added to the tree only if they contain geospatial data
for (int i=0;i<ntables;i++)
{
//To check if a table contains geo data
//select * from geometry_columns where f_table_name=tablenames.at(i)
//getting the geo field name and its type
//temporal var
std::vector<std::string> tables;
//SQL request
PGresult *resG;
std::string aux="select * from geometry_columns where f_table_name='" + tablenames.at(i) + "'";
resG = PQexec(GetDBConn(), aux.c_str() );
//NO null answer
if(resG != NULL)
{
//OK answer
if (PQresultStatus(resG) == PGRES_TUPLES_OK)
{
//The table contains geo data, adds the table to the tree and its records
if (PQntuples(resG))
{
//Table instance
cpw::Table new_tablep;
cpw::Entity* new_table = cpw::EntityFactory::GetInstance()->CreateEntity(new_tablep.GetClassName());
cpw::Table &table= *((cpw::Table*) new_table);
new_table->SetName(tablenames.at(i));
//It is assumed that the table contains columns
table.SetEmpty(false);
cpw::EntityRegistry::GetInstance()->Add(new_table);
Add(new_table);
//For each record (indeed we expect only one per table, is has not been tested with more)
for (int nl = 0; nl < PQntuples(resG); nl++)
{
//Getting the table name
std::string columnname;
int ncolumn=PQfnumber(resG, "f_geometry_column");
//geo spatial field name
columnname=PQgetvalue(resG, nl, ncolumn);
//Geo information is coded, thus it must be done the inverse operation to GeometryfromText, PostGIS function asewkt allows that
//http://www.mapbender.org/presentations/Spatial_Data_Management_Arnulf_Christl/Spatial_Data_Management_Arnulf_Christl.pdf
//MOre utilities http://postgis.refractions.net/docs/ch03.html#id2656610
//The table column names are requested
//Each column is treated accordingly (specially the geospacial info)
std::string consulta;
std::string str,Name;
str = "SELECT column_name FROM information_schema.columns WHERE table_name = '" + tablenames.at(i) + "'";
PGresult *resC = PQexec(GetDBConn(), str.c_str());
//If there are columns we compose in column the total collection of fields to be read from the table
if (PQresultStatus(resC) == PGRES_TUPLES_OK)
{
//Position of the column containing the column_name
int npos=PQfnumber(resC, "column_name");
//For each column
for (int j = 0; j < PQntuples(resC); j++)
{
//The name is read
std::string strtmp;
strtmp=PQgetvalue(resC, j, npos);
if (j)
{
if (strtmp.compare(columnname)==0)//Column with geo spatial info, thus a special treatment is needed
{
consulta.append(" , asText("+ columnname + ")");
}
else//normal column
{
consulta.append(" , "+ strtmp );
}
}
else
{//We assume that the first column will never be the geospatial column
consulta=strtmp;
}
}
}
else Name="name"; //Default option
PQclear(resC);
//Composing SQL request considering the field names just read from tha table
//For the geospatial column:
//asewkt gets srid and point asText erturns only the point. asGml asSvg asKml
PGresult *res=GetDBRecordsfromTable((std::string&)consulta,(std::string&)tablenames.at(i));
//If no null request
if (res!=NULL)
{
if (PQresultStatus(res) == PGRES_TUPLES_OK)
{
//The records are added to the later-tree
//Right now is done for a specific set of fields (that are known)
for (int nr = 0; nr < PQntuples(res); nr++)
{
//lement3d instance
std::string strtmp;
cpw::Element3D new_elto3dp;
cpw::Entity* new_elto3d = cpw::EntityFactory::GetInstance()->CreateEntity(new_elto3dp.GetClassName());
//The field id gives us the field type
int pos=PQfnumber(res, "id");
strtmp=PQgetvalue(res, nr, pos);
cpw::TypeId id(strtmp);
new_elto3d->SetID(id);
pos=PQfnumber(res, "name");
strtmp=PQgetvalue(res, nr, pos);
new_elto3d->SetName(strtmp);
pos=PQfnumber(res, "font");
strtmp=PQgetvalue(res, nr, pos);
new_elto3d->SetFont(strtmp);
pos=PQfnumber(res, "text");
strtmp=PQgetvalue(res, nr, pos);
((cpw::Element *) new_elto3d)->SetText(strtmp);
pos=PQfnumber(res, "description");
strtmp=PQgetvalue(res, nr, pos);
new_elto3d->SetDescription(strtmp);
pos=PQfnumber(res, "primitive_url");
strtmp=PQgetvalue(res, nr, pos);
//To avoid problems
std::replace(strtmp.begin(), strtmp.end(), '/', '\\');
new_elto3d->SetPrimitiveUrl(strtmp);
pos=PQfnumber(res, "icon");
strtmp=PQgetvalue(res, nr, pos);
//To avoid problems
std::replace(strtmp.begin(), strtmp.end(), '/', '\\');
new_elto3d->SetIcon(strtmp);
pos=PQfnumber(res, "html");
strtmp=PQgetvalue(res, nr, pos);
new_elto3d->SetHtml(strtmp);
pos=PQfnumber(res, "model_url");
strtmp=PQgetvalue(res, nr, pos);
//To avoid problems
std::replace(strtmp.begin(), strtmp.end(), '/', '\\');
((cpw::Element3D *) new_elto3d)->SetModelUrl(strtmp);
//booleans
pos=PQfnumber(res, "dynamic");
strtmp=PQgetvalue(res, nr, pos);
if (atol(strtmp.c_str()))
new_elto3d->SetDynamic(true);
else
new_elto3d->SetDynamic(false);
pos=PQfnumber(res, "visible");
strtmp=PQgetvalue(res, nr, pos);
if (atol(strtmp.c_str()))
new_elto3d->SetVisible(true);
else
new_elto3d->SetVisible(false);
pos=PQfnumber(res, "animate");
strtmp=PQgetvalue(res, nr, pos);
if (atol(strtmp.c_str()))
new_elto3d->SetAnimate(true);
else
new_elto3d->SetAnimate(false);
pos=PQfnumber(res, "published");
strtmp=PQgetvalue(res, nr, pos);
if (atol(strtmp.c_str()))
new_elto3d->SetPublished(true);
else
new_elto3d->SetPublished(false);
//Numerical values with spaces for scale
pos=PQfnumber(res, "scale");
strtmp=PQgetvalue(res, nr, pos);//This string contains three numerical values separates with blanks
//First blank
int fb=strtmp.find_first_of(" ");
//second blank
int sb=strtmp.find_first_of(" ",fb+1);
//Getting the three numerical valus
float fvals[3];
fvals[0]=(float)atof(strtmp.substr(0,fb).c_str());
fvals[1]=(float)atof(strtmp.substr(fb+1,sb-fb).c_str());
fvals[2]=(float)atof(strtmp.substr(sb,strtmp.length()-sb).c_str());
((cpw::Element *) new_elto3d)->SetScale(fvals);
//Numerical values with spaces for oritntation
pos=PQfnumber(res, "orientation");
strtmp=PQgetvalue(res, nr, pos);//This string contains three numerical values separates with blanks
//First blank position
fb=strtmp.find_first_of(" ");
//Second blank position
sb=strtmp.find_first_of(" ",fb+1);
//The three numerical values are extracted
fvals[0]=(float)atof(strtmp.substr(0,fb).c_str());
fvals[1]=(float)atof(strtmp.substr(fb+1,sb-fb).c_str());
fvals[2]=(float)atof(strtmp.substr(sb,strtmp.length()-sb).c_str());
((cpw::Element *) new_elto3d)->SetOrientation(fvals);
//geospatial information column
int posgeo=PQfnumber(res, "astext");
strtmp=PQgetvalue(res, nr, posgeo);
//The open ( is saearched
sb=strtmp.find_first_of("(");
//A blank i slocated
fb=strtmp.find_first_of(" ",sb+1);
//the final ) is located
int lb=strtmp.find_first_of(")");
//latitude is between the ( and bank,
fvals[0]=(float)atof(strtmp.substr(sb+1,fb-(sb+1)).c_str());//latitude
fvals[1]=(float)atof(strtmp.substr(fb+1,lb-fb).c_str());//lenght
//Conversion to UTM
int RefEllipsoid = 23;//WGS-84. See list with file "LatLong-UTM conversion.cpp" for id numbers
UTMLL utm_aux;
double UTMNorthing=0.f, UTMEasting=0.f;
char UTMZone[5];
utm_aux.LLtoUTM(RefEllipsoid, fvals[0], fvals[1], UTMNorthing, UTMEasting,UTMZone);
//The height was stored separately
pos=PQfnumber(res, "utm_z");
strtmp=PQgetvalue(res, nr, pos);//La cadena contiene los tres valores separados por espacios
float height=(float)atof(strtmp.c_str());
((cpw::Element *) new_elto3d)->SetUtm(UTMEasting,UTMNorthing,height);
//Adding the element to the layer-tree
cpw::EntityRegistry::GetInstance()->Add(new_elto3d);
table.Add(new_elto3d);
}
}
}
PQclear(res);
}
}//records available
}//OK
}//Not null
PQclear(resG);
}
}
}
//! Opens connection with DB
/*!
Opens connection with DB
*/
//Falta quizás comprobar si ya está conectada antes de hacerlo de nuevo
bool DataBase::OpenConnection()
{
PGconn *conn;
std::string conninfo;
//Composing connect command
std::string str;
str = "hostaddr=" + GetDBHost() + " port=5432" + " user=" + GetDBUser() + " password=" + GetDBPasswd() + " dbname=" + GetDBName();
if (str.c_str()!=NULL)
conninfo = str;
else//default connection
conninfo = "hostaddr=10.22.144.150 port=5432 user=postgres2 password=agustin dbname=pepe";
// Connecting with DB
conn = PQconnectdb(conninfo.c_str());
//Saving identifier
SetDBConn(conn);
//conn = PQconnectdb(conninfo);
// Checking connection
if (PQstatus(conn) != CONNECTION_OK)
{
fprintf(stderr, "Connection to database failed: %s",
PQerrorMessage(conn));
Disconnect();
return false;
}
return true;
}
/*
PRIMARY KEY clave primaria
//Eliminar una tabla
//DROP TABLE customer
//Eliminar los datos de la tabla pero no la tabla
//TRUNCATE TABLE customer
//Añadir una columna a una tabla (customer), indicamos el nombre y tipo
//ALTER table customer add Gender char(1)
//Modificar el nombre de una columna
//ALTER table customer change Address Addr char(50)
//Modificar el tipo de una columna
//ALTER table customer modify Addr char(30)
//Eliminar una columna
//ALTER table customer drop Gender
//Borrar un registro
DELETE FROM Store_Information
WHERE store_name = "Los Angeles"
*/
| BackupTheBerlios/rvzware | src/cpw/persistent/database/DataBase.cpp | C++ | gpl-2.0 | 25,854 |
// --------------------------------------------------------------------------
#include <vector>
#include <string>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <getopt.h>
// --------------------------------------------------------------------------
#include "ORepHelpers.h"
#include "ObjectRepository.h"
#include "ObjectRepositoryFactory.h"
#include "Exceptions.h"
#include "UniSetObject.h"
#include "UniSetTypes.h"
#include "ObjectsManager.h"
#include "MessageType.h"
#include "Configuration.h"
#include "ObjectIndex_XML.h"
#include "Debug.h"
// --------------------------------------------------------------------------
using namespace std;
using namespace UniSetTypes;
// --------------------------------------------------------------------------
enum Command
{
StartUp,
FoldUp,
Finish,
Exist,
Configure,
LogRotate
};
static struct option longopts[] = {
{ "help", no_argument, 0, 'h' },
{ "confile", required_argument, 0, 'c' },
{ "create", no_argument, 0, 'b' },
{ "exist", no_argument, 0, 'e' },
{ "omap", no_argument, 0, 'o' },
{ "msgmap", no_argument, 0, 'm' },
{ "start", no_argument, 0, 's' },
{ "finish", no_argument, 0, 'f' },
{ "foldUp", no_argument, 0, 'u' },
{ "configure", required_argument, 0, 'r' },
{ "logrotate", required_argument, 0, 'l' },
{ "info", required_argument, 0, 'i' },
{ "setValue", required_argument, 0, 'x' },
{ "getValue", required_argument, 0, 'g' },
{ "getRawValue", required_argument, 0, 'w' },
{ "getCalibrate", required_argument, 0, 'y' },
{ "oinfo", required_argument, 0, 'p' },
{ "verbose", no_argument, 0, 'v' },
{ NULL, 0, 0, 0 }
};
string conffile("configure.xml");
// --------------------------------------------------------------------------
static bool commandToAll( const string& section, ObjectRepository *rep, Command cmd );
static void createSections( UniSetTypes::Configuration* c );
// --------------------------------------------------------------------------
int omap();
int msgmap();
int configure( const string& args, UniversalInterface &ui );
int logRotate( const string& args, UniversalInterface &ui );
int setValue( const string& args, UniversalInterface &ui, Configuration* conf = UniSetTypes::conf );
int getValue( const string& args, UniversalInterface &ui, Configuration* conf = UniSetTypes::conf );
int getRawValue( const string& args, UniversalInterface &ui );
int getState( const string& args, UniversalInterface &ui );
int getCalibrate( const string& args, UniversalInterface &ui );
int oinfo( const string& args, UniversalInterface &ui );
// --------------------------------------------------------------------------
static void print_help(int width, const string& cmd, const string& help, const string& tab=" " )
{
// чтобы не менять параметры основного потока
// создаём свой stream...
ostringstream info;
info.setf(ios::left, ios::adjustfield);
info << tab << setw(width) << cmd << " - " << help;
cout << info.str();
}
// --------------------------------------------------------------------------
static void short_usage()
{
cout << "Usage: uniset-admin [--confile configure.xml] --command [arg] \n for detailed information arg --help" << endl;
}
// --------------------------------------------------------------------------
static void usage()
{
cout << "\nUsage: \n\tuniset-admin [--confile configure.xml] --command [arg]\n";
cout << "commands list:\n";
cout << "-----------------------------------------\n";
print_help(24, "-с|--confile file.xml ","Используемый конфигурационный файл\n");
cout << endl;
print_help(24, "-b|--create ","Создание репозитория\n");
print_help(24, "-e|--exist ","Вызов функции exist() показывающей какие объекты зарегистрированы и доступны.\n");
print_help(24, "-o|--omap ","Вывод на экран списка объектов с идентификаторами.\n");
print_help(24, "-m|--msgmap ","Вывод на экран списка сообщений с идентификаторами.\n");
print_help(24, "-s|--start ","Посылка SystemMessage::StartUp всем объектам (процессам)\n");
print_help(24, "-u|--foldUp ","Посылка SystemMessage::FoldUp всем объектам (процессам)\n");
print_help(24, "-f|--finish ","Посылка SystemMessage::Finish всем объектам (процессам)\n");
print_help(24, "-h|--help ","Вывести это сообщение.\n");
cout << endl;
print_help(36, "-r|--configure [FullObjName] ","Посылка SystemMessage::ReConfiguration всем объектам (процессам) или заданному по имени (FullObjName).\n");
print_help(36, "-l|--logrotate [FullObjName] ","Посылка SystemMessage::LogRotate всем объектам (процессам) или заданному по имени (FullObjName).\n");
print_help(36, "-p|--oinfo OID ","Получить информацию об объекте (SimpleInfo).\n");
cout << endl;
print_help(48, "-x|--setValue id1@node1=val,id2@node2=val2,id3=val3,.. ","Выставить значения датчиков\n");
print_help(36, "-g|--getValue id1@node1,id2@node2,id3,id4 ","Получить значения датчиков.\n");
cout << endl;
print_help(36, "-w|--getRawValue id1@node1=val,id2@node2=val2,id3=val3,.. ","Получить 'сырое' значение.\n");
print_help(36, "-y|--getCalibrate id1@node1=val,id2@node2=val2,id3=val3,.. ","Получить параметры калибровки.\n");
print_help(36, "-v|--verbose","Подробный вывод логов.\n");
cout << endl;
}
// --------------------------------------------------------------------------------------
/*!
\todo Оптимизировать commandToAll, т.к. сейчас НА КАЖДОМ ШАГЕ цикла
создаётся сообщение и происходит преобразование в TransportMessage.
TransportMessage можно создать один раз до цикла.
*/
// --------------------------------------------------------------------------------------
static bool verb = false;
int main(int argc, char** argv)
{
try
{
int optindex = 0;
char opt = 0;
while( (opt = getopt_long(argc, argv, "vhc:beomsfur:l:i:x:g:w:y:p:",longopts,&optindex)) != -1 )
{
switch (opt) //разбираем параметры
{
case 'h': //--help
usage();
return 0;
case 'v':
verb=true;
break;
case 'c': //--confile
conffile = optarg;
break;
case 'o': //--omap
{
uniset_init(argc,argv,conffile);
return omap();
}
break;
case 'b': //--create
{
uniset_init(argc,argv,conffile);
createSections(conf);
}
return 0;
case 'm': //--msgmap
{
uniset_init(argc,argv,conffile);
return msgmap();
}
break;
case 'x': //--setValue
{
uniset_init(argc,argv,conffile);
UniversalInterface ui(conf);
return setValue(optarg,ui);
}
break;
case 'g': //--getValue
{
// cout<<"(main):received option --getValue='"<<optarg<<"'"<<endl;
uniset_init(argc,argv,conffile);
UniversalInterface ui(conf);
return getValue(optarg,ui);
}
break;
case 'w': //--getRawValue
{
// cout<<"(main):received option --getRawValue='"<<optarg<<"'"<<endl;
uniset_init(argc,argv,conffile);
UniversalInterface ui(conf);
return getRawValue(optarg,ui);
}
break;
case 'p': //--oinfo
{
// cout<<"(main):received option --oinfo='"<<optarg<<"'"<<endl;
uniset_init(argc,argv,conffile);
UniversalInterface ui(conf);
return oinfo(optarg,ui);
}
break;
case 'e': //--exist
{
// cout<<"(main):received option --exist"<<endl;
uniset_init(argc,argv,conffile);
UniversalInterface ui(conf);
Command cmd=Exist;
verb = true;
ObjectRepository* rep = new ObjectRepository(conf);
commandToAll(conf->getServicesSection(), rep, (Command)cmd);
commandToAll(conf->getControllersSection(), rep, (Command)cmd);
commandToAll(conf->getObjectsSection(), rep, (Command)cmd);
delete rep;
// cout<<"(exist): done"<<endl;
}
return 0;
case 's': //--start
{
// cout<<"(main):received option --start"<<endl;
uniset_init(argc,argv,conffile);
UniversalInterface ui(conf);
Command cmd=StartUp;
ObjectRepository* rep = new ObjectRepository(conf);
commandToAll(conf->getServicesSection(), rep, (Command)cmd);
commandToAll(conf->getControllersSection(), rep, (Command)cmd);
commandToAll(conf->getObjectsSection(), rep, (Command)cmd);
delete rep;
}
return 0;
case 'r': //--configure
{
uniset_init(argc,argv,conffile);
UniversalInterface ui(conf);
return configure(optarg,ui);
}
break;
case 'f': //--finish
{
// cout<<"(main):received option --finish"<<endl;
uniset_init(argc,argv,conffile);
UniversalInterface ui(conf);
Command cmd=Finish;
ObjectRepository* rep = new ObjectRepository(conf);
commandToAll(conf->getServicesSection(), rep, (Command)cmd);
commandToAll(conf->getControllersSection(), rep, (Command)cmd);
commandToAll(conf->getObjectsSection(), rep, (Command)cmd);
delete rep;
cout<<"(finish): done"<<endl;
}
return 0;
case 'l': //--logrotate
{
uniset_init(argc,argv,conffile);
UniversalInterface ui(conf);
return logRotate(optarg, ui);
}
break;
case 'y': //--getCalibrate
{
// cout<<"(main):received option --getCalibrate='"<<optarg<<"'"<<endl;
uniset_init(argc,argv,conffile);
UniversalInterface ui(conf);
return getCalibrate(optarg, ui);
}
break;
case 'u': //--foldUp
{
// cout<<"(main):received option --foldUp"<<endl;
uniset_init(argc,argv,conffile);
UniversalInterface ui(conf);
Command cmd=FoldUp;
ObjectRepository* rep = new ObjectRepository(conf);
commandToAll(conf->getServicesSection(), rep, (Command)cmd);
commandToAll(conf->getControllersSection(), rep, (Command)cmd);
commandToAll(conf->getObjectsSection(), rep, (Command)cmd);
delete rep;
// cout<<"(foldUp): done"<<endl;
}
return 0;
case '?':
default:
{
short_usage();
return 1;
}
}
}
return 0;
}
catch(Exception& ex)
{
if( verb )
cout <<"admin(main): " << ex << endl;
}
catch(CORBA::SystemException& ex)
{
if( verb )
cerr << "поймали CORBA::SystemException:" << ex.NP_minorString() << endl;
}
catch(CORBA::Exception&)
{
if( verb )
cerr << "поймали CORBA::Exception." << endl;
}
catch(omniORB::fatalException& fe)
{
if( verb )
{
cerr << "поймали omniORB::fatalException:" << endl;
cerr << " file: " << fe.file() << endl;
cerr << " line: " << fe.line() << endl;
cerr << " mesg: " << fe.errmsg() << endl;
}
}
catch(...)
{
if( verb )
cerr << "неизвестное исключение" << endl;
}
return 1;
}
// ==============================================================================================
static bool commandToAll(const string& section, ObjectRepository *rep, Command cmd)
{
if( verb )
cout <<"\n||=======******** " << section << " ********=========||\n"<< endl;
try
{
ListObjectName ls;
rep->list(section.c_str(),&ls);
if( ls.empty() )
{
if( verb )
cout << "пусто!!!!!!" << endl;
return false;
}
ObjectsManager_i_var proc;
UniSetObject_i_var obj;
string fullName;
ListObjectName::const_iterator li;
string buf;
cout.setf(ios::left, ios::adjustfield);
for ( li=ls.begin();li!=ls.end();++li)
{
string ob(*li);
buf = section+"/"+ob;
fullName= buf.c_str();
try
{
UniSetTypes::ObjectVar o =rep->resolve(fullName);
obj= UniSetObject_i::_narrow(o);
switch( cmd )
{
case StartUp:
{
if(CORBA::is_nil(obj)) break;
SystemMessage msg(SystemMessage::StartUp);
obj->push( Message::transport(msg) );
if( verb )
cout << setw(55) << ob <<" <--- start OK" << endl;
}
break;
case FoldUp:
{
if(CORBA::is_nil(obj)) break;
SystemMessage msg(SystemMessage::FoldUp);
obj->push( Message::transport(msg) );
if( verb )
cout << setw(55) << ob << " <--- foldUp OK" << endl;
}
break;
case Finish:
{
if(CORBA::is_nil(obj)) break;
SystemMessage msg(SystemMessage::Finish);
obj->push( Message::transport(msg) );
if( verb )
cout << setw(55)<< ob << " <--- finish OK" << endl;
}
break;
case Exist:
{
if (obj->exist())
{
if( verb )
cout << setw(55) << ob << " <--- exist ok\n";
}
else if( verb )
cout << setw(55) << ob << " <--- exist NOT OK\n";
}
break;
case Configure:
{
SystemMessage sm(SystemMessage::ReConfiguration);
obj->push(sm.transport_msg());
if( verb )
cout << setw(55) << ob << " <--- configure ok\n";
}
break;
case LogRotate:
{
SystemMessage msg(SystemMessage::LogRotate);
obj->push( Message::transport(msg) );
if( verb )
cout << setw(55) << ob << " <--- logrotate ok\n";
break;
}
default:
{
if( verb )
cout << "неизвестная команда -" << cmd << endl;
return false;
}
}
}
catch(Exception& ex)
{
if( verb )
cout << setw(55) << ob << " <--- " << ex << endl;
}
catch( CORBA::SystemException& ex )
{
if( verb )
cout << setw(55) << ob << " <--- недоступен!!(CORBA::SystemException): " << ex.NP_minorString() << endl;
}
}
}
catch( ORepFailed )
{
return false;
}
return true;
}
// ==============================================================================================
static void createSections( UniSetTypes::Configuration* rconf )
{
ObjectRepositoryFactory repf(rconf);
repf.createRootSection(rconf->getRootSection());
repf.createRootSection(rconf->getSensorsSection());
repf.createRootSection(rconf->getObjectsSection());
repf.createRootSection(rconf->getControllersSection());
repf.createRootSection(rconf->getServicesSection());
if( verb )
cout<<"(create): created"<<endl;
}
// ==============================================================================================
int omap()
{
try
{
cout.setf(ios::left, ios::adjustfield);
cout << "========================== ObjectsMap =================================\n";
conf->oind->printMap(cout);
cout << "==========================================================================\n";
}
catch(Exception& ex)
{
if( verb )
unideb[Debug::CRIT] << " configuration init FAILED!!! \n";
return 1;
}
return 0;
}
// --------------------------------------------------------------------------------------
int msgmap()
{
try
{
cout.setf(ios::left, ios::adjustfield);
cout << "========================== MessagesMap =================================\n";
conf->mi->printMessagesMap(cout);
cout << "==========================================================================\n";
}
catch(Exception& ex)
{
if( verb )
unideb[Debug::CRIT] << " configuration init FAILED!!! " << ex << endl;;
return 1;
}
return 0;
}
// --------------------------------------------------------------------------------------
int setValue( const string& args, UniversalInterface &ui, Configuration* conf )
{
int err = 0;
typedef std::list<UniSetTypes::ParamSInfo> SList;
SList sl = UniSetTypes::getSInfoList(args, conf);
if( verb )
cout << "====== setValue ======" << endl;
for( SList::iterator it=sl.begin(); it!=sl.end(); it++ )
{
try
{
UniversalIO::IOTypes t = conf->getIOType(it->si.id);
if( verb )
{
cout << " value: " << it->val << endl;
cout << " name: (" << it->si.id << ") " << it->fname << endl;
cout << " iotype: " << t << endl;
cout << " text: " << conf->oind->getTextName(it->si.id) << "\n\n";
}
if( it->si.node == DefaultObjectId )
it->si.node = conf->getLocalNode();
switch(t)
{
case UniversalIO::DigitalInput:
ui.saveState(it->si.id,(it->val?true:false),t,it->si.node);
break;
case UniversalIO::DigitalOutput:
ui.setState(it->si.id,(it->val?true:false),it->si.node);
break;
case UniversalIO::AnalogInput:
ui.saveValue(it->si.id,it->val,t,it->si.node);
break;
case UniversalIO::AnalogOutput:
ui.setValue(it->si.id,it->val,it->si.node);
break;
default:
if( verb )
cerr << "FAILED: Unknown 'iotype' for " << it->fname << endl;
err = 1;
break;
}
}
catch(Exception& ex)
{
if( verb )
cerr << "(setValue): " << ex << endl;;
err = 1;
}
}
return err;
}
// --------------------------------------------------------------------------------------
int getValue( const string& args, UniversalInterface &ui, Configuration* conf )
{
int err = 0;
typedef std::list<UniSetTypes::ParamSInfo> SList;
SList sl = UniSetTypes::getSInfoList( args, UniSetTypes::conf );
if( verb )
cout << "====== getValue ======" << endl;
for( SList::iterator it=sl.begin(); it!=sl.end(); it++ )
{
try
{
UniversalIO::IOTypes t = conf->getIOType(it->si.id);
if( verb )
{
cout << " name: (" << it->si.id << ") " << it->fname << endl;
cout << " iotype: " << t << endl;
cout << " text: " << conf->oind->getTextName(it->si.id) << "\n\n";
}
if( it->si.node == DefaultObjectId )
it->si.node = conf->getLocalNode();
switch(t)
{
case UniversalIO::DigitalOutput:
case UniversalIO::DigitalInput:
if( verb )
cout << " state: " << ui.getState(it->si.id,it->si.node) << endl;
else
cout << ui.getState(it->si.id,it->si.node);
break;
case UniversalIO::AnalogOutput:
case UniversalIO::AnalogInput:
if( verb )
cout << " value: " << ui.getValue(it->si.id,it->si.node) << endl;
else
cout << ui.getValue(it->si.id,it->si.node);
break;
default:
if( verb )
cerr << "FAILED: Unknown 'iotype' for " << it->fname << endl;
err = 1;
break;
}
}
catch(Exception& ex)
{
if( verb )
cerr << "(getValue): " << ex << endl;
err = 1;
}
}
return err;
}
// --------------------------------------------------------------------------------------
int getCalibrate( const std::string& args, UniversalInterface &ui )
{
int err = 0;
typedef std::list<UniSetTypes::ParamSInfo> SList;
SList sl = UniSetTypes::getSInfoList( args, UniSetTypes::conf );
if( verb )
cout << "====== getCalibrate ======" << endl;
for( SList::iterator it=sl.begin(); it!=sl.end(); it++ )
{
if( it->si.node == DefaultObjectId )
it->si.node = conf->getLocalNode();
cout << " name: (" << it->si.id << ") " << it->fname << endl;
cout << " text: " << conf->oind->getTextName(it->si.id) << "\n";
try
{
cout << "калибровка: ";
IOController_i::CalibrateInfo ci = ui.getCalibrateInfo(it->si);
cout << ci << endl;
}
catch(Exception& ex)
{
cerr << "(getCalibrate): " << ex << endl;;
err = 1;
}
}
return err;
}
// --------------------------------------------------------------------------------------
int getRawValue( const std::string& args, UniversalInterface &ui )
{
int err = 0;
typedef std::list<UniSetTypes::ParamSInfo> SList;
SList sl = UniSetTypes::getSInfoList( args, UniSetTypes::conf );
if( verb )
cout << "====== getRawValue ======" << endl;
for( SList::iterator it=sl.begin(); it!=sl.end(); it++ )
{
if( it->si.node == DefaultObjectId )
it->si.node = conf->getLocalNode();
if( verb )
{
cout << " name: (" << it->si.id << ") " << it->fname << endl;
cout << " text: " << conf->oind->getTextName(it->si.id) << "\n\n";
}
try
{
if( verb )
cout << " value: " << ui.getRawValue(it->si) << endl;
else
cout << " value: " << ui.getRawValue(it->si);
}
catch(Exception& ex)
{
if( verb )
cerr << "(getRawValue): " << ex << endl;;
err = 1;
}
}
return err;
}
// --------------------------------------------------------------------------------------
int logRotate( const string& arg, UniversalInterface &ui )
{
// посылка всем
if( arg.empty() || (arg.c_str())[0]!='-' )
{
ObjectRepository* rep = new ObjectRepository(conf);
commandToAll(conf->getServicesSection(), rep, (Command)LogRotate);
commandToAll(conf->getControllersSection(), rep, (Command)LogRotate);
commandToAll(conf->getObjectsSection(), rep, (Command)LogRotate);
delete rep;
}
else // посылка определённому объекту
{
UniSetTypes::ObjectId id = conf->oind->getIdByName(arg);
if( id == DefaultObjectId )
{
if( verb )
cout << "(logrotate): name='" << arg << "' не найдено!!!\n";
return 1;
}
SystemMessage sm(SystemMessage::LogRotate);
TransportMessage tm(sm.transport_msg());
ui.send(id,tm);
if( verb )
cout << "\nSend 'LogRotate' to " << arg << " OK.\n";
}
return 0;
}
// --------------------------------------------------------------------------------------
int configure( const string& arg, UniversalInterface &ui )
{
// посылка всем
if( arg.empty() || (arg.c_str())[0]!='-' )
{
ObjectRepository* rep = new ObjectRepository(conf);
commandToAll(conf->getServicesSection(), rep, (Command)Configure);
commandToAll(conf->getControllersSection(), rep, (Command)Configure);
commandToAll(conf->getObjectsSection(), rep, (Command)Configure);
delete rep;
}
else // посылка определённому объекту
{
UniSetTypes::ObjectId id = conf->oind->getIdByName(arg);
if( id == DefaultObjectId )
{
if( verb )
cout << "(configure): name='" << arg << "' не найдено!!!\n";
return 1;
}
SystemMessage sm(SystemMessage::ReConfiguration);
TransportMessage tm(sm.transport_msg());
ui.send(id,tm);
if( verb )
cout << "\nSend 'ReConfigure' to " << arg << " OK.\n";
}
return 0;
}
// --------------------------------------------------------------------------------------
int oinfo( const string& arg, UniversalInterface &ui )
{
UniSetTypes::ObjectId oid(uni_atoi(arg));
if( oid==0 )
{
if( verb )
cout << "(oinfo): Не задан OID!"<< endl;
return 1;
}
UniSetTypes::ObjectVar o = ui.resolve(oid);
UniSetObject_i_var obj = UniSetObject_i::_narrow(o);
if(CORBA::is_nil(obj))
{
if( verb )
cout << "(oinfo): объект " << oid << " недоступен" << endl;
}
else
{
SimpleInfo_var inf = obj->getInfo();
cout << inf->info << endl;
}
return 0;
}
// --------------------------------------------------------------------------------------
| vitlav/libuniset | Utilities/Admin/admin.cc | C++ | gpl-2.0 | 23,256 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.tomcat.util.bcel.classfile;
import java.io.DataInput;
import java.io.IOException;
import org.apache.tomcat.util.bcel.Constants;
/**
* This class is derived from the abstract
* <A HREF="org.apache.tomcat.util.bcel.classfile.Constant.html">Constant</A> class
* and represents a reference to a Double object.
*
* @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A>
* @see Constant
*/
public final class ConstantDouble extends Constant {
private static final long serialVersionUID = 3450743772468544760L;
private double bytes;
/**
* @param bytes Data
*/
public ConstantDouble(double bytes) {
super(Constants.CONSTANT_Double);
this.bytes = bytes;
}
/**
* Initialize instance from file data.
*
* @param file Input stream
* @throws IOException
*/
ConstantDouble(DataInput file) throws IOException {
this(file.readDouble());
}
/**
* @return data, i.e., 8 bytes.
*/
public final double getBytes() {
return bytes;
}
/**
* @return String representation.
*/
@Override
public final String toString() {
return super.toString() + "(bytes = " + bytes + ")";
}
}
| deathspeeder/class-guard | apache-tomcat-7.0.53-src/java/org/apache/tomcat/util/bcel/classfile/ConstantDouble.java | Java | gpl-2.0 | 2,065 |
<?php
/**
*
* @package InfinityCoreCMS
* @version $Id$
* @copyright (c) 2008 InfinityCoreCMS
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/**
*
* @Extra credits for this file
* Vjacheslav Trushkin (http://www.stsoftware.biz)
*
*/
define('IN_INFINITYCORECMS', true);
if (!defined('IP_ROOT_PATH')) define('IP_ROOT_PATH', './../');
if (!defined('PHP_EXT')) define('PHP_EXT', substr(strrchr(__FILE__, '.'), 1));
$no_page_header = true;
require('pagestart.' . PHP_EXT);
// Mighty Gorgon - ACP Privacy - BEGIN
$is_allowed = check_acp_module_access();
if (empty($is_allowed))
{
message_die(GENERAL_MESSAGE, $lang['Not_Auth_View']);
}
// Mighty Gorgon - ACP Privacy - END
define('IN_XS', true);
include_once('xs_include.' . PHP_EXT);
// check filter
$filter = isset($_GET['filter']) ? stripslashes($_GET['filter']) : (isset($_POST['filter']) ? stripslashes($_POST['filter']) : '');
if(isset($_POST['filter_update']))
{
$filter_data = array(
'ext' => trim(stripslashes($_POST['filter_ext'])),
'data' => trim(stripslashes($_POST['filter_data']))
);
$filter = serialize($filter_data);
}
else
{
$filter_data = @unserialize($filter);
if(empty($filter_data['ext']))
{
$filter_data['ext'] = '';
}
if(empty($filter_data['data']))
{
$filter_data['data'] = '';
}
}
$filter_str = '?filter=' . urlencode($filter);
$template->assign_block_vars('nav_left',array('ITEM' => '» <a href="' . append_sid('xs_edit.' . PHP_EXT.$filter_str) . '">' . $lang['xs_edit_templates'] . '</a>'));
$editable = array('.htm', '.html', '.tpl', '.css', '.txt', '.cfg', '.xml', '.php', '.htaccess');
// get current directory
$current_dir = isset($_GET['dir']) ? stripslashes($_GET['dir']) : (isset($_POST['dir']) ? stripslashes($_POST['dir']) : 'templates');
$current_dir = xs_fix_dir($current_dir);
if(defined('DEMO_MODE') && substr($current_dir, 0, 9) !== 'templates')
{ // limit access to "templates" in demo mode
$current_dir = 'templates';
}
$dirs = explode('/', $current_dir);
for($i = 0; $i < sizeof($dirs); $i++)
{
if(!$dirs[$i] || $dirs[$i] === '.')
{
unset($dirs[$i]);
}
}
$current_dir = implode('/', $dirs);
$current_dir_full = $current_dir; //'templates' . ($current_dir ? '/' . $current_dir : '');
$current_dir_root = $current_dir ? $current_dir . '/' : '';
$return_dir = str_replace('{URL}', append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir=' . urlencode($current_dir)), $lang['xs_edittpl_back_dir']);
$return_url = $return_dir;
$return_url_root = str_replace('{URL}', append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir='), $lang['xs_edittpl_back_dir']);
$template->assign_vars(array(
'FILTER_EXT' => htmlspecialchars($filter_data['ext']),
'FILTER_DATA' => htmlspecialchars($filter_data['data']),
'FILTER_URL' => append_sid('xs_edit.' . PHP_EXT),
'FILTER_DIR' => htmlspecialchars($current_dir),
'S_FILTER' => '<input type="hidden" name="filter" value="' . htmlspecialchars($filter) . '" />'
)
);
/*
* show edit form
*/
if(isset($_GET['edit']) && !empty($_GET['restore']))
{
$file = stripslashes($_GET['edit']);
$file = xs_fix_dir($file);
$fullfile = $current_dir_root . $file;
$localfile = '../' . $fullfile;
$hash = md5($localfile);
$backup_name = XS_TEMP_DIR . XS_BACKUP_PREFIX . $hash . '.' . intval($_GET['restore']) . XS_BACKUP_EXT;
if(@file_exists($backup_name))
{
// restore file
$_POST['edit'] = $_GET['edit'];
$_POST['content'] = addslashes(implode('', @file($backup_name)));
unset($_GET['edit']);
$return_file = str_replace('{URL}', append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir=' . urlencode($current_dir) . '&edit=' . urlencode($file)), $lang['xs_edittpl_back_edit']);
$return_url = $return_file . '<br /><br />' . $return_dir;
}
}
/*
* save modified file
*/
if(isset($_POST['edit']) && !defined('DEMO_MODE'))
{
$file = stripslashes($_POST['edit']);
$content = stripslashes($_POST['content']);
$fullfile = $current_dir_root . $file;
$localfile = '../' . $fullfile;
if(!empty($_POST['trim']))
{
$content = trim($content);
}
if(!empty($_FILES['upload']['tmp_name']) && @file_exists($_FILES['upload']['tmp_name']))
{
$content = @implode('', @file($_FILES['upload']['tmp_name']));
}
$params = array(
'edit' => $file,
'dir' => $current_dir,
'content' => $content,
'filter' => $filter,
);
$return_file = str_replace('{URL}', append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir=' . urlencode($current_dir) . '&edit=' . urlencode($file)), $lang['xs_edittpl_back_edit']);
$return_url = $return_file . '<br /><br />' . $return_dir;
// get ftp configuration
$write_local = false;
if(!get_ftp_config(append_sid('xs_edit.' . PHP_EXT), $params, true))
{
xs_exit();
}
xs_ftp_connect(append_sid('xs_edit.' . PHP_EXT), $params, true);
if($ftp === XS_FTP_LOCAL)
{
$write_local = true;
$local_filename = $localfile;
}
else
{
$local_filename = XS_TEMP_DIR . 'edit_' . time() . '.tmp';
}
$f = @fopen($local_filename, 'wb');
if(!$f)
{
xs_error($lang['xs_error_cannot_open'] . '<br /><br />' . $return_url);
}
fwrite($f, $content);
fclose($f);
if($write_local)
{
xs_message($lang['Information'], $lang['xs_edit_file_saved'] . '<br /><br />' . $return_url);
}
// generate ftp actions
$actions = array();
// chdir to template directory
for($i = 0; $i < sizeof($dirs); $i++)
{
$actions[] = array(
'command' => 'chdir',
'dir' => $dirs[$i]
);
}
$actions[] = array(
'command' => 'upload',
'local' => $local_filename,
'remote' => $fullfile
);
$ftp_log = array();
$ftp_error = '';
$res = ftp_myexec($actions);
echo "<!--\n\n";
echo "\$actions dump:\n\n";
print_r($actions);
echo "\n\n\$ftp_log dump:\n\n";
print_r($ftp_log);
echo "\n\n -->";
@unlink($local_filename);
if($res)
{
xs_message($lang['Information'], $lang['xs_edit_file_saved'] . '<br /><br />' . $return_url);
}
xs_error($ftp_error . '<br /><br />' . $return_url);
}
/*
* show edit form
*/
if(isset($_GET['edit']))
{
$file = stripslashes($_GET['edit']);
$file = xs_fix_dir($file);
$fullfile = $current_dir_root . $file;
$localfile = '../' . $fullfile;
$hash = md5($localfile);
if(!@file_exists($localfile))
{
xs_error($lang['xs_edit_not_found'] . '<br /><br />' . $return_url);
}
$content = @file($localfile);
if(!is_array($content))
{
xs_error($lang['xs_edit_not_found'] . '<br /><br />' . $return_url);
}
$content = implode('', $content);
if(isset($_GET['download']) && !defined('DEMO_MODE'))
{
xs_download_file($file, $content);
xs_exit();
}
if(isset($_GET['downloadbackup']) && !defined('DEMO_MODE'))
{
$backup_name = XS_TEMP_DIR . XS_BACKUP_PREFIX . $hash . '.' . intval($_GET['downloadbackup']) . XS_BACKUP_EXT;
xs_download_file($file, implode('', @file($backup_name)));
xs_exit();
}
$return_file = str_replace('{URL}', append_sid('xs_edit.' . PHP_EXT.$filter_str.'&dir=' . urlencode($current_dir).'&edit='.urlencode($file)), $lang['xs_edittpl_back_edit']);
$return_url = $return_file . '<br /><br />' . $return_dir;
$template->assign_vars(array(
'U_ACTION' => append_sid('xs_edit.' . PHP_EXT),
'U_BROWSE' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir=' . urlencode($current_dir)),
'U_EDIT' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir=' . urlencode($current_dir) . '&edit=' . urlencode($file)),
'U_BACKUP' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dobackup=1&dir='.urlencode($current_dir) . '&edit=' . urlencode($file)),
'U_DOWNLOAD' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&download=1&dir='.urlencode($current_dir) . '&edit=' . urlencode($file)),
'CURRENT_DIR' => htmlspecialchars($current_dir_full),
'DIR' => htmlspecialchars($current_dir),
'FILE' => htmlspecialchars($file),
'FULLFILE' => htmlspecialchars($fullfile),
'CONTENT' => defined('DEMO_MODE') ? $lang['xs_error_demo_edit'] : htmlspecialchars($content),
)
);
if($current_dir_full)
{
$template->assign_block_vars('nav_left',array('ITEM' => '» <a href="' . append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir='.$current_dir) . '">' . htmlspecialchars($current_dir_full) . '</a>'));
}
// show tree
$arr = array();
$template->assign_block_vars('tree', array(
'ITEM' => 'InfinityCoreCMS',
'URL' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir='),
'SEPARATOR' => '',
));
$back_dir = '';
for($i = 0; $i < sizeof($dirs); $i++)
{
$arr[] = $dirs[$i];
$str = implode('/', $arr);
if(sizeof($dirs) > ($i + 1))
{
$back_dir = $str;
}
$template->assign_block_vars('tree', array(
'ITEM' => htmlspecialchars($dirs[$i]),
'URL' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir=' . urlencode($str)),
'SEPARATOR' => '/',
));
}
// view backup
if(!empty($_GET['viewbackup']) && !defined('DEMO_MODE'))
{
$backup_name = XS_TEMP_DIR . XS_BACKUP_PREFIX . $hash . '.' . intval($_GET['viewbackup']) . XS_BACKUP_EXT;
$template->assign_vars(array(
'CONTENT' => implode('', @file($backup_name))
)
);
}
// save backup
if(isset($_GET['dobackup']) && !defined('DEMO_MODE'))
{
$backup_name = XS_TEMP_DIR . XS_BACKUP_PREFIX . $hash . '.' . time() . XS_BACKUP_EXT;
$f = @fopen($backup_name, 'wb');
if(!$f)
{
xs_error(str_replace('{FILE}', $backup_name, $lang['xs_error_cannot_create_tmp']) . '<br /><br />' . $return_url);
}
fwrite($f, $content);
fclose($f);
@chmod($backup_name, 0777);
}
// delete backup
if(isset($_GET['delbackup']) && !defined('DEMO_MODE'))
{
$backup_name = XS_TEMP_DIR . XS_BACKUP_PREFIX . $hash . '.' . intval($_GET['delbackup']) . XS_BACKUP_EXT;
@unlink($backup_name);
}
// show backups
$backups = array();
$res = opendir(XS_TEMP_DIR);
$match = XS_BACKUP_PREFIX . $hash . '.';
$match_len = strlen($match);
while(($f = readdir($res)) !== false)
{
if(substr($f, 0, $match_len) === $match)
{
$str = substr($f, $match_len, strlen($f) - $match_len - strlen(XS_BACKUP_EXT));
if(intval($str))
{
$backups[] = intval($str);
}
}
}
closedir($res);
sort($backups);
for($i = 0; $i < sizeof($backups); $i++)
{
$template->assign_block_vars('backup', array(
'TIME' => create_date($config['default_dateformat'], $backups[$i], $config['board_timezone']),
'U_RESTORE' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir=' . urlencode($current_dir) . '&edit=' . urlencode($file) . '&restore=' . $backups[$i]),
'U_DELETE' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir=' . urlencode($current_dir) . '&edit=' . urlencode($file) . '&delbackup=' . $backups[$i]),
'U_DOWNLOAD' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir=' . urlencode($current_dir) . '&edit=' . urlencode($file) . '&downloadbackup=' . $backups[$i]),
'U_VIEW' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir=' . urlencode($current_dir) . '&edit=' . urlencode($file) . '&viewbackup=' . $backups[$i]),
)
);
}
// show template
$template->set_filenames(array('body' => XS_TPL_PATH . 'edit_file.tpl'));
$template->pparse('body');
xs_exit();
}
/*
* show file browser
*/
// show tree
$arr = array();
$template->assign_block_vars('tree', array(
'ITEM' => 'InfinityCoreCMS',
'URL' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir='),
'SEPARATOR' => '',
));
$back_dir = '';
for($i = 0; $i < sizeof($dirs); $i++)
{
$arr[] = $dirs[$i];
$str = implode('/', $arr);
if(sizeof($dirs) > ($i + 1))
{
$back_dir = $str;
}
$template->assign_block_vars('tree', array(
'ITEM' => htmlspecialchars($dirs[$i]),
'URL' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir=' . urlencode($str)),
'SEPARATOR' => '/',
)
);
}
// get list of files/directories
$list_files = array(); // non-editable files
$list_files_editable = array(); // editable files
$list_dirs = array(); // directories
$res = @opendir('../' . $current_dir_full);
if(!$res)
{
xs_error(str_replace('{DIR}', $current_dir_full, $lang['xs_export_no_open_dir']) . '<br /><br />' . $return_url_root);
}
while(($file = readdir($res)) !== false)
{
if($file !== '.' && $file !== '..')
{
$filename = '../' . ($current_dir_full ? $current_dir_full . '/' : '') . $file;
if(is_dir($filename))
{
$list_dirs[] = $file;
}
else
{
$pos = strrpos($file, '.');
if($pos !== false)
{
$ext = strtolower(substr($file, $pos));
$ext1 = substr($ext, 1);
if((!$filter_data['ext'] && xs_in_array($ext, $editable)) || $ext1 === $filter_data['ext'])
{
// check filter
if($filter_data['data'])
{
$content = @implode('', @file($filename));
if(strpos($content, $filter_data['data']) !== false)
{
$list_files_editable[] = $file;
}
}
else
{
$list_files_editable[] = $file;
}
}
else
{
$list_files[] = $file;
}
}
}
}
}
closedir($res);
$list_dirs_count = sizeof($list_dirs);
$list_files_count = sizeof($list_files) + sizeof($list_files_editable);
if($current_dir || sizeof($list_dirs))
{
$template->assign_block_vars('begin_dirs', array(
'COUNT' => sizeof($list_dirs),
'L_COUNT' => str_replace('{COUNT}', sizeof($list_dirs), $lang['xs_fileman_dircount'])
));
}
else
{
$template->assign_block_vars('begin_nodirs', array());
}
if($current_dir)
{
$template->assign_block_vars('begin_dirs.dir', array(
'NAME' => '..',
'FULLNAME' => htmlspecialchars($back_dir ? $back_dir . '/' : ''),
'URL' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir=' . urlencode($back_dir)),
)
);
}
// show subdirectories
sort($list_dirs);
for($i = 0; $i < sizeof($list_dirs); $i++)
{
$dir = $list_dirs[$i];
$str = $current_dir_root . $dir;
$template->assign_block_vars('begin_dirs.dir', array(
'NAME' => htmlspecialchars($dir),
'FULLNAME' => htmlspecialchars($current_dir_root . $dir),
'URL' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir=' . urlencode($str)),
)
);
}
// show editable files
if(sizeof($list_files_editable))
{
$template->assign_block_vars('begin_files', array('COUNT' => sizeof($list_files_editable)));
}
else
{
$template->assign_block_vars('begin_nofiles', array('COUNT' => sizeof($list_files_editable)));
}
sort($list_files_editable);
// get today start
$today = floor((time() + 3600 * $config['board_timezone']) / 86400) * 86400 - (3600 * $config['board_timezone']);
for($i = 0; $i < sizeof($list_files_editable); $i++)
{
$file = $list_files_editable[$i];
$fullfile = $current_dir_root . $file;
$localfile = '../' . $fullfile;
$row_class = $xs_row_class[$i % 2];
$t = @filemtime($localfile);
$filetime = $t ? create_date($config['default_dateformat'], $t, $config['board_timezone']) : ' ';
$template->assign_block_vars('begin_files.file', array(
'ROW_CLASS' => $row_class,
'NAME' => htmlspecialchars($file),
'FULLNAME' => htmlspecialchars($fullfile),
'SIZE' => @filesize($localfile),
'TIME' => $filetime,
'URL' => append_sid('xs_edit.' . PHP_EXT . $filter_str . '&dir=' . urlencode($current_dir) . '&edit=' . urlencode($file))
)
);
if($t < $today)
{
$template->assign_block_vars('begin_files.file.old', array());
}
else
{
$template->assign_block_vars('begin_files.file.today', array());
}
}
$template->set_filenames(array('body' => XS_TPL_PATH . 'edit.tpl'));
$template->pparse('body');
xs_exit();
?> | LordPsyan/InfinityCoreCMS | adm/xs_edit.php | PHP | gpl-2.0 | 15,350 |
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla view library
jimport('joomla.application.component.view');
jimport('joomla.application.component.controller');
/**
* HTML View class for the HelloWorld Component
*/
class HoroscopeViewNavamsha extends JViewLegacy
{
public $data;
function display($tpl = null)
{
$this->data = $this->get('Data');
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
if(isset($_GET['chart']) && (empty($this->data)))
{
$app = JFactory::getApplication();
$link = Juri::base().'horoscope?chart='.$_GET['chart'];
$app->redirect($link);
}
else
{
$tpl = null;
parent::display($tpl);
}
}
}
| luffy22/aisha | components/com_horoscope/views/navamsha/view.html.php | PHP | gpl-2.0 | 967 |
<?php
/**
* @package Joomla.Libraries
* @subpackage Form
*
* @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
JFormHelper::loadFieldClass('groupedlist');
$app=JFactory::getApplication();
$client=$app->getClientId();
if($client==0){
require_once realpath(JPATH_SITE. '/components/com_menus/helpers/menus.php');
}else {
// Import the com_menus helper.
require_once realpath(JPATH_ADMINISTRATOR . '/components/com_menus/helpers/menus.php');
}
/**
* Supports an HTML grouped select list of menu item grouped by menu
*
* @since 1.6
*/
class JFormFieldMenuitem extends JFormFieldGroupedList
{
/**
* The form field type.
*
* @var string
* @since 1.6
*/
public $type = 'MenuItem';
/**
* The menu type.
*
* @var string
* @since 3.2
*/
protected $menuType;
/**
* The language.
*
* @var array
* @since 3.2
*/
protected $language;
/**
* The published status.
*
* @var array
* @since 3.2
*/
protected $published;
/**
* The disabled status.
*
* @var array
* @since 3.2
*/
protected $disable;
/**
* Method to get certain otherwise inaccessible properties from the form field object.
*
* @param string $name The property name for which to the the value.
*
* @return mixed The property value or null.
*
* @since 3.2
*/
public function __get($name)
{
switch ($name)
{
case 'menuType':
case 'language':
case 'published':
case 'disable':
return $this->$name;
}
return parent::__get($name);
}
/**
* Method to set certain otherwise inaccessible properties of the form field object.
*
* @param string $name The property name for which to the the value.
* @param mixed $value The value of the property.
*
* @return void
*
* @since 3.2
*/
public function __set($name, $value)
{
switch ($name)
{
case 'menuType':
$this->menuType = (string) $value;
break;
case 'language':
case 'published':
case 'disable':
$value = (string) $value;
$this->$name = $value ? explode(',', $value) : array();
break;
default:
parent::__set($name, $value);
}
}
/**
* Method to attach a JForm object to the field.
*
* @param SimpleXMLElement $element The SimpleXMLElement object representing the `<field>` tag for the form field object.
* @param mixed $value The form field value to validate.
* @param string $group The field name group control value. This acts as as an array container for the field.
* For example if the field has name="foo" and the group value is set to "bar" then the
* full field name would end up being "bar[foo]".
*
* @return boolean True on success.
*
* @see JFormField::setup()
* @since 3.2
*/
public function setup(SimpleXMLElement $element, $value, $group = null)
{
$result = parent::setup($element, $value, $group);
if ($result == true)
{
$this->menuType = (string) $this->element['menu_type'];
$this->published = $this->element['published'] ? explode(',', (string) $this->element['published']) : array();
$this->disable = $this->element['disable'] ? explode(',', (string) $this->element['disable']) : array();
$this->language = $this->element['language'] ? explode(',', (string) $this->element['language']) : array();
$this->disableChosen = $this->element['disableChosen'] ? true:false;
}
return $result;
}
/**
* Method to get the field option groups.
*
* @return array The field option objects as a nested array in groups.
*
* @since 1.6
*/
protected function getGroups()
{
$groups = array();
$menuType = $this->menuType;
// Get the menu items.
$items = MenusHelper::getMenuLinks($menuType, 0, 0, $this->published, $this->language);
// Build group for a specific menu type.
if ($menuType)
{
// If the menutype is empty, group the items by menutype.
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('title'))
->from($db->quoteName('#__menu_types'))
->where($db->quoteName('menutype') . ' = ' . $db->quote($menuType));
$db->setQuery($query);
try
{
$menuTitle = $db->loadResult();
}
catch (RuntimeException $e)
{
$menuTitle = $menuType;
}
// Initialize the group.
$groups[$menuTitle] = array();
// Build the options array.
foreach ($items as $link)
{
$levelPrefix = str_repeat('- ', max(0, $link->level - 1));
// Displays language code if not set to All
if ($link->language !== '*')
{
$lang = ' (' . $link->language . ')';
}
else
{
$lang = '';
}
$groups[$menuTitle][] = JHtml::_('select.option',
$link->value, $levelPrefix . $link->text . $lang,
'value',
'text',
in_array($link->type, $this->disable)
);
}
}
// Build groups for all menu types.
else
{
// Build the groups arrays.
foreach ($items as $menu)
{
// Initialize the group.
$groups[$menu->title] = array();
// Build the options array.
foreach ($menu->links as $link)
{
$levelPrefix = str_repeat('- ', $link->level - 1);
// Displays language code if not set to All
if ($link->language !== '*')
{
$lang = ' (' . $link->language . ')';
}
else
{
$lang = '';
}
$groups[$menu->title][] = JHtml::_('select.option',
$link->value, $levelPrefix . $link->text . $lang,
'value',
'text',
in_array($link->type, $this->disable)
);
}
}
}
// Merge any additional groups in the XML definition.
$groups = array_merge(parent::getGroups(), $groups);
return $groups;
}
}
| cuongnd/banhangonline88_joomla | libraries/cms/form/field/menuitem.php | PHP | gpl-2.0 | 5,948 |
////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 RWS Inc, All Rights Reserved
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of version 2 of the GNU General Public License as published by
// the Free Software Foundation
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
//////////////////////////////////////////////////////////////////////////////
//
// MultiBtn.cpp
//
// History:
// 04/10/97 JMI Started this using RPushBtn as a template.
//
// 04/17/97 JMI Added Load and Save components.
//
// 04/22/97 JMI Added NextState().
// CursorEvent() now uses NextState().
// Also, DrawBackgroundRes() now chooses the image indexed
// by m_sState instead of m_sState + 1.
//
// 09/25/97 JMI ReadMembers() was not clearing states that had no
// corresponding images which, since SetNumStates()
// preserves existing state images, could result in old
// images persisting through loads that contained no image
// for that state.
// Also, now, in file version 7, reads and writes the
// current state.
//
//////////////////////////////////////////////////////////////////////////////
//
// This a GUI item that is based on RBtn.
// This overrides CursorEvent() to get information about where a click in its
// RHot occurred.
// This overrides Compose() to add text.
//
// Enhancements/Uses:
// To change the look of a button when pressed, you may want to override the
// Compose() or DrawBorder() in a derived class.
// To get a callback on a click/release pair in the button, set m_bcUser.
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Headers.
//////////////////////////////////////////////////////////////////////////////
#include "Blue.h"
#ifdef PATHS_IN_INCLUDES
#include "ORANGE/GUI/MultiBtn.h"
#else
#include "multibtn.h"
#endif // PATHS_IN_INCLUDES
//////////////////////////////////////////////////////////////////////////////
// Module specific macros.
//////////////////////////////////////////////////////////////////////////////
// Sets val to def if val is -1.
#define DEF(val, def) ((val == -1) ? def : val)
//////////////////////////////////////////////////////////////////////////////
// Module specific typedefs.
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Module specific (static) variables.
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Construction/Destruction.
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// Default constructor.
//
//////////////////////////////////////////////////////////////////////////////
RMultiBtn::RMultiBtn()
{
// Override RGuiItem's/RBtn's defaults.
m_type = MultiBtn; // Indicates type of GUI item.
// Initialize RMultiBtn members.
m_sState = 0; // The button's current state, 0..m_sNumStates - 1.
m_sNumStates = 0; // Number of button states.
m_papimStates = NULL; // Ptr to array of m_sNumStates ptrs to button
// state images.
}
//////////////////////////////////////////////////////////////////////////////
//
// Destructor.
//
//////////////////////////////////////////////////////////////////////////////
RMultiBtn::~RMultiBtn()
{
DestroyStates();
}
////////////////////////////////////////////////////////////////////////
// Methods.
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//
// Cursor event notification.
// Events in event area.
// (virtual).
//
////////////////////////////////////////////////////////////////////////
void RMultiBtn::CursorEvent( // Returns nothing.
RInputEvent* pie) // In: Most recent user input event.
// Out: pie->sUsed = TRUE, if used.
{
switch (pie->sEvent)
{
case RSP_MB0_DOUBLECLICK:
case RSP_MB0_RELEASED:
// If we were clicked in . . .
if (m_sPressed != FALSE)
{
// Do change of state right away so user callback gets the new
// value.
// If within event area . . .
if ( pie->sPosX >= m_sEventAreaX && pie->sPosX < m_sEventAreaX + m_sEventAreaW
&& pie->sPosY >= m_sEventAreaY && pie->sPosY < m_sEventAreaY + m_sEventAreaH)
{
// Change state.
NextState();
}
}
break;
}
// Call base.
RGuiItem::CursorEvent(pie);
switch (pie->sEvent)
{
case RSP_MB0_DOUBLECLICK:
case RSP_MB0_PRESSED:
// Always recompose on press, since there's so many possibilities
// with this button.
Compose();
// Note that we used it.
pie->sUsed = TRUE;
break;
case RSP_MB0_RELEASED:
// Always recompose on release, since there's so many possibilities
// with this button.
Compose();
// Note that we used it.
pie->sUsed = TRUE;
break;
}
}
////////////////////////////////////////////////////////////////////////
// Draw background resource, if one is specified.
// Utilizes base class version to place and BLiT the resource.
// (virtual).
////////////////////////////////////////////////////////////////////////
void RMultiBtn::DrawBackgroundRes( // Returns nothing.
RImage* pim /*= NULL*/) // Dest image, uses m_im, if NULL.
{
// Store old bkd res.
RImage* pimBkdRes = m_pimBkdRes;
// If we have any states . . .
if (m_papimStates != NULL)
{
// Choose proper image.
if (m_sPressed == FALSE)
{
// If the state is available . . .
if (m_sState <= m_sNumStates)
{
// Get the state.
m_pimBkdRes = m_papimStates[m_sState];
}
}
else
{
// Get the pressed feedback.
m_pimBkdRes = m_papimStates[0];
}
}
// Call base.
RBtn::DrawBackgroundRes(pim);
// Restore bkd res.
m_pimBkdRes = pimBkdRes;
}
////////////////////////////////////////////////////////////////////////
// Set number of states.
// This will clear all existing state images.
////////////////////////////////////////////////////////////////////////
int16_t RMultiBtn::SetNumStates( // Returns 0 on success.
int16_t sNumStates) // In: New number of states.
{
int16_t sRes = 0; // Assume success.
// Allocate an array of image ptrs and clear them all . . .
RImage** papimNewStates = new RImage*[sNumStates + 1];
if (papimNewStates != NULL)
{
// Clear all the ptrs to NULL.
memset(papimNewStates, 0, sizeof(RImage*) * (sNumStates + 1));
// If there was an old array . . .
if (m_papimStates != NULL)
{
// Copy any currently valid ptrs within new range.
int16_t i;
for (i = 0; i <= sNumStates && i <= m_sNumStates; i++)
{
// Copy entry.
papimNewStates[i] = m_papimStates[i];
// Clear entry so it is not deleted.
m_papimStates[i] = NULL;
}
// Destroy any current states plus array.
DestroyStates();
}
// Store the new number of states.
m_sNumStates = sNumStates;
// Store new arrray.
m_papimStates = papimNewStates;
}
else
{
TRACE("SetNumStates(): Failed to allocate new array of Image ptrs.\n");
sRes = -1;
}
return sRes;
}
////////////////////////////////////////////////////////////////////////
// Set button state or feedback state image.
////////////////////////////////////////////////////////////////////////
int16_t RMultiBtn::SetState( // Returns 0 on success.
RImage* pim, // In: Image for state sState.
int16_t sState) // In: State to update (0 == feedback state,
// 1..n == state number).
{
int16_t sRes = 0; // Assume success.
if (m_papimStates == NULL || sState >= m_sNumStates)
{
sRes = SetNumStates(sState);
}
// If successful so far . . .
if (sRes == 0)
{
// Clear current value.
delete m_papimStates[sState];
// Allocate new one . . .
m_papimStates[sState] = new RImage;
if (m_papimStates[sState] != NULL)
{
// Copy specified image.
*(m_papimStates[sState]) = *pim;
}
else
{
TRACE("SetState(): Failed to allocate new RImage.\n");
sRes = -1;
}
}
return sRes;
}
//////////////////////////////////////////////////////////////////////////////
// Set button state or feedback state image.
// The feedback state image is always the last image (m_sNumStates).
//////////////////////////////////////////////////////////////////////////////
int16_t RMultiBtn::SetState( // Returns 0 on success.
char* pszImageName, // In: File name of image for state sState.
int16_t sState) // In: State to update (0 == feedback state,
// 1..n == state number).
{
int16_t sRes = 0; // Assume success.
RImage im;
if (RFileEZLoad(&im, pszImageName, "rb", RFile::LittleEndian) == 0)
{
sRes = SetState(&im, sState);
}
else
{
TRACE("SetState(): RFileEZLoad() failed for \"%s\".\n", pszImageName);
sRes = -1;
}
return sRes;
}
//////////////////////////////////////////////////////////////////////////////
// Clear button state or feedback state image.
// The feedback state image is always the first image.
//////////////////////////////////////////////////////////////////////////////
void RMultiBtn::ClearState( // Returns nothing.
int16_t sState) // In: State to clear (0 == feedback state,
// 1..n == state number).
{
if (sState >= 0 && sState <= m_sNumStates)
{
if (m_papimStates != NULL)
{
// State be gone. Safe for already deallocated states as long as
// they're NULL.
delete m_papimStates[sState];
m_papimStates[sState] = NULL;
}
}
}
//////////////////////////////////////////////////////////////////////////////
// Go to the next logical state.
//////////////////////////////////////////////////////////////////////////////
int16_t RMultiBtn::NextState(void) // Returns new state.
{
if (m_sNumStates > 0)
{
m_sState = (m_sState % m_sNumStates) + 1;
}
else
{
m_sState = 0;
}
return m_sState;
}
//////////////////////////////////////////////////////////////////////////////
// Querries.
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Get the current image for the specified state.
//////////////////////////////////////////////////////////////////////////////
RImage* RMultiBtn::GetState( // Returns image, if available; NULL, otherwise.
int16_t sState) // In: State to get (0 == feedback state,
// 1..n == state number).
{
RImage* pimRes = NULL; // Assume not available.
if (sState >= 0 && sState <= m_sNumStates)
{
if (m_papimStates != NULL)
{
pimRes = m_papimStates[sState];
}
}
return pimRes;
}
//////////////////////////////////////////////////////////////////////////////
// Internal functions.
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Destroys current state bitmaps.
//////////////////////////////////////////////////////////////////////////////
void RMultiBtn::DestroyStates(void) // Returns nothing.
{
if (m_papimStates != NULL)
{
int16_t i;
for (i = 0; i <= m_sNumStates; i++)
{
delete m_papimStates[i];
}
delete []m_papimStates;
m_sNumStates = 0;
}
}
////////////////////////////////////////////////////////////////////////
// Read item's members from file.
// (virtual/protected (overriden here)).
////////////////////////////////////////////////////////////////////////
int16_t RMultiBtn::ReadMembers( // Returns 0 on success.
RFile* pfile, // File to read from.
U32 u32Version) // File format version to use.
{
int16_t sRes = 0; // Assume success.
// Invoke base class to read base members.
sRes = RBtn::ReadMembers(pfile, u32Version);
// If okay so far . . .
if (sRes == 0)
{
ASSERT(pfile != NULL);
ASSERT(pfile->IsOpen() != FALSE);
// Switch on version.
switch (u32Version)
{
default:
// Insert additional version numbers here!
case 7:
pfile->Read(&m_sState);
case 6:
case 5:
case 4:
case 3:
case 2:
case 1:
{
int16_t sNumStates = 0; // Safety.
// Read this class's members.
pfile->Read(&sNumStates);
// Set number of states.
if (SetNumStates(sNumStates) == 0)
{
// Read all the images.
int16_t sCurState;
int16_t sImageForState;
for (sCurState = 0; sCurState <= m_sNumStates && sRes == 0; sCurState++)
{
pfile->Read(&sImageForState);
if (sImageForState != FALSE)
{
// There is an image. Load it.
RImage imState;
if (imState.Load(pfile) == 0)
{
// Set that state.
if (SetState(&imState, sCurState) == 0)
{
// Successfully loaded and set state image.
}
else
{
TRACE("ReadMembers9): SetState() failed for state #%d.\n", sCurState);
sRes = -3;
}
}
else
{
TRACE("ReadMembers(): GetState() failed for state #%d.\n", sCurState);
sRes = -2;
}
}
else
{
// Make sure the state is clear.
ClearState(sCurState);
}
}
}
else
{
TRACE("ReadMembers(): SetNumStates() failed.\n");
sRes = -1;
}
}
case 0: // In version 0, only base class RGuiItem members were stored.
// If successful . . .
if (pfile->Error() == FALSE)
{
// Success.
}
else
{
TRACE("ReadMembers(): Error reading RMultiBtn members.\n");
sRes = -1;
}
break;
}
}
return sRes;
}
////////////////////////////////////////////////////////////////////////
// Write item's members to file.
// (virtual/protected (overriden here)).
////////////////////////////////////////////////////////////////////////
int16_t RMultiBtn::WriteMembers( // Returns 0 on success.
RFile* pfile) // File to write to.
{
int16_t sRes = 0; // Assume success.
// Invoke base class to read base members.
sRes = RBtn::WriteMembers(pfile);
// If okay so far . . .
if (sRes == 0)
{
ASSERT(pfile != NULL);
ASSERT(pfile->IsOpen() != FALSE);
// Write this class's members.
pfile->Write(m_sState);
pfile->Write(m_sNumStates);
// Write all the images.
int16_t sCurState;
for (sCurState = 0; sCurState <= m_sNumStates && sRes == 0; sCurState++)
{
// If there is a bitmap for this state . . .
RImage* pimState = GetState(sCurState);
if (pimState != NULL)
{
// There is an image. Write flag indicating such.
pfile->Write((int16_t)TRUE);
// Write image.
sRes = pimState->Save(pfile);
}
else
{
// No image. Write flag indicating such.
pfile->Write((int16_t)FALSE);
}
}
// If successful . . .
if (pfile->Error() == FALSE)
{
// Success.
}
else
{
TRACE("WriteMembers(): Error writing RMultiBtn members.\n");
sRes = -1;
}
}
return sRes;
}
//////////////////////////////////////////////////////////////////////////////
// EOF
//////////////////////////////////////////////////////////////////////////////
| PixelDevLabs/Ezia-Cleaner_Build-934afd57b26a | RSPiX/Src/ORANGE/GUI/MultiBtn.cpp | C++ | gpl-2.0 | 15,860 |
/*
* Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptPCH.h"
#include "dragon_soul.h"
#include "Map.h"
class instance_dragon_soul: public InstanceMapScript
{
public:
instance_dragon_soul() : InstanceMapScript("instance_dragon_soul", 967) { }
struct instance_dragon_soul_InstanceMapScript : public InstanceScript
{
instance_dragon_soul_InstanceMapScript(InstanceMap* map) : InstanceScript(map)
{
}
// Creatures
uint64 MorchokGUID;
uint64 UnsleepingGUID;
uint64 WarlordGUID;
uint64 HagaraGUID;
uint64 UltraxionGUID;
uint64 WarmasterGUID;
uint64 PortalGUID;
uint64 Maelstrom_trall;
uint64 Maelstrom_kalecgos;
uint64 Maelstrom_ysera;
uint64 Maelstrom_nozdormy;
uint64 Maelstrom_alexstrasza;
uint64 Aspect_Of_MagicGUID;
uint64 AlexstraszaGUID;
uint64 YseraGUID;
uint64 NozdormuGUID;
uint64 Trall_Vs_UltraxionGUID;
uint64 DeathwingGUID;
uint64 arm_tentacle_1;
uint64 arm_tentacle_2;
uint64 wing_tentacle_1;
uint64 wing_tentacle_2;
void Initialize()
{
SetBossNumber(MAX_ENCOUNTER);
MorchokGUID = 0;
UnsleepingGUID = 0;
WarlordGUID = 0;
HagaraGUID = 0;
UltraxionGUID = 0;
WarmasterGUID = 0;
PortalGUID = 0;
Maelstrom_trall = 0;
Maelstrom_kalecgos = 0;
Maelstrom_ysera = 0;
Maelstrom_nozdormy = 0;
Maelstrom_alexstrasza = 0;
Aspect_Of_MagicGUID = 0;
AlexstraszaGUID = 0;
YseraGUID = 0;
NozdormuGUID = 0;
Trall_Vs_UltraxionGUID = 0;
DeathwingGUID = 0;
arm_tentacle_1 = 0;
arm_tentacle_2 = 0;
wing_tentacle_1 = 0;
wing_tentacle_2 = 0;
}
void OnCreatureCreate(Creature* creature)
{
switch (creature->GetEntry())
{
case NPC_MORCHOK:
MorchokGUID = creature->GetGUID();
break;
case NPC_WARLORD:
UnsleepingGUID = creature->GetGUID();
break;
case NPC_UNSLEEPING:
WarlordGUID = creature->GetGUID();
break;
case NPC_HAGARA:
HagaraGUID = creature->GetGUID();
break;
case NPC_ULTRAXION:
UltraxionGUID = creature->GetGUID();
break;
case NPC_WARMASTER:
WarmasterGUID = creature->GetGUID();
break;
case NPC_PORTAL:
PortalGUID = creature->GetGUID();
break;
case NPC_TRALL_VS_ULTRAXION:
Trall_Vs_UltraxionGUID = creature->GetGUID();
break;
case NPC_ALEXSTRASZA:
AlexstraszaGUID = creature->GetGUID();
break;
case NPC_YSERA:
YseraGUID = creature->GetGUID();
break;
case NPC_NOZDORMU:
NozdormuGUID = creature->GetGUID();
break;
case NPC_ASPECT_OF_MAGIC:
Aspect_Of_MagicGUID = creature->GetGUID();
break;
case NPC_MAELSTROM_TRALL:
Maelstrom_trall = creature->GetGUID();
break;
case NPC_MAELSTROM_KALECGOS:
Maelstrom_kalecgos = creature->GetGUID();
break;
case NPC_MAELSTROM_YSERA:
Maelstrom_ysera = creature->GetGUID();
break;
case NPC_MAELSTROM_NOZDORMY:
Maelstrom_nozdormy = creature->GetGUID();
break;
case NPC_MAELSTROM_ALEXSTRASZA:
Maelstrom_alexstrasza = creature->GetGUID();
break;
case NPC_DEATHWING_1:
DeathwingGUID = creature->GetGUID();
break;
case NPC_ARM_TENTACLE_1:
arm_tentacle_1 = creature->GetGUID();
break;
case NPC_ARM_TENTACLE_2:
arm_tentacle_2 = creature->GetGUID();
break;
case NPC_WING_TENTACLE_1:
wing_tentacle_1 = creature->GetGUID();
break;
case NPC_WING_TENTACLE_2:
wing_tentacle_2 = creature->GetGUID();
break;
}
}
void SetData(uint32 type, uint32 data)
{
switch (type)
{
case DATA_DAMAGE_DEATHWING:
if(data == DONE)
if(Creature* creature = instance->GetCreature(DeathwingGUID))
creature->CastSpell(creature, 106548);
SaveToDB();
break;
case DATA_ATTACK_DEATHWING:
{
switch (data)
{
case IN_PROGRESS:
if(Creature* creature = instance->GetCreature(arm_tentacle_1))
{
creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
creature->SetVisible(true);
}
if(Creature* creature = instance->GetCreature(arm_tentacle_2))
{
creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
creature->SetVisible(true);
}
if(Creature* creature = instance->GetCreature(wing_tentacle_1))
{
creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
creature->SetVisible(true);
}
if(Creature* creature = instance->GetCreature(wing_tentacle_2))
{
creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
creature->SetVisible(true);
}
break;
}
SaveToDB();
break;
}
default:
break;
}
}
uint64 GetData64 (uint32 identifier) const
{
switch (identifier)
{
case NPC_MAELSTROM_TRALL:
return Maelstrom_trall;
case NPC_DEATHWING_1:
return DeathwingGUID;
}
return 0;
}
bool SetBossState(uint32 type, EncounterState state)
{
if (!InstanceScript::SetBossState(type, state))
return false;
switch(type)
{
case BOSS_MORCHOK:
case BOSS_WARLORD:
case BOSS_UNSLEEPING:
case BOSS_HAGARA:
case BOSS_WARMASTER:
case BOSS_DEATHWING:
break;
case BOSS_ULTRAXION:
if(state == DONE)
if(Creature* creature = instance->GetCreature(Trall_Vs_UltraxionGUID))
creature->SummonCreature(NPC_TRAVEL_TO_THE_DECK_OF_THE_SKYFIRE, -1802.141f, -2364.638f, 340.796f, 5.234f, TEMPSUMMON_CORPSE_DESPAWN, 900000);
break;
case DATA_TRALL_VS_ULTRAXION:
switch (state)
{
case DONE:
if(Creature* creature = instance->GetCreature(Trall_Vs_UltraxionGUID))
{
creature->AddAura(LAST_DEFENDER_OF_AZEROTH, creature);
creature->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP);
}
if(Creature* creature = instance->GetCreature(AlexstraszaGUID))
creature->CastSpell(creature, GIFT_OF_LIFE);
if(Creature* creature = instance->GetCreature(YseraGUID))
creature->CastSpell(creature, ESSENCE_OF_DREAMS);
if(Creature* creature = instance->GetCreature(NozdormuGUID))
creature->AddAura(TIMELOOP, creature);
if(Creature* creature = instance->GetCreature(Aspect_Of_MagicGUID))
creature->CastSpell(creature, SOURCE_OF_MAGIC);
case FAIL:
DoRemoveAurasDueToSpellOnPlayers(105554);
DoRemoveAurasDueToSpellOnPlayers(106368);
DoRemoveAurasDueToSpellOnPlayers(LAST_DEFENDER_OF_AZEROTH);
DoRemoveAurasDueToSpellOnPlayers(TIMELOOP);
DoRemoveAurasDueToSpellOnPlayers(SOURCE_OF_MAGIC);
DoRemoveAurasDueToSpellOnPlayers(ESSENCE_OF_DREAMS);
DoRemoveAurasDueToSpellOnPlayers(GIFT_OF_LIFE);
break;
default:
break;
}
break;
case DATA_PORTALS_ON_OFF:
break;
}
return true;
}
std::string GetSaveData()
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
saveStream << "D S " << GetBossSaveData();
OUT_SAVE_INST_DATA_COMPLETE;
return saveStream.str();
}
void Load(const char* str)
{
if (!str)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(str);
char dataHead1, dataHead2;
std::istringstream loadStream(str);
loadStream >> dataHead1 >> dataHead2;
if(dataHead1 == 'D' && dataHead2 == 'S')
{
for(uint32 i = 0; i < MAX_ENCOUNTER; ++i)
{
uint32 tmpState;
loadStream >> tmpState;
if (tmpState == IN_PROGRESS || tmpState > SPECIAL)
tmpState = NOT_STARTED;
SetBossState(i, EncounterState(tmpState));
}
}
OUT_LOAD_INST_DATA_COMPLETE;
}
};
InstanceScript* GetInstanceScript(InstanceMap* map) const
{
return new instance_dragon_soul_InstanceMapScript(map);
}
};
void AddSC_instance_dragon_soul()
{
new instance_dragon_soul();
} | Ginfred/DeathCore | src/server/scripts/Kalimdor/CavernsOfTime/DragonSoul/instance_dragon_soul.cpp | C++ | gpl-2.0 | 10,625 |
var config = require('comm/script/config')
App({
globalData: {
userInfo: null
},
onLaunch: function() {
// 获取用户信息
this.getUserInfo()
//初始化缓存
this.initStorage()
},
getUserInfo:function(cb){
var that = this
wx.login({
success: function () {
wx.getUserInfo({
success: function (res) {
that.globalData.userInfo = res.userInfo
typeof cb == "function" && cb(that.globalData.userInfo)
}
})
}
})
},
getCity: function(cb) {
var that = this
wx.getLocation({
type: 'gcj02',
success: function (res) {
var locationParam = res.latitude + ',' + res.longitude + '1'
wx.request({
url: config.apiList.baiduMap,
data: {
ak: config.baiduAK,
location: locationParam,
output: 'json',
pois: '1'
},
method: 'GET',
success: function(res){
config.city = res.data.result.addressComponent.city.slice(0,-1)
typeof cb == "function" && cb(res.data.result.addressComponent.city.slice(0,-1))
},
fail: function(res) {
// 重新定位
that.getCity();
}
})
}
})
},
initStorage: function() {
wx.getStorageInfo({
success: function(res) {
// 判断电影收藏是否存在,没有则创建
if (!('film_favorite' in res.keys)) {
wx.setStorage({
key: 'film_favorite',
data: []
})
}
// 判断人物收藏是否存在,没有则创建
if (!('person_favorite' in res.keys)) {
wx.setStorage({
key: 'person_favorite',
data: []
})
}
// 判断电影浏览记录是否存在,没有则创建
if (!('film_history' in res.keys)) {
wx.setStorage({
key: 'film_history',
data: []
})
}
// 判断人物浏览记录是否存在,没有则创建
if (!('person_history' in res.keys)) {
wx.setStorage({
key: 'person_history',
data: []
})
}
// 个人信息默认数据
var personInfo = {
name: '',
nickName: '',
gender: '',
age: '',
birthday: '',
constellation: '',
company: '',
school: '',
tel: '',
email:'',
intro: ''
}
// 判断个人信息是否存在,没有则创建
if (!('person_info' in res.keys)) {
wx.setStorage({
key: 'person_info',
data: personInfo
})
}
// 判断相册数据是否存在,没有则创建
if (!('gallery' in res.keys)) {
wx.setStorage({
key: 'gallery',
data: []
})
}
// 判断背景卡选择数据是否存在,没有则创建
if (!('skin' in res.keys)) {
wx.setStorage({
key: 'skin',
data: ''
})
}
}
})
}
}) | YHaven/sjqTest | wxCode/allMovie/app.js | JavaScript | gpl-2.0 | 3,189 |
package org.totalboumboum.ai.v201112.ais.gungorkavus.v3.criterion;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.totalboumboum.ai.v201112.adapter.agent.AiUtilityCriterionBoolean;
import org.totalboumboum.ai.v201112.adapter.communication.StopRequestException;
import org.totalboumboum.ai.v201112.adapter.data.AiHero;
import org.totalboumboum.ai.v201112.adapter.data.AiTile;
import org.totalboumboum.ai.v201112.adapter.data.AiZone;
import org.totalboumboum.ai.v201112.ais.gungorkavus.v3.GungorKavus;
/**
* Cette classe est un simple exemple de
* critère binaire. Copiez-la, renommez-la, modifiez-la
* pour l'adapter à vos besoin.
*
* @author Eyüp Burak Güngör
* @author Umit Kavus
*/
@SuppressWarnings("deprecation")
public class VDAdvPertinent extends AiUtilityCriterionBoolean
{ /** Nom de ce critère */
public static final String NAME = "Pertinent";
/**
* Crée un nouveau critère binaire.
*
* @param ai
* ?
* @throws StopRequestException
* Au cas où le moteur demande la terminaison de l'agent.
*/
public VDAdvPertinent(GungorKavus ai) throws StopRequestException
{ // init nom
super(NAME);
ai.checkInterruption();
// init agent
this.ai = ai;
}
/////////////////////////////////////////////////////////////////
// ARTIFICIAL INTELLIGENCE /////////////////////////////////////
/////////////////////////////////////////////////////////////////
/** */
protected GungorKavus ai;
/////////////////////////////////////////////////////////////////
// PROCESS /////////////////////////////////////
/////////////////////////////////////////////////////////////////
@Override
public Boolean processValue(AiTile tile) throws StopRequestException
{
ai.checkInterruption();
boolean result = false;
AiZone zone = ai.getZone();
AiHero ownHero = zone.getOwnHero();
int ownForce = ownHero.getBombNumberMax()*50+ownHero.getBombRange()*70;
int opForce = 0;
Set<AiHero> opponentL = new TreeSet<AiHero>();
List<AiTile> tileNL = tile.getNeighbors();
List<AiHero> remainingOp = zone.getRemainingHeroes();
for(int i = 0;i<tileNL.size();i++){
ai.checkInterruption();
for(int j = 0;j<tileNL.get(i).getHeroes().size();j++){
ai.checkInterruption();
if(remainingOp.contains(tileNL.get(i).getHeroes().get(j)))
opponentL.add(tileNL.get(i).getHeroes().get(j));
}
}
Iterator<AiHero> heroIt = opponentL.iterator();
while(heroIt.hasNext()){
ai.checkInterruption();
AiHero opponent = heroIt.next();
opForce = opponent.getBombNumberMax()*50+opponent.getBombRange()*70;
if(opForce<=ownForce){
result = true;
}
}
return result;
}
} | vlabatut/totalboumboum | resources/ai/org/totalboumboum/ai/v201112/ais/gungorkavus/v3/criterion/VDAdvPertinent.java | Java | gpl-2.0 | 2,816 |
let sentryCaptureException
export function logException(ex: Error): void {
if (__DEV__) {
window.console && console.error && console.error(ex)
} else if (sentryCaptureException) {
sentryCaptureException(ex)
}
}
export async function initSentryLogger(): Promise<void> {
const [{ init: sentryInit }, { captureException }] = await Promise.all([
import(/* webpackChunkName: 'sentry' */ '@sentry/browser/dist/sdk'),
import(/* webpackChunkName: 'sentry' */ '@sentry/browser'),
])
if (__CONFIG__.sentry.dsn) {
sentryCaptureException = captureException
sentryInit({
dsn: __CONFIG__.sentry.dsn,
environment: 'prototype',
maxBreadcrumbs: 10,
ignoreErrors: ['top.GLOBALS'],
})
}
}
| zsebtanar/zsebtanar-proto | src/client/generic/utils/logger.ts | TypeScript | gpl-2.0 | 738 |
<?php
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package Colouralia
* @subpackage Emily Armstrong
*/
global $hello;
$hello = get_post(27);
setup_postdata($hello);
//echo var_export($hello);
?>
<div id="hello">
<div class="infinite">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="title">
<h2><?php echo $hello->post_title; ?></h2>
<div class="content">
<?php echo the_content(); ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
| marcosposada/emily | wp-content/themes/emily/hello-section.php | PHP | gpl-2.0 | 868 |
?php
/**
* @version
* @package MosPrayer - COAddOns for Mambo & Jommla - Prayers on Articles based on COMBO by Phil Taylor
* @copyright (C) 2008 ongetc.com
* @info ongetc@ongetc.com http://ongetc.com
* @license GNU/GPL http://ongetc.com/gpl.html.
*/
// translated by Fuga http://dndon.net
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
//admin.mosprayer.html.php
define('_PRY_A_KEEPUPTODATE','ÅÐÇ ÃÑÏÊ ÇáÅÔÊÑÇß Ýí ÞÇÆãÉ ÇáÊÍÏíËÇÊ ÅÖÛØ Úáì ÇáÒÑ');
define('_PRY_A_SUBSCRIBE','ÅÔÊÑÇß');
define('_PRY_A_UNSUBSCRIBE','ÅäÓÍÇÈ');
define('_PRY_A_BACKUP','äÓÎÉ ÅÍÊíÇØíÉ');
define('_PRY_A_BACKUP_DESC','Úãá äÓÎÉ ÇÍÊíÇØíÉ ãä #__content_mosprayer_requests');
define('_PRY_A_RESTORE','ÅÓÊÚÇÏÉ');
define('_PRY_A_RESTORE_DESC','ÅÓÊÚÇÏÉ ÇáäÓÎÉ ÇáÅÍÊíÇØíÉ ãä #__content_mosprayer_requests');
define('_PRY_A_CONFIG','ÇáÊÚÏíáÇÊ');
define('_PRY_A_CONFIG_DESC','ÍÝÙ ÇáÊÚÏíáÇÊ');
define('_PRY_A_INSTRUCTIONS','ÇáÊÚáíãÇÊ');
define('_PRY_A_INSTRUCTIONS_DESC','ØÑíÞÉ ÊäÕíÈ ÇáÈÑäÇãÌ');
define('_PRY_A_ABOUT','Úä ÇáÈÑäÇãÌ');
define('_PRY_A_ABOUT_DESC','Úä åÐÇ ÇáÈÑäÇãÌ');
define('_PRY_A_LINK','ÑÇÈØ');
define('_PRY_A_LINK_DESC','áãäÊÌ ÇáÈÑäÇãÌ');
define('_PRY_A_CHECK','ÇáÊÃßÏ ãä æÌæÏ ÊÍÏíËÇÊ');
define('_PRY_A_VERSION','ÅÕÏÇÑß åæ ');
define('_PRY_A_DONATE','íÑÌì ÇáÖÛØ Úáì ÃÚáÇä ÇáíÇåæ Ãæ Úáì ÇáÃÞá Þã ÈÏÚã ÇáÈÑäÇãÌ ÈÊÈÑÚ ÈÓíØ');
define('_PRY_A_REVIEW','ÚÑÖ ÇáÊÚáíÞÇÊ ( ÇáÃÍÏË ÃæáÇ )');
define('_PRY_A_DISPLAY','ÚÑÖ #');
define('_PRY_A_NAME_SUB','ÇáÅÓã');
define('_PRY_A_EMAIL_SUB','ÇáÈÑíÏ');
define('_PRY_A_HOMEPAGE','ÇáãæÞÚ');
define('_PRY_A_PRAYER','ÇáÊÚáíÞ');
define('_PRY_A_ARTICLE','ÇáãÞÇáÉ');
define('_PRY_A_PUBLISHED','ãäÔæÑ');
define('_PRY_A_MOS_BY','ÈÑäÇãÌ ÇáÊÚáíÞÇÊ ÈæÇÓØÉ');
define('_PRY_A_CURRENT_SETTINGS','ÇáÎÕÇÆÕ ÇáÍÇáíÉ');
define('_PRY_A_EXPLANATION','ÇáÔÑÍ');
define('_PRY_A_ADMIN_EMAIL','ÈÑíÏ ÇáãÏíÑ');
define('_PRY_A_ADMIN_EMAIL_DESC','ÈÑíÏ ÇáãÏíÑ ÇáÐí ÊÕá Çáíå ÇáÊÚáíÞÇÊ Úáì ÇáÈÑíÏ');
define('_PRY_A_ADMIN_ALERTS','ÅÈáÇÛ ÈÑíÏí');
define('_PRY_A_ADMIN_EMAIL_ENABLE','åá ÊÑíÏ ÊÈáíÛ ÈÑíÏí ÚäÏ ßá ÊÚáíÞ');
define('_PRY_A_VISITOR_EMAIL','ÈÑíÏ ááÒÇÆÑ');
define('_PRY_A_VISITOR_EMAIL_DESC','åá ÊÑíÏ ÅÑÓÇá ÈÑíÏ áßá ÒÇÆÑ Ãæ ÚÖæ ÞÇã ÈÅÖÇÝÉ ÊÚáíÞ');
define('_PRY_A_REVIEW_SUBM','ÊÝÞÏ ÞÈá ÇáäÔÑ');
define('_PRY_A_REVIEW_DESC','ÅÐÇ ÅÎÊÑÊ äÚã ÝÐáß íÚäí Ãä ÇáÊÚáíÞ íÖÇÝ Ýí ÞÇÚÏÉ ÇáÈíÇäÇÊ æáÇ íäÔÑ ÇáÇ ÈÚÏ ÊÕÑíÍß áå ÈÇáäÔÑ .íãßäß ÊÍÏíÏ ÎíÇÑ ÅÈáÇÛ ÈÑíÏí ááãÏíÑ ÃÚáÇå æÐáß áÅÎÈÇÑß Èßá ÇáÊÚÇáíÞ ÇáÊí ÊäÊÙÑ ÇáäÔÑ');
define('_PRY_A_REGISTERED_ONLY','ÝÞØ ÇáÃÚÖÇÁ');
define('_PRY_A_REG_ONLY_DESC','ÅÎÊÑ äÚã áÅÊÇÍÉ ÇáÊÚáíÞÇÊ ááÃÚÖÇÁ ÝÞØ .. áÇ ÊÎÝ ÓíÊã ÚÑÖ ÇáÊÚáíÞÇÊ ááÚÇãÉ æáßä áÇ íãßäåã ÇáÊÚáíÞ ÇáÇ ÇÐÇ ßÇä áÏíåã ÚÖæíÉ Ýí ÇáãÌáÉ');
define('_PRY_A_NOTIFY_VERSION','ÊÈáíÛ ÚäÏ æÌæÏ äÓÎÉ ÌÏíÏÉ');
define('_PRY_A_NOT_VER_DESC','ÅÎÊÑ äÚã ÅÐÇ ÃÑÏÊ Ãä ÊÕáß ÇáÊÍÏíËÇÊ ÚäÏ æÌæÏ äÓÎÉ ÌÏíÏÉ ãä ÇáÈÑäÇãÌ');
define('_PRY_A_HAVE_DONATED','åá ÞãÊ ÈÇáÊÈÑÚ ¿');
define('_PRY_A_DONATE2','ÅÐÇ ÅÎÊÑÊ äÚã Ýáä íÙåÑ ãÑÈÚ ÇáÊÈÑÚ ÊÍÊ ÇáÊÚáíÞÇÊ .. ÇÐÇ ÅÎÊÑÊ áÇ ÝÓíÙåÑ ãÑÈÚ ÇáÊÈÑÚ ÃÓÝá ÇáÊÚáíÞÇÊ');
define('_PRY_A_IMPORTANT_NOTE','ãÚáæãÇÊ ãåãÉ');
define('_PRY_A_TEMPLATE','íÌÈ Úáíß ÊÍÑíÑ ÃãÑ Ýí ÇáÞÇáÈ æÐáß áÊÝÚíá ÇáÊÚáíÞÇÊ Ýí ãÌáÊß<br><a href="index2.php?option=templates&task=edit">ÅäÊÞá Çáì ÇáÞæÇáÈ</a>');
define('_PRY_A_CHANGE_TO','ÅÓÊÈÏá ÇáßæÏ ÇáÊÇáí');
define('_PRY_A_HAVE_FUN','Thats it! ~ (I will not be answering emails along the line of "<em>I"ve installed your component but the form doesn"t show.....</em>" :-)</p> <p> Have Fun!</p> <p>~<a href="http://ongetc.com" target="_blank">Chanh Ong</a>. </p>');
define('_PRY_A_FORCE_PREVIEW','ãÔÇåÏÉ Ãæ ÈÑæÝÉ');
define('_PRY_A_FORCE_PREVIEW_TEXT','ÅÎÊÑ äÚã ÇÐÇ ÃÑÏÊ ÚÑÖ ÈÑæÝÉ ãä ÇáÊÚáíÞ ÞÈá ÇáÅÖÇÝÉ áãÖíÝ ÇáÊÚáíÞ');
define('_PRY_A_HIDE','ÅÎÝÇÁ ÇáÍÞæá');
define('_PRY_A_HIDE_DESC','ÚÑÖ ÑæÇÈØ áÅÖÇÝÉ ÇáÊÚáíÞ æ ãÔÇÏÉ ÇáÊÚáíÞÇÊ ÈÏáÇ ãä ÚÑÖ ÇáÝæÑã ÊÍÊ ÇáãÞÇáÉ');
define('_PRY_A_DATE','ÇáÊÇÑíÎ');
define('_PRY_A_HIDE_URL','ÅÎÝÇÁ ÇáÑÇÈØ');
define('_PRY_A_HIDE_URL_DESC','åá ÊæÏ ÅÎÝÇÁ ÍÞá ÚäæÇä ãæÞÚ ãÖíÝ ÇáÊÚáíÞ');
define('_PRY_A_EMAIL_REQ','Email Required');
define('_PRY_A_EMAIL_REQ_DESC','Use to set either email is required or not on the prayers form by default');
define('_PRY_A_EXCL_SEC','Exclude Section');
define('_PRY_A_EXCL_SEC_DESC','Use to exclude section not to show prayers form by default, eg: 0,1');
define('_PRY_A_PER_PAGE','Prayers per page');
define('_PRY_A_PER_PAGE_DESC','Use to show number of prayers per page, eg: 3');
define('_PRY_A_NEW_1ST','New Prayers First');
define('_PRY_A_NEW_1ST_DESC','List new prayer entries first');
define('_PRY_A_FORM_ABOVE','Comment Form Above');
define('_PRY_A_FORM_ABOVE_DESC','Show prayer form above prayer entries');
define('_PRY_A_USE_DIVCSS','Use DIV CSS');
define('_PRY_A_USE_DIVCSS_DESC','Show prayer form using DIV CSS from template');
define('_PRY_A_EXCL_CONT','Exclude Contents');
define('_PRY_A_EXCL_CONT_DESC','Use to exclude contents via article id not to show prayers form, eg: 0,1');
define('_PRY_A_IP','IP');
define('_PRY_A_USE_USERNAME','Use username');
define('_PRY_A_USE_USERNAME_DESC','Show username instead of name');
define('_PRY_A_CLOSE_CONT','Close Contents');
define('_PRY_A_CLOSE_CONT_DESC','Use to close contents via article id not to show prayers form, eg: 0,1');
define('_PRY_A_USE_SECTOKEN','Use security token');
define('_PRY_A_USE_SECTOKEN_DESC','Check for security token when submit prayer (invisible Captcha)');
//mosprayer.php
define('_PRY_A_NO',"áÇ");
define('_PRY_A_YES',"äÚã");
define('_PRY_R_COM_NUMBER',"ÚÏÏ ÇáÊÚáíÞÇÊ");
define('_PRY_R_NO_COM',"áÇ íæÌÏ Ãí ÊÚáíÞ Çáì ÇáÂä .. íãßäß ÇáÈÏà ÈÅÖÇÝÉ Ãæá ÊÚáíÞ");
define('_PRY_R_POST',"龂");
define('_PRY_R_HOMEPAGE',"ÕÍÇÈ ãæÞÚ");
define('_PRY_R_DATE_ON',"Ýí");
define('_PRY_R_DATE_AT',"Ýí");
define('_PRY_R_ADD_PRAYER',"ÃÖÝ ÊÚáíÞß ááãÞÇáÉ Ãæ ÇáÏÑÓ");
define('_PRY_R_ADD_COM2'," ...");
define('_PRY_R_NAME',"ÇáÅÓã");
define('_PRY_R_EMAIL',"ÇáÈÑíÏ");
define('_PRY_R_EMAIL_NOT',"ÓÊÊã ÍãÇíÉ ÈÑíÏß ãä ÇáÚÑÖ Ýí ÇáãæÞÚ");
define('_PRY_R_HOMEPAGE_IN',"ÇáãæÞÚ");
define('_PRY_R_COM',"ÇáÊÚáíÞ");
define('_PRY_R_FULLY',"íÑÌì ãáà ÇáÍÞæá !");
define('_PRY_R_NEW_COM',"ÊÚáíÞ ÌÏíÏ Ýí");
define('_PRY_R_HAVE_NEW',"áÏíß ÊÚáíÞ Úáì ÇáãÞÇáÉ ÇáÊÇáíÉ :");
define('_PRY_R_LOGIN',"íÑÌì ÇáÏÎæá ááæÍÉ ÇáÊÍßã áäÔÑ ÇáãÞÇáÉ Ãæ ÍÐÝåÇ");
define('_PRY_R_QUICKLINK',"åÐÇ ÑÇÈØ ÓÑíÚ áÏÎæá áæÍÉ ÇáÊÍßã");
define('_PRY_R_THANKS',"ÔßÑÇ áÊÚáíÞß");
define('_PRY_R_THANKS2',"ÔßÑÇ áÊÚáíÞß Úáì ÇáÏÑÓ Ãæ ÇáãÞÇáÉ ÇáÊÇáíÉ");
define('_PRY_R_ADMIN_REV',"ÓíÞæã ÇáãÏíÑ ÈÊÝÞÏ ÇáÊÚáíÞ ÞÈá äÔÑå");
define('_PRY_R_ENTERED',"ÃäÊ ÃÏÎáÊ");
define('_PRY_R_VISIT',"íÑÌì ÒíÇÑÉ ÇáãæÞÚ ÞÑíÈÇ");
define('_PRY_R_THANKS3',"ÔßÑÇ áÅÖÇÝÊß ÇáÊÚáíÞ");
define('_PRY_R_THANKS4',"ÔßÑÇ áß Úáì ÇáÊÚáíÞ ... ÓÊÊã ãÔÇåÏÉ ÇáÊÚáíÞ ÞÈá äÔÑå ãä ÞÈá ÇáãÏíÑ");
define('_PRY_R_SUBMIT',"ÃÖÝ");
define('_PRY_R_RESET',"ãÓÍ");
define('_PRY_R_NOT_AUTH',"áÇ íãßäß ÅÖÇÝÉ ÊÚáíÞ íÑÌì ÊÓÌíá ÏÎæá");
define('_PRY_R_PREV_PAGE',"Prev Page");
define('_PRY_R_NEXT_PAGE',"Next Page");
define('_PRY_R_PAGE',"Page");
define('_PRY_R_REQUEST',"User Prayers");
define('_PRY_R_OF',"of");
define('_PRY_R_CANCEL',"Cancel");
define('_PRY_R_FORM_INTRO',"Enter your prayer below.");
define('_PRY_R_PREVIEW_HEAD',"Please check your entry...");
define('_PRY_R_PREVIEW_INTRO',"Is the below correct? <p />Please make any necessary changes before submitting. Warning: Cancelling will erase your prayer!");
define('_PRY_R_REQ',"<small><i> (ãØáæÈ)</i></small>");
define('_PRY_R_OPT',"<small><i>(optional)</i></small>");
define('_PRY_R_HOMEURL',"here");
define('_PRY_R_CHECKLINK',"CHECK LINK");
define('_PRY_R_QUICKPOST',"Quick Post");
?> | chanhong/mosprayer | language/arabic.php | PHP | gpl-2.0 | 7,522 |
from PyQt4 import QtCore, uic
from PyQt4.QtGui import *
from subprocess import call
from grafo import Grafo
from uis.uiMainwindow import Ui_MainWindow
from sobre import SobreUi
import pdb
from resultado import Resultado
def debug_trace():
'''Set a tracepoint in the Python debugger that works with Qt'''
from PyQt4.QtCore import pyqtRemoveInputHook
from pdb import set_trace
pyqtRemoveInputHook()
set_trace()
class MainWindow(QMainWindow, Ui_MainWindow):
matrizAdjacencia = {}
grafo = Grafo()
def closeEvent(self, event):
if False: event = QCloseEvent
def alert(self):
QMessageBox.about(self, "TESTE", "TESTE")
def addVertice(self, vertice):
if not vertice: return
self.modelVertice.appendRow(QStandardItem(vertice))
self.listVertices.setModel(self.modelVertice)
self.addToComboVertice(vertice)
self.grafo.addVertice(vertice)
def buttonAddVertice(self):
self.addVertice(self.lineNomeVertice.text())
def addAresta(self, aresta):
if not aresta: return
self.modelAresta.appendRow(QStandardItem(aresta))
self.listArestas.setModel(self.modelAresta)
self.comboAresta.addItem(aresta)
self.grafo.addAresta(aresta)
def buttonAddAresta(self):
self.addAresta(self.lineNomeAresta.text())
def addToComboVertice(self, text):
self.comboVertice1.addItem(text)
self.comboVertice2.addItem(text)
self.comboCaminhoInicio.addItem(text)
self.comboCaminhoFim.addItem(text)
def addConexao(self, v1, aresta, v2, peso = 1):
if not v1 or not aresta or not v2: return
conexao = v1 + '|' + aresta + '|' + v2 + '|' + str(peso)
self.modelConexao.appendRow(QStandardItem(conexao))
self.grafo.addConexao(v1, aresta, v2, peso)
self.listConexoes.setModel(self.modelConexao)
def buttonAddConexao(self):
try:
peso = int(self.linePesoNo.text())
except:
peso = 1
v1, v2 = self.comboVertice1.currentText(), self.comboVertice2.currentText()
aresta = self.comboAresta.currentText()
self.addConexao(v1, aresta, v2, peso)
def gerar(self):
# ['1|2|1|1']
# v1 | a | v2 | peso
resList = []
if self.checkDirecionado.isChecked():
self.grafo.setDirecionado(True)
else:
self.grafo.setDirecionado(False)
if self.checkExisteLaco.isChecked():
if self.grafo.existeLaco():
resList.append("- Existem os seguintes laços:\n" + "\n".join(self.grafo.getLaco()))
else:
resList.append("- Nao existem lacos no grafo.")
if self.checkExisteParalela.isChecked():
if self.grafo.existeArestaParalela():
resList.append("- Existem arestas paralelas")
else:
resList.append("- Nao existem arestas paralelas")
if self.checkExisteIsolado.isChecked():
if self.grafo.existeVerticeIsolado():
resList.append("- Existem vertices isolados")
else:
resList.append("- Nao existem vertices isolados")
if self.checkOrdem.isChecked():
resList.append("- Ordem do grafo: " + str(self.grafo.getOrdem()))
if self.checkExisteCiclo.isChecked():
ciclos = self.grafo.getCiclos()
if ciclos:
resList.append("- Existe(m) ciclo(s) para o(s) vértice(s): " + ", ".join(ciclos))
else:
resList.append("- Nao existem ciclos no grafo")
if self.checkConexo.isChecked():
if self.grafo.isConexo():
resList.append("- Grafo é conexo")
else:
resList.append("- Grafo não é conexo")
if self.checkCaminhoCurto.isChecked():
v1 = self.comboCaminhoInicio.currentText()
v2 = self.comboCaminhoFim.currentText()
if self.grafo.existeCaminho(v1, v2, []):
resList.append("- Existe caminho entre o vértice '" + v1 + "' e '" + v2 +"'")
else:
resList.append("- Nao existe caminho entre o vértice '" + v1 + "' e '" + v2 +"'")
if self.checkGrau.isChecked():
graus = self.grafo.getTodosGraus()
if self.grafo.isDirecionado:
resList.append("- Grau de cada vértice (emissão, recepção):")
else:
resList.append("- Grau de cada vértice:")
for v in graus.keys():
if self.grafo.isDirecionado:
resList.append(" '" + v + "': " + str(graus[v][0]) + ", " + str(graus[v][1]))
else:
resList.append(" '" + v + "': " + str(graus[v]))
resList.append("")
if self.checkAdjacencia.isChecked():
adjacencias = self.grafo.getTodasAdjacencias()
resList.append("- Adjacências de cada vértice:")
for v in adjacencias.keys():
strAdj = "" + v + ": "
verticesAdj = []
for arestaAdj, vertAdj in adjacencias[v]:
verticesAdj.append(vertAdj)
if verticesAdj:
resList.append(strAdj + ", ".join(verticesAdj))
else:
resList.append(strAdj + "Nenhum")
resultado = Resultado("\n".join(resList), self)
resultado.centerToMainWindow()
self.resultados.append(resultado)
def buttonRemoveVertice(self):
index = self.listVertices.currentIndex()
text = self.modelVertice.itemFromIndex(index).text()
self.removeVertice({'index': index.row(), 'value': text})
def removeVertice(self, v):
self.grafo.removeVertice(v['value'])
self.modelVertice.removeRow(v['index'])
eraseFrom = [self.comboVertice1,self.comboVertice2,self.comboCaminhoInicio,self.comboCaminhoFim]
for combo in eraseFrom:
combo.removeItem(combo.findText(v['value']))
# for i in self.comboVertice1.count():
# pass
toErase = []
for i in range(self.modelConexao.rowCount()):
item = self.modelConexao.item(i)
values = item.text().split('|')
if values[0] == str(v['value']) or values[2] == str(v['value']):
toErase.append(item)
for item in toErase:
index = self.modelConexao.indexFromItem(item)
if False: index = QStandardItem
self.modelConexao.removeRow(index.row())
def removeConexao(self, a):
self.grafo.removeConexao(a['value'].split('|')[1])
self.modelConexao.removeRow(a['index'])
def removeAresta(self, a):
self.grafo.removeAresta(a['value'])
self.modelAresta.removeRow(a['index'])
self.comboAresta.removeItem(self.comboAresta.findText(a['value']))
toErase = []
for i in range(self.modelConexao.rowCount()):
item = self.modelConexao.item(i)
values = item.text().split('|')
print(values)
if values[1] == str(a['value']):
toErase.append(item)
for item in toErase:
index = self.modelConexao.indexFromItem(item)
if False: index = QStandardItem
self.modelConexao.removeRow(index.row())
def listVerticesClicked(self, model):
if False: model = QStandardItem
self.modelVertice.removeRow(model.row())
def __init__(self, parent=None, name=None, fl=0):
self.resultados = []
QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
Ui_MainWindow.setupUi(self, self)
self.menuArquivo.setTitle("&Arquivo")
# uic.loadUi('mainwindow.ui', self)
# self.listVertices.setEditTriggers(QApplication.NoEditTriggers)
self.modelVertice = QStandardItemModel(self.listVertices)
self.modelAresta = QStandardItemModel(self.listArestas)
self.modelConexao = QStandardItemModel(self.listConexoes)
self.sobreUi = SobreUi(self)
self.sobreUi.tbAbout.setText(open('sobre.txt').read())
self.events()
def buttonRemoveAresta(self):
index = self.listArestas.currentIndex()
text = self.modelAresta.itemFromIndex(index).text()
self.removeAresta({'index': index.row(), 'value': text})
def buttonRemoveConexao(self):
index = self.listConexoes.currentIndex()
text = self.modelConexao.itemFromIndex(index).text()
self.removeConexao({'index': index.row(), 'value': text})
def events(self):
QtCore.QObject.connect(self.pushAddVertice,
QtCore.SIGNAL("clicked()"),
self.buttonAddVertice)
QtCore.QObject.connect(self.pushAddAresta,
QtCore.SIGNAL("clicked()"),
self.buttonAddAresta)
QtCore.QObject.connect(self.pushAddConexao,
QtCore.SIGNAL("clicked()"),
self.buttonAddConexao)
QtCore.QObject.connect(self.pushRemoverVertice,
QtCore.SIGNAL("clicked()"),
self.buttonRemoveVertice)
QtCore.QObject.connect(self.pushRemoverAresta,
QtCore.SIGNAL("clicked()"),
self.buttonRemoveAresta)
QtCore.QObject.connect(self.pushRemoveConexao,
QtCore.SIGNAL("clicked()"),
self.buttonRemoveConexao)
QtCore.QObject.connect(self.pushGerar, QtCore.SIGNAL("clicked()"), self.gerar)
self.actionSobre.triggered.connect(self.showSobreUi)
self.actionSair.triggered.connect(self.sair)
def showSobreUi(self):
self.sobreUi.show()
self.sobreUi.centerToMainWindow()
def sair(self):
self.close()
def show(self):
super().show()
| sollidsnake/grafo | mainwindow.py | Python | gpl-2.0 | 10,057 |
<?php
$lang['0comments'] = '%d Kommentare';
$lang['1comments'] = '%d Kommentar';
$lang['Xcomments'] = '%d Kommentare';
$lang['readmore'] = 'Weiter lesen...';
$lang['prev'] = '< Neuere Beiträge';;
$lang['next'] = 'Ältere Beiträge >';
$lang['title'] = 'Titel:';
$lang['create'] = 'Anlegen';
$lang['comment_mail'] = 'E-Mail';
$lang['comment_name'] = 'Name';
$lang['comment_web'] = 'Webseite';
$lang['comment_preview'] = 'Vorschau';
$lang['comment_submit'] = 'Kommentieren';
$lang['comment_subscribe'] = 'Neue Kommentare abbonieren';
$lang['err_notitle'] = 'Kein Beitragstitel angegeben!';
| foozzi/linuxeed.org | lib/plugins/blogtng/lang/de/lang.php | PHP | gpl-2.0 | 633 |
<?php
/**
* @category Virtue Theme
* @package Metaboxes
* @license http://www.opensource.org/licenses/gpl-license.php GPL v2.0 (or later)
* @link https://github.com/jaredatch/Custom-Metaboxes-and-Fields-for-WordPress
*/
add_filter( 'cmb_meta_boxes', 'virtue_metaboxes' );
/**
* Define the metabox and field configurations.
*
* @param array $meta_boxes
* @return array
*/
//add_filter('cmb_icomoon', 'cmb_icomoon');
add_filter( 'cmb_render_imag_select_taxonomy', 'imag_render_imag_select_taxonomy', 10, 2 );
function imag_render_imag_select_taxonomy( $field, $meta ) {
wp_dropdown_categories(array(
'show_option_none' => __( "All", 'virtue' ),
'hierarchical' => 1,
'taxonomy' => $field['taxonomy'],
'orderby' => 'name',
'hide_empty' => 0,
'name' => $field['id'],
'selected' => $meta
));
if ( !empty( $field['desc'] ) ) echo '<p class="cmb_metabox_description">' . $field['desc'] . '</p>';
}
add_filter( 'cmb_render_imag_select_category', 'imag_render_imag_select_category', 10, 2 );
function imag_render_imag_select_category( $field, $meta ) {
wp_dropdown_categories(array(
'show_option_none' => __( "All Blog Posts", 'virtue' ),
'hierarchical' => 1,
'taxonomy' => 'category',
'orderby' => 'name',
'hide_empty' => 0,
'name' => $field['id'],
'selected' => $meta
));
if ( !empty( $field['desc'] ) ) echo '<p class="cmb_metabox_description">' . $field['desc'] . '</p>';
}
add_filter( 'cmb_render_imag_select_sidebars', 'imag_render_imag_select_sidebars', 10, 2 );
function imag_render_imag_select_sidebars( $field, $meta ) {
global $vir_sidebars;
echo '<select name="', $field['id'], '" id="', $field['id'], '">';
foreach ($vir_sidebars as $side) {
echo '<option value="', $side['id'], '"', $meta == $side['id'] ? ' selected="selected"' : '', '>', $side['name'], '</option>';
}
echo '</select>';
if ( !empty( $field['desc'] ) ) echo '<p class="cmb_metabox_description">' . $field['desc'] . '</p>';
}
function virtue_metaboxes( array $meta_boxes ) {
// Start with an underscore to hide fields from custom fields list
$prefix = '_kad_';
$meta_boxes[] = array(
'id' => 'subtitle_metabox',
'title' => __( "Page Title and Subtitle", 'virtue' ),
'pages' => array( 'page', ), // Post type
'context' => 'normal',
'priority' => 'high',
'show_names' => true, // Show field names on the left
'fields' => array(
array(
'name' => __( "Subtitle", 'virtue' ),
'desc' => __( "Subtitle will go below page title", 'virtue' ),
'id' => $prefix . 'subtitle',
'type' => 'textarea_small',
),
)
);
$meta_boxes[] = array(
'id' => 'post_metabox',
'title' => __("Post Options", 'virtue'),
'pages' => array( 'post',), // Post type
'context' => 'normal',
'priority' => 'high',
'show_names' => true, // Show field names on the left
'fields' => array(
array(
'name' => __("Head Content", 'virtue' ),
'desc' => '',
'id' => $prefix . 'blog_head',
'type' => 'select',
'options' => array(
array( 'name' => __("None", 'virtue' ), 'value' => 'none', ),
array( 'name' => __("Image Slider", 'virtue' ), 'value' => 'flex', ),
array( 'name' => __("Video", 'virtue' ), 'value' => 'video', ),
array( 'name' => __("Image", 'virtue' ), 'value' => 'image', ),
),
),
array(
'name' => __("Max Image/Slider Height", 'virtue' ),
'desc' => __("Default is: 400 <b>(Note: just input number, example: 350)</b>", 'virtue' ),
'id' => $prefix . 'posthead_height',
'type' => 'text_small',
),
array(
'name' => __("Max Image/Slider Width", 'virtue' ),
'desc' => __("Default is: 770 or 1140 on fullwidth posts <b>(Note: just input number, example: 650, does not apply to carousel slider)</b>", 'virtue' ),
'id' => $prefix . 'posthead_width',
'type' => 'text_small',
),
array(
'name' => __("Post Summary", 'virtue' ),
'desc' => '',
'id' => $prefix . 'post_summery',
'type' => 'select',
'options' => array(
array( 'name' => __('Default', 'virtue' ), 'value' => 'default', ),
array( 'name' => __('Text', 'virtue' ), 'value' => 'text', ),
array( 'name' => __('Portrait Image', 'virtue'), 'value' => 'img_portrait', ),
array( 'name' => __('Landscape Image', 'virtue'), 'value' => 'img_landscape', ),
array( 'name' => __('Portrait Image Slider', 'virtue'), 'value' => 'slider_portrait', ),
array( 'name' => __('Landscape Image Slider', 'virtue'), 'value' => 'slider_landscape', ),
array( 'name' => __('Video', 'virtue'), 'value' => 'video', ),
),
),
array(
'name' => __('Display Sidebar?', 'virtue'),
'desc' => __('Choose if layout is fullwidth or sidebar', 'virtue'),
'id' => $prefix . 'post_sidebar',
'type' => 'select',
'options' => array(
array( 'name' => __('Yes', 'virtue'), 'value' => 'yes', ),
array( 'name' => __('No', 'virtue'), 'value' => 'no', ),
),
),
array(
'name' => __('Choose Sidebar', 'virtue'),
'desc' => '',
'id' => $prefix . 'sidebar_choice',
'type' => 'imag_select_sidebars',
),
array(
'name' => __('Author Info', 'virtue'),
'desc' => __('Display an author info box?', 'virtue'),
'id' => $prefix . 'blog_author',
'type' => 'select',
'options' => array(
array( 'name' => __('No', 'virtue'), 'value' => 'no', ),
array( 'name' => __('Yes', 'virtue'), 'value' => 'yes', ),
),
),
array(
'name' => __('Posts Carousel', 'virtue'),
'desc' => __('Display a carousel with similar or recent posts?', 'virtue'),
'id' => $prefix . 'blog_carousel_similar',
'type' => 'select',
'options' => array(
array( 'name' => __('No', 'virtue'), 'value' => 'no', ),
array( 'name' => __('Yes - Display Recent Posts', 'virtue'), 'value' => 'recent', ),
array( 'name' => __('Yes - Display Similar Posts', 'virtue'), 'value' => 'similar', )
),
),
array(
'name' => __('Carousel Title', 'virtue'),
'desc' => __('ex. Similar Posts', 'virtue'),
'id' => $prefix . 'blog_carousel_title',
'type' => 'text_medium',
),
),
);
$meta_boxes[] = array(
'id' => 'post_video_metabox',
'title' => __('Post Video Box', 'virtue'),
'pages' => array( 'post',), // Post type
'context' => 'normal',
'priority' => 'high',
'show_names' => true,
'fields' => array(
array(
'name' => __('If Video Post', 'virtue'),
'desc' => __('Place Embed Code Here, works with youtube, vimeo...', 'virtue'),
'id' => $prefix . 'post_video',
'type' => 'textarea_code',
),
),
);
$meta_boxes[] = array(
'id' => 'portfolio_post_metabox',
'title' => __('Portfolio Post Options', 'virtue'),
'pages' => array( 'portfolio' ), // Post type
'context' => 'normal',
'priority' => 'high',
'show_names' => true, // Show field names on the left
'fields' => array(
array(
'name' => __('Project Layout', 'virtue'),
'desc' => '<a href="http://docs.kadencethemes.com/virtue/#portfolio_posts" target="_new" >Whats the difference?</a>',
'id' => $prefix . 'ppost_layout',
'type' => 'radio_inline',
'options' => array(
array( 'name' => __('Beside', 'virtue'), 'value' => 'beside', ),
array( 'name' => __('Above', 'virtue'), 'value' => 'above', ),
array( 'name' => __('Three Rows', 'virtue'), 'value' => 'three', ),
),
),
array(
'name' => __('Project Options', 'virtue'),
'desc' => '',
'id' => $prefix . 'ppost_type',
'type' => 'select',
'options' => array(
array( 'name' => __('Image', 'virtue'), 'value' => 'image', ),
array( 'name' => __('Image Slider', 'virtue'), 'value' => 'flex', ),
array( 'name' => __('Carousel Slider', 'virtue'), 'value' => 'carousel', ),
array( 'name' => __('Video', 'virtue'), 'value' => 'video', ),
array( 'name' => __('None', 'virtue'), 'value' => 'none', ),
),
),
array(
'name' => __("Max Image/Slider Height", 'virtue' ),
'desc' => __("Default is: 450 <b>(Note: just input number, example: 350)</b>", 'virtue' ),
'id' => $prefix . 'posthead_height',
'type' => 'text_small',
),
array(
'name' => __("Max Image/Slider Width", 'virtue' ),
'desc' => __("Default is: 670 or 1140 on <b>above</b> or <b>three row</b> layouts (Note: just input number, example: 650)</b>", 'virtue' ),
'id' => $prefix . 'posthead_width',
'type' => 'text_small',
),
array(
'name' => __('Value 01 Title', 'virtue'),
'desc' => __('ex. Project Type:', 'virtue'),
'id' => $prefix . 'project_val01_title',
'type' => 'text_medium',
),
array(
'name' => __('Value 01 Description', 'virtue'),
'desc' => __('ex. Character Illustration', 'virtue'),
'id' => $prefix . 'project_val01_description',
'type' => 'text_medium',
),
array(
'name' => __('Value 02 Title', 'virtue'),
'desc' => __('ex. Skills Needed:', 'virtue'),
'id' => $prefix . 'project_val02_title',
'type' => 'text_medium',
),
array(
'name' => __('Value 02 Description', 'virtue'),
'desc' => __('ex. Photoshop, Illustrator', 'virtue'),
'id' => $prefix . 'project_val02_description',
'type' => 'text_medium',
),
array(
'name' => __('Value 03 Title', 'virtue'),
'desc' => __('ex. Customer:', 'virtue'),
'id' => $prefix . 'project_val03_title',
'type' => 'text_medium',
),
array(
'name' => __('Value 03 Description', 'virtue'),
'desc' => __('ex. Example Inc', 'virtue'),
'id' => $prefix . 'project_val03_description',
'type' => 'text_medium',
),
array(
'name' => __('Value 04 Title', 'virtue'),
'desc' => __('ex. Project Year:', 'virtue'),
'id' => $prefix . 'project_val04_title',
'type' => 'text_medium',
),
array(
'name' => __('Value 04 Description', 'virtue'),
'desc' => __('ex. 2013', 'virtue'),
'id' => $prefix . 'project_val04_description',
'type' => 'text_medium',
),
array(
'name' => __('External Website', 'virtue'),
'desc' => __('ex. Website:', 'virtue'),
'id' => $prefix . 'project_val05_title',
'type' => 'text_medium',
),
array(
'name' => __('Website Address', 'virtue'),
'desc' => __('ex. http://www.example.com', 'virtue'),
'id' => $prefix . 'project_val05_description',
'type' => 'text_medium',
),
array(
'name' => __('If Video Project', 'virtue'),
'desc' => __('Place Embed Code Here, works with youtube, vimeo...', 'virtue'),
'id' => $prefix . 'post_video',
'type' => 'textarea_code',
),
array(
'name' => __('Similar Portfolio Item Carousel', 'virtue'),
'desc' => __('Display a carousel with similar portfolio items below project?', 'virtue'),
'id' => $prefix . 'portfolio_carousel_recent',
'type' => 'select',
'options' => array(
array( 'name' => __('No', 'virtue'), 'value' => 'no', ),
array( 'name' => __('Yes - Display Recent Projects', 'virtue'), 'value' => 'recent', ),
),
),
array(
'name' => __('Carousel Title', 'virtue'),
'desc' => __('ex. Similar Projects', 'virtue'),
'id' => $prefix . 'portfolio_carousel_title',
'type' => 'text_medium',
),
),
);
$meta_boxes[] = array(
'id' => 'portfolio_metabox',
'title' => __('Portfolio Page Options', 'virtue'),
'pages' => array( 'page' ), // Post type
'show_on' => array('key' => 'page-template', 'value' => array( 'page-portfolio.php' )),
'context' => 'normal',
'priority' => 'high',
'show_names' => true, // Show field names on the left
'fields' => array(
array(
'name' => __('Columns', 'virtue'),
'desc' => '',
'id' => $prefix . 'portfolio_columns',
'type' => 'select',
'options' => array(
array( 'name' => __('Four Column', 'virtue'), 'value' => '4', ),
array( 'name' => __('Three Column', 'virtue'), 'value' => '3', ),
array( 'name' => __('Two Column', 'virtue'), 'value' => '2', ),
),
),
array(
'name' => __('Portfolio Work Types', 'virtue'),
'desc' => '',
'id' => $prefix .'portfolio_type',
'type' => 'imag_select_taxonomy',
'taxonomy' => 'portfolio-type',
),
array(
'name' => __('Order Items By', 'virtue'),
'desc' => '',
'id' => $prefix . 'portfolio_order',
'type' => 'select',
'options' => array(
array( 'name' => __('Menu Order', 'virtue'), 'value' => 'menu_order', ),
array( 'name' => __('Title', 'virtue'), 'value' => 'title', ),
array( 'name' => __('Date', 'virtue'), 'value' => 'date', ),
array( 'name' => __('Random', 'virtue'), 'value' => 'rand', ),
),
),
array(
'name' => __('Items per Page', 'virtue'),
'desc' => __('How many portfolio items per page', 'virtue'),
'id' => $prefix . 'portfolio_items',
'type' => 'select',
'options' => array(
array( 'name' => __('All', 'virtue'), 'value' => 'all', ),
array( 'name' => '3', 'value' => '3', ),
array( 'name' => '4', 'value' => '4', ),
array( 'name' => '5', 'value' => '5', ),
array( 'name' => '6', 'value' => '6', ),
array( 'name' => '7', 'value' => '7', ),
array( 'name' => '8', 'value' => '8', ),
array( 'name' => '9', 'value' => '9', ),
array( 'name' => '10', 'value' => '10', ),
array( 'name' => '11', 'value' => '11', ),
array( 'name' => '12', 'value' => '12', ),
array( 'name' => '13', 'value' => '13', ),
array( 'name' => '14', 'value' => '14', ),
array( 'name' => '15', 'value' => '15', ),
array( 'name' => '16', 'value' => '16', ),
),
),
array(
'name' => __('Set image height', 'virtue'),
'desc' => __('Default is 1:1 ratio <b>(Note: just input number, example: 350)</b>', 'virtue'),
'id' => $prefix . 'portfolio_img_crop',
'type' => 'text_small',
),
array(
'name' => __('Display Item Work Types', 'virtue'),
'desc' => '',
'id' => $prefix . 'portfolio_item_types',
'type' => 'checkbox',
'std' => '1'
),
array(
'name' => __('Display Item Excerpt', 'virtue'),
'desc' => '',
'id' => $prefix . 'portfolio_item_excerpt',
'type' => 'checkbox',
'std' => '1'
),
array(
'name' => __('Add Lightbox link in the top right of each item', 'virtue'),
'desc' => '',
'id' => $prefix . 'portfolio_lightbox',
'type' => 'select',
'options' => array(
array( 'name' => __('No', 'virtue'), 'value' => 'no', ),
array( 'name' => __('Yes', 'virtue'), 'value' => 'yes', ),
),
),
));
$meta_boxes[] = array(
'id' => 'pagefeature_metabox',
'title' => __('Feature Page Options', 'virtue'),
'pages' => array( 'page' ), // Post type
'show_on' => array('key' => 'page-template', 'value' => array( 'page-feature.php', 'page-feature-sidebar.php')),
'context' => 'normal',
'priority' => 'high',
'show_names' => true, // Show field names on the left
'fields' => array(
array(
'name' => __('Feature Options', 'virtue'),
'desc' => __('If image slider make sure images uploaded are at least 1140px wide.', 'virtue'),
'id' => $prefix . 'page_head',
'type' => 'select',
'options' => array(
array( 'name' => __('Image Slider', 'virtue'), 'value' => 'flex', ),
array( 'name' => __('Video', 'virtue'), 'value' => 'video', ),
array( 'name' => __('Image', 'virtue'), 'value' => 'image', ),
),
),
array(
'name' => __('Max Image/Slider Height', 'virtue'),
'desc' => __('Default is: 400 <b>(Note: just input number, example: 350)</b>', 'virtue'),
'id' => $prefix . 'posthead_height',
'type' => 'text_small',
),
array(
'name' => __("Max Image/Slider Width", 'virtue' ),
'desc' => __("Default is: 1140 <b>(Note: just input number, example: 650, does not apply to Carousel slider)</b>", 'virtue' ),
'id' => $prefix . 'posthead_width',
'type' => 'text_small',
),
array(
'name' => __('Use Lightbox for Feature Image', 'virtue'),
'desc' => __("If feature option is set to image, choose to use lightbox link with image.", 'virtue' ),
'id' => $prefix . 'feature_img_lightbox',
'type' => 'select',
'options' => array(
array( 'name' => __('Yes', 'virtue'), 'value' => 'yes', ),
array( 'name' => __('No', 'virtue'), 'value' => 'no', ),
),
),
array(
'name' => __('If Video Post', 'virtue'),
'desc' => __('Place Embed Code Here, works with youtube, vimeo...', 'virtue'),
'id' => $prefix . 'post_video',
'type' => 'textarea_code',
),
));
$meta_boxes[] = array(
'id' => 'bloglist_metabox',
'title' => __('Blog List Options', 'virtue'),
'pages' => array( 'page' ), // Post type
'show_on' => array('key' => 'page-template', 'value' => array( 'page-blog.php')),
'context' => 'normal',
'priority' => 'high',
'show_names' => true, // Show field names on the left
'fields' => array(
array(
'name' => __('Blog Category', 'virtue'),
'desc' => __('Select all blog posts or a specific category to show', 'virtue'),
'id' => $prefix .'blog_cat',
'type' => 'imag_select_category',
'taxonomy' => 'category',
),
array(
'name' => __('How Many Posts Per Page', 'virtue'),
'desc' => '',
'id' => $prefix . 'blog_items',
'type' => 'select',
'options' => array(
array( 'name' => __('All', 'virtue'), 'value' => 'all', ),
array( 'name' => '2', 'value' => '2', ),
array( 'name' => '3', 'value' => '3', ),
array( 'name' => '4', 'value' => '4', ),
array( 'name' => '5', 'value' => '5', ),
array( 'name' => '6', 'value' => '6', ),
array( 'name' => '7', 'value' => '7', ),
array( 'name' => '8', 'value' => '8', ),
array( 'name' => '9', 'value' => '9', ),
array( 'name' => '10', 'value' => '10', ),
array( 'name' => '11', 'value' => '11', ),
array( 'name' => '12', 'value' => '12', ),
array( 'name' => '13', 'value' => '13', ),
array( 'name' => '14', 'value' => '14', ),
array( 'name' => '15', 'value' => '15', ),
array( 'name' => '16', 'value' => '16', ),
),
),
array(
'name' => __('Display Post Content as:', 'virtue'),
'desc' => '',
'id' => $prefix . 'blog_summery',
'type' => 'select',
'options' => array(
array( 'name' => __('Summary', 'virtue'), 'value' => 'summery', ),
array( 'name' => __('Full', 'virtue'), 'value' => 'full', ),
),
),
array(
'name' => __('Display Sidebar?', 'virtue'),
'desc' => __('Choose if layout is fullwidth or sidebar', 'virtue'),
'id' => $prefix . 'page_sidebar',
'type' => 'select',
'options' => array(
array( 'name' => __('Yes', 'virtue'), 'value' => 'yes', ),
array( 'name' => __('No', 'virtue'), 'value' => 'no', ),
),
),
array(
'name' => __('Choose Sidebar', 'virtue'),
'desc' => '',
'id' => $prefix . 'sidebar_choice',
'type' => 'imag_select_sidebars',
),
));
$meta_boxes[] = array(
'id' => 'contact_metabox',
'title' => __('Contact Page Options', 'virtue'),
'pages' => array( 'page' ), // Post type
'show_on' => array('key' => 'page-template', 'value' => array( 'page-contact.php')),
'context' => 'normal',
'priority' => 'high',
'show_names' => true, // Show field names on the left
'fields' => array(
array(
'name' => __('Use Contact Form', 'virtue'),
'desc' => '',
'id' => $prefix .'contact_form',
'type' => 'select',
'options' => array(
array( 'name' => __('Yes', 'virtue'), 'value' => 'yes', ),
array( 'name' => __('No', 'virtue'), 'value' => 'no', ),
),
),
array(
'name' => __('Contact Form Title', 'virtue'),
'desc' => __('ex. Send us an Email', 'virtue'),
'id' => $prefix . 'contact_form_title',
'type' => 'text',
),
array(
'name' => __('Use Map', 'virtue'),
'desc' => '',
'id' => $prefix .'contact_map',
'type' => 'select',
'options' => array(
array( 'name' => __('No', 'virtue'), 'value' => 'no', ),
array( 'name' => __('Yes', 'virtue'), 'value' => 'yes', ),
),
),
array(
'name' => __('Address', 'virtue'),
'desc' => __('Enter your Location', 'virtue'),
'id' => $prefix . 'contact_address',
'type' => 'text',
),
array(
'name' => __('Map Type', 'virtue'),
'desc' => '',
'id' => $prefix . 'contact_maptype',
'type' => 'select',
'options' => array(
array( 'name' => __('ROADMAP', 'virtue'), 'value' => 'ROADMAP', ),
array( 'name' => __('HYBRID', 'virtue'), 'value' => 'HYBRID', ),
array( 'name' => __('TERRAIN', 'virtue'), 'value' => 'TERRAIN', ),
array( 'name' => __('SATELLITE', 'virtue'), 'value' => 'SATELLITE', ),
),
),
array(
'name' => __('Map Zoom Level', 'virtue'),
'desc' => __('A good place to start is 15', 'virtue'),
'id' => $prefix . 'contact_zoom',
'std' => '15',
'type' => 'select',
'options' => array(
array( 'name' => __('1 (World View)', 'virtue'), 'value' => '1', ),
array( 'name' => '2', 'value' => '2', ),
array( 'name' => '3', 'value' => '3', ),
array( 'name' => '4', 'value' => '4', ),
array( 'name' => '5', 'value' => '5', ),
array( 'name' => '6', 'value' => '6', ),
array( 'name' => '7', 'value' => '7', ),
array( 'name' => '8', 'value' => '8', ),
array( 'name' => '9', 'value' => '9', ),
array( 'name' => '10', 'value' => '10', ),
array( 'name' => '11', 'value' => '11', ),
array( 'name' => '12', 'value' => '12', ),
array( 'name' => '13', 'value' => '13', ),
array( 'name' => '14', 'value' => '14', ),
array( 'name' => '15', 'value' => '15', ),
array( 'name' => '16', 'value' => '16', ),
array( 'name' => '17', 'value' => '17', ),
array( 'name' => '18', 'value' => '18', ),
array( 'name' => '19', 'value' => '19', ),
array( 'name' => '20', 'value' => '20', ),
array( 'name' => __('21 (Street View)', 'virtue'), 'value' => '21', ),
),
),
array(
'name' => __('Map Height', 'virtue'),
'desc' => __('Default is 300', 'virtue'),
'id' => $prefix . 'contact_mapheight',
'type' => 'text_small',
),
));
$meta_boxes[] = array(
'id' => 'page_sidebar',
'title' => __('Sidebar Options', 'virtue'),
'pages' => array( 'page' ), // Post type
'show_on' => array( 'key' => 'page-template', 'value' => array('page-sidebar.php','page-feature-sidebar.php')),
'context' => 'normal',
'priority' => 'high',
'show_names' => true, // Show field names on the left
'fields' => array(
array(
'name' => __('Choose Sidebar', 'virtue'),
'desc' => '',
'id' => $prefix . 'sidebar_choice',
'type' => 'imag_select_sidebars',
),
));
// Add other metaboxes as needed
return $meta_boxes;
}
add_action( 'init', 'initialize_showcase_meta_boxes', 9999 );
/**
* Initialize the metabox class.
*/
function initialize_showcase_meta_boxes() {
if ( ! class_exists( 'cmb_Meta_Box' ) )
require_once 'cmb/init.php';
} | pcostan/mscm | wp-content/themes/virtue/lib/metaboxes.php | PHP | gpl-2.0 | 24,075 |
import numpy as np
from collections import namedtuple
import interp
epi0 = 1. # Epsilon0
Species = namedtuple("Species", ["q", "m", "N", "x0", "vx0", "vy0"])
__cache_one_d_poisson = {}
def one_d_poisson(n):
if n in __cache_one_d_poisson:
return __cache_one_d_poisson[n]
a = np.zeros((n,n))
np.fill_diagonal(a, -2.)
np.fill_diagonal(a[:-1,1:], 1.)
np.fill_diagonal(a[1:,:-1], 1.)
__cache_one_d_poisson[n] = a
return a
# Dict of solver functions with string keys
__solver = {}
def poisson_solve_fd(b, dx):
""" Assume V0=0
"""
nx = len(b)
A = one_d_poisson(nx-1)
p = -b*(dx**2)
x = np.zeros_like(p)
x[1:] = np.linalg.solve(A, p[1:])
return x
__solver["FD"] = poisson_solve_fd
def poisson_solve_fft(rho, dx):
nx = len(rho)
rhok = np.fft.fft(rho)
k = np.fft.fftfreq(nx)*2*np.pi/dx
kd = (k[1:]**2)*(np.sin(k[1:]*dx/2.)/(k[1:]*dx/2))**2
phik = np.zeros_like(rhok)
phik[1:] = rhok[1:]/kd
sol = np.real(np.fft.ifft(phik))
return sol
__solver["FFT"] = poisson_solve_fft
def poisson_solve(b, dx, method="FFT"):
if method in __solver:
return __solver[method](b, dx)
else:
return method(b, dx)
# Dicts of weight/interp functions with string keys
__weight = {}
__interp = {}
__weight["CIC"] = interp.weight_cic
def interp_cic(E, xp, nx, L):
""" Interpolate E to particle positions (CIC)
"""
xps = xp*nx/L
left = np.floor(xps).astype(np.int)
right = np.mod(np.ceil(xps), nx).astype(np.int)
E_interp = E[left]*(left+1-xps) + E[right]*(xps-left)
return E_interp
__interp["CIC"] = interp_cic
def weight_ngp(xp, q, nx, L):
""" Weighting to grid (NGP)
"""
rho = np.zeros(nx)
xps = np.round(xp*nx/L).astype(np.int)
xps[xps==nx] = 0
for i in xrange(len(xps)):
rho[xps[i]] += q[i]
return rho
__weight["NGP"] = weight_ngp
def interp_ngp(E, xp, nx, L):
""" Interpolate E to particle positions (NGP)
"""
xps = np.round(xp*nx/L).astype(np.int)
xps[xps==nx] = 0
return E[xps]
__interp["NGP"] = interp_ngp
def weight(xp, q, nx, L, method="CIC"):
if method in __weight:
dx = L/nx
return __weight[method](xp, q, nx, L)
else:
return method(xp, q, nx, L)
def interp(E, xp, nx, L, method="CIC"):
if method in __interp:
return __interp[method](E, xp, nx, L)
else:
return method(E, xp, nx, L)
def calc_E(phi, dx):
""" Calc E at the particle positions
Centered difference (second order)
"""
E = np.zeros_like(phi)
E[1:-1] = -(phi[2:]-phi[:-2])
E[0] = -(phi[1]-phi[-1])
E[-1] = -(phi[0]-phi[-2])
return E/(2*dx)
def accel(vx, vy, E, alpha, dt):
""" Accel in place
"""
vx[:] = vx + alpha*E*dt/2.
# vy is unchanged
def rotate(vx, vy, wc, dt):
""" Rotate in place
"""
c = np.cos(wc*dt)
s = np.sin(wc*dt)
vx_new = c*vx + s*vy
vy_new = -s*vx + c*vy
vx[:] = vx_new
vy[:] = vy_new
def normalize(x, L):
""" Keep x in [0,L), assuming a periodic domain
"""
# The order here is significant because of rounding
# If x<0 is very close to 0, then float(x+L)=L
while len(x[x<0])>0 or len(x[x>=L])>0:
x[x<0] = x[x<0] + L
x[x>=L] = x[x>=L] - L
def move(xp, vx, vy, dt, L, do_move=None):
""" Move in place
"""
if do_move is None:
xp[:] = xp + dt*vx
else:
xp[do_move] = xp[do_move] + dt*vx[do_move]
normalize(xp, L)
def pic(species, nx, dx, nt, dt, L, B0, solver_method="FFT",
weight_method="CIC",
interp_method="CIC"):
N = 0
for s in species: N += s.N
q, qm, wc, xp, vx, vy = [np.zeros(N) for _ in range(6)]
do_move = np.ndarray((N,), dtype=np.bool)
do_move[:] = False
count = 0 # Trailing count
for s in species:
q[count:count+s.N] = s.q
qm[count:count+s.N] = s.q/s.m
wc[count:count+s.N] = (s.q/s.m)*B0
xp[count:count+s.N] = s.x0
vx[count:count+s.N] = s.vx0
vy[count:count+s.N] = s.vy0
do_move[count:count+s.N] = s.m>0
count += s.N
# store the results at each time step
xpa = np.zeros((nt+1, N))
vxa = np.zeros((nt+1, N))
vya = np.zeros((nt+1, N))
Ea = np.zeros((nt+1, nx))
phia = np.zeros((nt+1, nx))
rhoa = np.zeros((nt+1, nx))
# Main solution loop
# Init half step back
rho = weight(xp, q, nx, L, method=weight_method)/dx
phi = poisson_solve(rho/epi0, dx, method=solver_method)
E0 = calc_E(phi, dx)
E = interp(E0, xp, nx, L, method=interp_method)
rotate(vx, vy, -wc, dt)
accel(vx, vy, E, -qm, dt)
xpa[0], vxa[0], vya[0] = xp, vx, vy
Ea[0], phia[0], rhoa[0] = E0, phi, rho
for i in range(1, nt+1):
# Update velocity
accel(vx, vy, E, qm, dt)
rotate(vx, vy, wc, dt)
accel(vx, vy, E, qm, dt)
# Update position
move(xp, vx, vy, dt, L, do_move=do_move)
rho = weight(xp, q, nx, L, method=weight_method)/dx
phi = poisson_solve(rho/epi0, dx, method=solver_method)
E0 = calc_E(phi, dx)
E = interp(E0, xp, nx, L, method=interp_method)
xpa[i], vxa[i], vya[i] = xp, vx, vy
Ea[i], phia[i], rhoa[i] = E0, phi, rho
return (xpa, vxa, vya, Ea, phia, rhoa)
| shigh/pyes1 | pyes1/pic1d2v.py | Python | gpl-2.0 | 5,516 |
package com.kamildanak.minecraft.safe.init;
import com.kamildanak.minecraft.safe.block.BlockSafe;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
public class SafeBlocks {
public static final BlockSafe SAFE;
static final Block[] BLOCKS;
static {
SAFE = new BlockSafe("safe", Material.GLASS);
BLOCKS = new Block[]{SAFE};
}
}
| kamilx3/Safe | src/main/java/com/kamildanak/minecraft/safe/init/SafeBlocks.java | Java | gpl-2.0 | 391 |
'use strict';
angular.module('<%=project.name.a()%>App')
.config(function ($stateProvider) {
$stateProvider
.state('entity', {
abstract: true,
parent: 'site'
});
});
| gen-js-bundles/angularjs-springboot-mongodb | templates/{srcWeb}/scripts/app/entities/entity.js | JavaScript | gpl-2.0 | 239 |
#include "./downloaditemdelegate.h"
#include <syncthingmodel/syncthingdownloadmodel.h>
#include <syncthingmodel/syncthingicons.h>
#include <qtforkawesome/icon.h>
#include <qtforkawesome/renderer.h>
#include <QApplication>
#include <QBrush>
#include <QFontMetrics>
#include <QPainter>
#include <QPalette>
#include <QPixmap>
#include <QStyle>
#include <QStyleOptionViewItem>
#include <QTextOption>
#include <iostream>
using namespace std;
using namespace Data;
namespace QtGui {
inline int centerObj(int avail, int size)
{
return (avail - size) / 2;
}
DownloadItemDelegate::DownloadItemDelegate(QObject *parent)
: QStyledItemDelegate(parent)
{
}
void DownloadItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
// init style options to use drawControl(), except for the text
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
opt.textElideMode = Qt::ElideNone; // elide manually
opt.features = QStyleOptionViewItem::None;
if (index.parent().isValid()) {
opt.displayAlignment = Qt::AlignTop | Qt::AlignLeft;
opt.decorationSize = QSize(option.rect.height(), option.rect.height());
opt.features |= QStyleOptionViewItem::HasDecoration;
opt.text = option.fontMetrics.elidedText(opt.text, Qt::ElideMiddle, opt.rect.width() - opt.rect.height() - 26);
} else {
opt.text = option.fontMetrics.elidedText(opt.text, Qt::ElideMiddle, opt.rect.width() / 2 - 4);
}
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &opt, painter);
// draw progress bar
const QAbstractItemModel *model = index.model();
QStyleOptionProgressBar progressBarOption;
progressBarOption.state = option.state;
progressBarOption.direction = option.direction;
progressBarOption.rect = option.rect;
if (index.parent().isValid()) {
progressBarOption.rect.setX(opt.rect.x() + opt.rect.height() + 4);
progressBarOption.rect.setY(opt.rect.y() + opt.rect.height() / 2);
} else {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
progressBarOption.rect.setX(opt.rect.x() + opt.fontMetrics.horizontalAdvance(opt.text) + 6);
#else
progressBarOption.rect.setX(opt.rect.x() + opt.fontMetrics.width(opt.text) + 6);
#endif
progressBarOption.rect.setWidth(progressBarOption.rect.width() - 18);
}
progressBarOption.textAlignment = Qt::AlignCenter;
progressBarOption.textVisible = true;
if (option.state & QStyle::State_Selected) {
progressBarOption.palette.setBrush(QPalette::WindowText, option.palette.brush(QPalette::HighlightedText));
}
progressBarOption.progress = model->data(index, SyncthingDownloadModel::ItemPercentage).toInt();
progressBarOption.minimum = 0;
progressBarOption.maximum = 100;
progressBarOption.text = model->data(index, SyncthingDownloadModel::ItemProgressLabel).toString();
QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter);
// draw buttons
int buttonY = option.rect.y();
if (!index.parent().isValid()) {
buttonY += centerObj(progressBarOption.rect.height(), 16);
}
IconManager::instance().forkAwesomeRenderer().render(
QtForkAwesome::Icon::Folder, painter, QRect(option.rect.right() - 16, buttonY, 16, 16), QGuiApplication::palette().color(QPalette::Text));
// draw file icon
if (index.parent().isValid()) {
const int fileIconHeight = option.rect.height() - 2;
painter->drawPixmap(option.rect.left(), option.rect.y() + 1, fileIconHeight, fileIconHeight,
model->data(index, Qt::DecorationRole).value<QIcon>().pixmap(fileIconHeight));
}
}
QSize DownloadItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QSize defaultSize(QStyledItemDelegate::sizeHint(option, index));
if (index.parent().isValid()) {
defaultSize.setHeight(defaultSize.height() + defaultSize.height() - 12);
}
return defaultSize;
}
} // namespace QtGui
| Martchus/syncthingtray | tray/gui/downloaditemdelegate.cpp | C++ | gpl-2.0 | 4,059 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "FastMixer"
//#define LOG_NDEBUG 0
#include <sys/atomics.h>
#include <time.h>
#include <utils/Log.h>
#include <utils/Trace.h>
#include <system/audio.h>
#ifdef FAST_MIXER_STATISTICS
#include <cpustats/CentralTendencyStatistics.h>
#ifdef CPU_FREQUENCY_STATISTICS
#include <cpustats/ThreadCpuUsage.h>
#endif
#endif
#include "AudioMixer.h"
#include "FastMixer.h"
#define FAST_HOT_IDLE_NS 1000000L // 1 ms: time to sleep while hot idling
#define FAST_DEFAULT_NS 999999999L // ~1 sec: default time to sleep
#define MIN_WARMUP_CYCLES 2 // minimum number of loop cycles to wait for warmup
#define MAX_WARMUP_CYCLES 10 // maximum number of loop cycles to wait for warmup
namespace android {
// Fast mixer thread
bool FastMixer::threadLoop()
{
static const FastMixerState initial;
const FastMixerState *previous = &initial, *current = &initial;
FastMixerState preIdle; // copy of state before we went into idle
struct timespec oldTs = {0, 0};
bool oldTsValid = false;
long slopNs = 0; // accumulated time we've woken up too early (> 0) or too late (< 0)
long sleepNs = -1; // -1: busy wait, 0: sched_yield, > 0: nanosleep
int fastTrackNames[FastMixerState::kMaxFastTracks]; // handles used by mixer to identify tracks
int generations[FastMixerState::kMaxFastTracks]; // last observed mFastTracks[i].mGeneration
unsigned i;
for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
fastTrackNames[i] = -1;
generations[i] = 0;
}
NBAIO_Sink *outputSink = NULL;
int outputSinkGen = 0;
AudioMixer* mixer = NULL;
short *mixBuffer = NULL;
enum {UNDEFINED, MIXED, ZEROED} mixBufferState = UNDEFINED;
NBAIO_Format format = Format_Invalid;
unsigned sampleRate = 0;
int fastTracksGen = 0;
long periodNs = 0; // expected period; the time required to render one mix buffer
long underrunNs = 0; // underrun likely when write cycle is greater than this value
long overrunNs = 0; // overrun likely when write cycle is less than this value
long forceNs = 0; // if overrun detected, force the write cycle to take this much time
long warmupNs = 0; // warmup complete when write cycle is greater than to this value
FastMixerDumpState dummyDumpState, *dumpState = &dummyDumpState;
bool ignoreNextOverrun = true; // used to ignore initial overrun and first after an underrun
#ifdef FAST_MIXER_STATISTICS
struct timespec oldLoad = {0, 0}; // previous value of clock_gettime(CLOCK_THREAD_CPUTIME_ID)
bool oldLoadValid = false; // whether oldLoad is valid
uint32_t bounds = 0;
bool full = false; // whether we have collected at least kSamplingN samples
#ifdef CPU_FREQUENCY_STATISTICS
ThreadCpuUsage tcu; // for reading the current CPU clock frequency in kHz
#endif
#endif
unsigned coldGen = 0; // last observed mColdGen
bool isWarm = false; // true means ready to mix, false means wait for warmup before mixing
struct timespec measuredWarmupTs = {0, 0}; // how long did it take for warmup to complete
uint32_t warmupCycles = 0; // counter of number of loop cycles required to warmup
NBAIO_Sink* teeSink = NULL; // if non-NULL, then duplicate write() to this non-blocking sink
for (;;) {
// either nanosleep, sched_yield, or busy wait
if (sleepNs >= 0) {
if (sleepNs > 0) {
ALOG_ASSERT(sleepNs < 1000000000);
const struct timespec req = {0, sleepNs};
nanosleep(&req, NULL);
} else {
sched_yield();
}
}
// default to long sleep for next cycle
sleepNs = FAST_DEFAULT_NS;
// poll for state change
const FastMixerState *next = mSQ.poll();
if (next == NULL) {
// continue to use the default initial state until a real state is available
ALOG_ASSERT(current == &initial && previous == &initial);
next = current;
}
FastMixerState::Command command = next->mCommand;
if (next != current) {
// As soon as possible of learning of a new dump area, start using it
dumpState = next->mDumpState != NULL ? next->mDumpState : &dummyDumpState;
teeSink = next->mTeeSink;
// We want to always have a valid reference to the previous (non-idle) state.
// However, the state queue only guarantees access to current and previous states.
// So when there is a transition from a non-idle state into an idle state, we make a
// copy of the last known non-idle state so it is still available on return from idle.
// The possible transitions are:
// non-idle -> non-idle update previous from current in-place
// non-idle -> idle update previous from copy of current
// idle -> idle don't update previous
// idle -> non-idle don't update previous
if (!(current->mCommand & FastMixerState::IDLE)) {
if (command & FastMixerState::IDLE) {
preIdle = *current;
current = &preIdle;
oldTsValid = false;
#ifdef FAST_MIXER_STATISTICS
oldLoadValid = false;
#endif
ignoreNextOverrun = true;
}
previous = current;
}
current = next;
}
#if !LOG_NDEBUG
next = NULL; // not referenced again
#endif
dumpState->mCommand = command;
switch (command) {
case FastMixerState::INITIAL:
case FastMixerState::HOT_IDLE:
sleepNs = FAST_HOT_IDLE_NS;
continue;
case FastMixerState::COLD_IDLE:
// only perform a cold idle command once
// FIXME consider checking previous state and only perform if previous != COLD_IDLE
if (current->mColdGen != coldGen) {
int32_t *coldFutexAddr = current->mColdFutexAddr;
ALOG_ASSERT(coldFutexAddr != NULL);
int32_t old = android_atomic_dec(coldFutexAddr);
if (old <= 0) {
__futex_syscall4(coldFutexAddr, FUTEX_WAIT_PRIVATE, old - 1, NULL);
}
// This may be overly conservative; there could be times that the normal mixer
// requests such a brief cold idle that it doesn't require resetting this flag.
isWarm = false;
measuredWarmupTs.tv_sec = 0;
measuredWarmupTs.tv_nsec = 0;
warmupCycles = 0;
sleepNs = -1;
coldGen = current->mColdGen;
#ifdef FAST_MIXER_STATISTICS
bounds = 0;
full = false;
#endif
oldTsValid = !clock_gettime(CLOCK_MONOTONIC, &oldTs);
} else {
sleepNs = FAST_HOT_IDLE_NS;
}
continue;
case FastMixerState::EXIT:
delete mixer;
delete[] mixBuffer;
return false;
case FastMixerState::MIX:
case FastMixerState::WRITE:
case FastMixerState::MIX_WRITE:
break;
default:
LOG_FATAL("bad command %d", command);
}
// there is a non-idle state available to us; did the state change?
size_t frameCount = current->mFrameCount;
if (current != previous) {
// handle state change here, but since we want to diff the state,
// we're prepared for previous == &initial the first time through
unsigned previousTrackMask;
// check for change in output HAL configuration
NBAIO_Format previousFormat = format;
if (current->mOutputSinkGen != outputSinkGen) {
outputSink = current->mOutputSink;
outputSinkGen = current->mOutputSinkGen;
if (outputSink == NULL) {
format = Format_Invalid;
sampleRate = 0;
} else {
format = outputSink->format();
sampleRate = Format_sampleRate(format);
ALOG_ASSERT(Format_channelCount(format) == 2);
}
dumpState->mSampleRate = sampleRate;
}
if ((format != previousFormat) || (frameCount != previous->mFrameCount)) {
// FIXME to avoid priority inversion, don't delete here
delete mixer;
mixer = NULL;
delete[] mixBuffer;
mixBuffer = NULL;
if (frameCount > 0 && sampleRate > 0) {
// FIXME new may block for unbounded time at internal mutex of the heap
// implementation; it would be better to have normal mixer allocate for us
// to avoid blocking here and to prevent possible priority inversion
mixer = new AudioMixer(frameCount, sampleRate, FastMixerState::kMaxFastTracks);
mixBuffer = new short[frameCount * 2];
periodNs = (frameCount * 1000000000LL) / sampleRate; // 1.00
underrunNs = (frameCount * 1750000000LL) / sampleRate; // 1.75
overrunNs = (frameCount * 500000000LL) / sampleRate; // 0.50
forceNs = (frameCount * 950000000LL) / sampleRate; // 0.95
warmupNs = (frameCount * 500000000LL) / sampleRate; // 0.50
} else {
periodNs = 0;
underrunNs = 0;
overrunNs = 0;
forceNs = 0;
warmupNs = 0;
}
mixBufferState = UNDEFINED;
#if !LOG_NDEBUG
for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
fastTrackNames[i] = -1;
}
#endif
// we need to reconfigure all active tracks
previousTrackMask = 0;
fastTracksGen = current->mFastTracksGen - 1;
dumpState->mFrameCount = frameCount;
} else {
previousTrackMask = previous->mTrackMask;
}
// check for change in active track set
unsigned currentTrackMask = current->mTrackMask;
dumpState->mTrackMask = currentTrackMask;
if (current->mFastTracksGen != fastTracksGen) {
ALOG_ASSERT(mixBuffer != NULL);
int name;
// process removed tracks first to avoid running out of track names
unsigned removedTracks = previousTrackMask & ~currentTrackMask;
while (removedTracks != 0) {
i = __builtin_ctz(removedTracks);
removedTracks &= ~(1 << i);
const FastTrack* fastTrack = ¤t->mFastTracks[i];
ALOG_ASSERT(fastTrack->mBufferProvider == NULL);
if (mixer != NULL) {
name = fastTrackNames[i];
ALOG_ASSERT(name >= 0);
mixer->deleteTrackName(name);
}
#if !LOG_NDEBUG
fastTrackNames[i] = -1;
#endif
// don't reset track dump state, since other side is ignoring it
generations[i] = fastTrack->mGeneration;
}
// now process added tracks
unsigned addedTracks = currentTrackMask & ~previousTrackMask;
while (addedTracks != 0) {
i = __builtin_ctz(addedTracks);
addedTracks &= ~(1 << i);
const FastTrack* fastTrack = ¤t->mFastTracks[i];
AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
ALOG_ASSERT(bufferProvider != NULL && fastTrackNames[i] == -1);
if (mixer != NULL) {
// calling getTrackName with default channel mask and a random invalid
// sessionId (no effects here)
name = mixer->getTrackName(AUDIO_CHANNEL_OUT_STEREO, -555);
ALOG_ASSERT(name >= 0);
fastTrackNames[i] = name;
mixer->setBufferProvider(name, bufferProvider);
mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
(void *) mixBuffer);
// newly allocated track names default to full scale volume
if (fastTrack->mSampleRate != 0 && fastTrack->mSampleRate != sampleRate) {
mixer->setParameter(name, AudioMixer::RESAMPLE,
AudioMixer::SAMPLE_RATE, (void*) fastTrack->mSampleRate);
}
mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
(void *) fastTrack->mChannelMask);
mixer->enable(name);
}
generations[i] = fastTrack->mGeneration;
}
// finally process modified tracks; these use the same slot
// but may have a different buffer provider or volume provider
unsigned modifiedTracks = currentTrackMask & previousTrackMask;
while (modifiedTracks != 0) {
i = __builtin_ctz(modifiedTracks);
modifiedTracks &= ~(1 << i);
const FastTrack* fastTrack = ¤t->mFastTracks[i];
if (fastTrack->mGeneration != generations[i]) {
AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
ALOG_ASSERT(bufferProvider != NULL);
if (mixer != NULL) {
name = fastTrackNames[i];
ALOG_ASSERT(name >= 0);
mixer->setBufferProvider(name, bufferProvider);
if (fastTrack->mVolumeProvider == NULL) {
mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
(void *)0x1000);
mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
(void *)0x1000);
}
if (fastTrack->mSampleRate != 0 &&
fastTrack->mSampleRate != sampleRate) {
mixer->setParameter(name, AudioMixer::RESAMPLE,
AudioMixer::SAMPLE_RATE, (void*) fastTrack->mSampleRate);
} else {
mixer->setParameter(name, AudioMixer::RESAMPLE,
AudioMixer::REMOVE, NULL);
}
mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
(void *) fastTrack->mChannelMask);
// already enabled
}
generations[i] = fastTrack->mGeneration;
}
}
fastTracksGen = current->mFastTracksGen;
dumpState->mNumTracks = popcount(currentTrackMask);
}
#if 1 // FIXME shouldn't need this
// only process state change once
previous = current;
#endif
}
// do work using current state here
if ((command & FastMixerState::MIX) && (mixer != NULL) && isWarm) {
ALOG_ASSERT(mixBuffer != NULL);
// for each track, update volume and check for underrun
unsigned currentTrackMask = current->mTrackMask;
while (currentTrackMask != 0) {
i = __builtin_ctz(currentTrackMask);
currentTrackMask &= ~(1 << i);
const FastTrack* fastTrack = ¤t->mFastTracks[i];
int name = fastTrackNames[i];
ALOG_ASSERT(name >= 0);
if (fastTrack->mVolumeProvider != NULL) {
uint32_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
(void *)(vlr & 0xFFFF));
mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
(void *)(vlr >> 16));
}
// FIXME The current implementation of framesReady() for fast tracks
// takes a tryLock, which can block
// up to 1 ms. If enough active tracks all blocked in sequence, this would result
// in the overall fast mix cycle being delayed. Should use a non-blocking FIFO.
size_t framesReady = fastTrack->mBufferProvider->framesReady();
#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
// I wish we had formatted trace names
char traceName[16];
strcpy(traceName, "framesReady");
traceName[11] = i + (i < 10 ? '0' : 'A' - 10);
traceName[12] = '\0';
ATRACE_INT(traceName, framesReady);
#endif
FastTrackDump *ftDump = &dumpState->mTracks[i];
FastTrackUnderruns underruns = ftDump->mUnderruns;
if (framesReady < frameCount) {
if (framesReady == 0) {
underruns.mBitFields.mEmpty++;
underruns.mBitFields.mMostRecent = UNDERRUN_EMPTY;
mixer->disable(name);
} else {
// allow mixing partial buffer
underruns.mBitFields.mPartial++;
underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL;
mixer->enable(name);
}
} else {
underruns.mBitFields.mFull++;
underruns.mBitFields.mMostRecent = UNDERRUN_FULL;
mixer->enable(name);
}
ftDump->mUnderruns = underruns;
ftDump->mFramesReady = framesReady;
}
int64_t pts;
if (outputSink == NULL || (OK != outputSink->getNextWriteTimestamp(&pts)))
pts = AudioBufferProvider::kInvalidPTS;
// process() is CPU-bound
mixer->process(pts);
mixBufferState = MIXED;
} else if (mixBufferState == MIXED) {
mixBufferState = UNDEFINED;
}
bool attemptedWrite = false;
//bool didFullWrite = false; // dumpsys could display a count of partial writes
if ((command & FastMixerState::WRITE) && (outputSink != NULL) && (mixBuffer != NULL)) {
if (mixBufferState == UNDEFINED) {
memset(mixBuffer, 0, frameCount * 2 * sizeof(short));
mixBufferState = ZEROED;
}
if (teeSink != NULL) {
(void) teeSink->write(mixBuffer, frameCount);
}
// FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink,
// but this code should be modified to handle both non-blocking and blocking sinks
dumpState->mWriteSequence++;
#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Tracer::traceBegin(ATRACE_TAG, "write");
#endif
ssize_t framesWritten = outputSink->write(mixBuffer, frameCount);
#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Tracer::traceEnd(ATRACE_TAG);
#endif
dumpState->mWriteSequence++;
if (framesWritten >= 0) {
ALOG_ASSERT(framesWritten <= frameCount);
dumpState->mFramesWritten += framesWritten;
//if ((size_t) framesWritten == frameCount) {
// didFullWrite = true;
//}
} else {
dumpState->mWriteErrors++;
}
attemptedWrite = true;
// FIXME count # of writes blocked excessively, CPU usage, etc. for dump
}
// To be exactly periodic, compute the next sleep time based on current time.
// This code doesn't have long-term stability when the sink is non-blocking.
// FIXME To avoid drift, use the local audio clock or watch the sink's fill status.
struct timespec newTs;
int rc = clock_gettime(CLOCK_MONOTONIC, &newTs);
if (rc == 0) {
if (oldTsValid) {
time_t sec = newTs.tv_sec - oldTs.tv_sec;
long nsec = newTs.tv_nsec - oldTs.tv_nsec;
ALOGE_IF(sec < 0 || (sec == 0 && nsec < 0),
"clock_gettime(CLOCK_MONOTONIC) failed: was %ld.%09ld but now %ld.%09ld",
oldTs.tv_sec, oldTs.tv_nsec, newTs.tv_sec, newTs.tv_nsec);
if (nsec < 0) {
--sec;
nsec += 1000000000;
}
// To avoid an initial underrun on fast tracks after exiting standby,
// do not start pulling data from tracks and mixing until warmup is complete.
// Warmup is considered complete after the earlier of:
// MIN_WARMUP_CYCLES write() attempts and last one blocks for at least warmupNs
// MAX_WARMUP_CYCLES write() attempts.
// This is overly conservative, but to get better accuracy requires a new HAL API.
if (!isWarm && attemptedWrite) {
measuredWarmupTs.tv_sec += sec;
measuredWarmupTs.tv_nsec += nsec;
if (measuredWarmupTs.tv_nsec >= 1000000000) {
measuredWarmupTs.tv_sec++;
measuredWarmupTs.tv_nsec -= 1000000000;
}
++warmupCycles;
if ((nsec > warmupNs && warmupCycles >= MIN_WARMUP_CYCLES) ||
(warmupCycles >= MAX_WARMUP_CYCLES)) {
isWarm = true;
dumpState->mMeasuredWarmupTs = measuredWarmupTs;
dumpState->mWarmupCycles = warmupCycles;
}
}
sleepNs = -1;
if (isWarm) {
if (sec > 0 || nsec > underrunNs) {
#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
ScopedTrace st(ATRACE_TAG, "underrun");
#endif
// FIXME only log occasionally
ALOGV("underrun: time since last cycle %d.%03ld sec",
(int) sec, nsec / 1000000L);
dumpState->mUnderruns++;
ignoreNextOverrun = true;
} else if (nsec < overrunNs) {
if (ignoreNextOverrun) {
ignoreNextOverrun = false;
} else {
// FIXME only log occasionally
ALOGV("overrun: time since last cycle %d.%03ld sec",
(int) sec, nsec / 1000000L);
dumpState->mOverruns++;
}
// This forces a minimum cycle time. It:
// - compensates for an audio HAL with jitter due to sample rate conversion
// - works with a variable buffer depth audio HAL that never pulls at a rate
// < than overrunNs per buffer.
// - recovers from overrun immediately after underrun
// It doesn't work with a non-blocking audio HAL.
sleepNs = forceNs - nsec;
} else {
ignoreNextOverrun = false;
}
}
#ifdef FAST_MIXER_STATISTICS
if (isWarm) {
// advance the FIFO queue bounds
size_t i = bounds & (FastMixerDumpState::kSamplingN - 1);
bounds = (bounds & 0xFFFF0000) | ((bounds + 1) & 0xFFFF);
if (full) {
bounds += 0x10000;
} else if (!(bounds & (FastMixerDumpState::kSamplingN - 1))) {
full = true;
}
// compute the delta value of clock_gettime(CLOCK_MONOTONIC)
uint32_t monotonicNs = nsec;
if (sec > 0 && sec < 4) {
monotonicNs += sec * 1000000000;
}
// compute the raw CPU load = delta value of clock_gettime(CLOCK_THREAD_CPUTIME_ID)
uint32_t loadNs = 0;
struct timespec newLoad;
rc = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &newLoad);
if (rc == 0) {
if (oldLoadValid) {
sec = newLoad.tv_sec - oldLoad.tv_sec;
nsec = newLoad.tv_nsec - oldLoad.tv_nsec;
if (nsec < 0) {
--sec;
nsec += 1000000000;
}
loadNs = nsec;
if (sec > 0 && sec < 4) {
loadNs += sec * 1000000000;
}
} else {
// first time through the loop
oldLoadValid = true;
}
oldLoad = newLoad;
}
#ifdef CPU_FREQUENCY_STATISTICS
// get the absolute value of CPU clock frequency in kHz
int cpuNum = sched_getcpu();
uint32_t kHz = tcu.getCpukHz(cpuNum);
kHz = (kHz << 4) | (cpuNum & 0xF);
#endif
// save values in FIFO queues for dumpsys
// these stores #1, #2, #3 are not atomic with respect to each other,
// or with respect to store #4 below
dumpState->mMonotonicNs[i] = monotonicNs;
dumpState->mLoadNs[i] = loadNs;
#ifdef CPU_FREQUENCY_STATISTICS
dumpState->mCpukHz[i] = kHz;
#endif
// this store #4 is not atomic with respect to stores #1, #2, #3 above, but
// the newest open and oldest closed halves are atomic with respect to each other
dumpState->mBounds = bounds;
#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
ATRACE_INT("cycle_ms", monotonicNs / 1000000);
ATRACE_INT("load_us", loadNs / 1000);
#endif
}
#endif
} else {
// first time through the loop
oldTsValid = true;
sleepNs = periodNs;
ignoreNextOverrun = true;
}
oldTs = newTs;
} else {
// monotonic clock is broken
oldTsValid = false;
sleepNs = periodNs;
}
} // for (;;)
// never return 'true'; Thread::_threadLoop() locks mutex which can result in priority inversion
}
FastMixerDumpState::FastMixerDumpState() :
mCommand(FastMixerState::INITIAL), mWriteSequence(0), mFramesWritten(0),
mNumTracks(0), mWriteErrors(0), mUnderruns(0), mOverruns(0),
mSampleRate(0), mFrameCount(0), /* mMeasuredWarmupTs({0, 0}), */ mWarmupCycles(0),
mTrackMask(0)
#ifdef FAST_MIXER_STATISTICS
, mBounds(0)
#endif
{
mMeasuredWarmupTs.tv_sec = 0;
mMeasuredWarmupTs.tv_nsec = 0;
#ifdef FAST_MIXER_STATISTICS
// sample arrays aren't accessed atomically with respect to the bounds,
// so clearing reduces chance for dumpsys to read random uninitialized samples
memset(&mMonotonicNs, 0, sizeof(mMonotonicNs));
memset(&mLoadNs, 0, sizeof(mLoadNs));
#ifdef CPU_FREQUENCY_STATISTICS
memset(&mCpukHz, 0, sizeof(mCpukHz));
#endif
#endif
}
FastMixerDumpState::~FastMixerDumpState()
{
}
// helper function called by qsort()
static int compare_uint32_t(const void *pa, const void *pb)
{
uint32_t a = *(const uint32_t *)pa;
uint32_t b = *(const uint32_t *)pb;
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
}
void FastMixerDumpState::dump(int fd)
{
if (mCommand == FastMixerState::INITIAL) {
fdprintf(fd, "FastMixer not initialized\n");
return;
}
#define COMMAND_MAX 32
char string[COMMAND_MAX];
switch (mCommand) {
case FastMixerState::INITIAL:
strcpy(string, "INITIAL");
break;
case FastMixerState::HOT_IDLE:
strcpy(string, "HOT_IDLE");
break;
case FastMixerState::COLD_IDLE:
strcpy(string, "COLD_IDLE");
break;
case FastMixerState::EXIT:
strcpy(string, "EXIT");
break;
case FastMixerState::MIX:
strcpy(string, "MIX");
break;
case FastMixerState::WRITE:
strcpy(string, "WRITE");
break;
case FastMixerState::MIX_WRITE:
strcpy(string, "MIX_WRITE");
break;
default:
snprintf(string, COMMAND_MAX, "%d", mCommand);
break;
}
double measuredWarmupMs = (mMeasuredWarmupTs.tv_sec * 1000.0) +
(mMeasuredWarmupTs.tv_nsec / 1000000.0);
double mixPeriodSec = (double) mFrameCount / (double) mSampleRate;
fdprintf(fd, "FastMixer command=%s writeSequence=%u framesWritten=%u\n"
" numTracks=%u writeErrors=%u underruns=%u overruns=%u\n"
" sampleRate=%u frameCount=%u measuredWarmup=%.3g ms, warmupCycles=%u\n"
" mixPeriod=%.2f ms\n",
string, mWriteSequence, mFramesWritten,
mNumTracks, mWriteErrors, mUnderruns, mOverruns,
mSampleRate, mFrameCount, measuredWarmupMs, mWarmupCycles,
mixPeriodSec * 1e3);
#ifdef FAST_MIXER_STATISTICS
// find the interval of valid samples
uint32_t bounds = mBounds;
uint32_t newestOpen = bounds & 0xFFFF;
uint32_t oldestClosed = bounds >> 16;
uint32_t n = (newestOpen - oldestClosed) & 0xFFFF;
if (n > kSamplingN) {
ALOGE("too many samples %u", n);
n = kSamplingN;
}
// statistics for monotonic (wall clock) time, thread raw CPU load in time, CPU clock frequency,
// and adjusted CPU load in MHz normalized for CPU clock frequency
CentralTendencyStatistics wall, loadNs;
#ifdef CPU_FREQUENCY_STATISTICS
CentralTendencyStatistics kHz, loadMHz;
uint32_t previousCpukHz = 0;
#endif
// Assuming a normal distribution for cycle times, three standard deviations on either side of
// the mean account for 99.73% of the population. So if we take each tail to be 1/1000 of the
// sample set, we get 99.8% combined, or close to three standard deviations.
static const uint32_t kTailDenominator = 1000;
uint32_t *tail = n >= kTailDenominator ? new uint32_t[n] : NULL;
// loop over all the samples
for (uint32_t j = 0; j < n; ++j) {
size_t i = oldestClosed++ & (kSamplingN - 1);
uint32_t wallNs = mMonotonicNs[i];
if (tail != NULL) {
tail[j] = wallNs;
}
wall.sample(wallNs);
uint32_t sampleLoadNs = mLoadNs[i];
loadNs.sample(sampleLoadNs);
#ifdef CPU_FREQUENCY_STATISTICS
uint32_t sampleCpukHz = mCpukHz[i];
// skip bad kHz samples
if ((sampleCpukHz & ~0xF) != 0) {
kHz.sample(sampleCpukHz >> 4);
if (sampleCpukHz == previousCpukHz) {
double megacycles = (double) sampleLoadNs * (double) (sampleCpukHz >> 4) * 1e-12;
double adjMHz = megacycles / mixPeriodSec; // _not_ wallNs * 1e9
loadMHz.sample(adjMHz);
}
}
previousCpukHz = sampleCpukHz;
#endif
}
fdprintf(fd, "Simple moving statistics over last %.1f seconds:\n", wall.n() * mixPeriodSec);
fdprintf(fd, " wall clock time in ms per mix cycle:\n"
" mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
wall.mean()*1e-6, wall.minimum()*1e-6, wall.maximum()*1e-6, wall.stddev()*1e-6);
fdprintf(fd, " raw CPU load in us per mix cycle:\n"
" mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
loadNs.mean()*1e-3, loadNs.minimum()*1e-3, loadNs.maximum()*1e-3,
loadNs.stddev()*1e-3);
#ifdef CPU_FREQUENCY_STATISTICS
fdprintf(fd, " CPU clock frequency in MHz:\n"
" mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
kHz.mean()*1e-3, kHz.minimum()*1e-3, kHz.maximum()*1e-3, kHz.stddev()*1e-3);
fdprintf(fd, " adjusted CPU load in MHz (i.e. normalized for CPU clock frequency):\n"
" mean=%.1f min=%.1f max=%.1f stddev=%.1f\n",
loadMHz.mean(), loadMHz.minimum(), loadMHz.maximum(), loadMHz.stddev());
#endif
if (tail != NULL) {
qsort(tail, n, sizeof(uint32_t), compare_uint32_t);
// assume same number of tail samples on each side, left and right
uint32_t count = n / kTailDenominator;
CentralTendencyStatistics left, right;
for (uint32_t i = 0; i < count; ++i) {
left.sample(tail[i]);
right.sample(tail[n - (i + 1)]);
}
fdprintf(fd, "Distribution of mix cycle times in ms for the tails (> ~3 stddev outliers):\n"
" left tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n"
" right tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
left.mean()*1e-6, left.minimum()*1e-6, left.maximum()*1e-6, left.stddev()*1e-6,
right.mean()*1e-6, right.minimum()*1e-6, right.maximum()*1e-6,
right.stddev()*1e-6);
delete[] tail;
}
#endif
// The active track mask and track states are updated non-atomically.
// So if we relied on isActive to decide whether to display,
// then we might display an obsolete track or omit an active track.
// Instead we always display all tracks, with an indication
// of whether we think the track is active.
uint32_t trackMask = mTrackMask;
fdprintf(fd, "Fast tracks: kMaxFastTracks=%u activeMask=%#x\n",
FastMixerState::kMaxFastTracks, trackMask);
fdprintf(fd, "Index Active Full Partial Empty Recent Ready\n");
for (uint32_t i = 0; i < FastMixerState::kMaxFastTracks; ++i, trackMask >>= 1) {
bool isActive = trackMask & 1;
const FastTrackDump *ftDump = &mTracks[i];
const FastTrackUnderruns& underruns = ftDump->mUnderruns;
const char *mostRecent;
switch (underruns.mBitFields.mMostRecent) {
case UNDERRUN_FULL:
mostRecent = "full";
break;
case UNDERRUN_PARTIAL:
mostRecent = "partial";
break;
case UNDERRUN_EMPTY:
mostRecent = "empty";
break;
default:
mostRecent = "?";
break;
}
fdprintf(fd, "%5u %6s %4u %7u %5u %7s %5u\n", i, isActive ? "yes" : "no",
(underruns.mBitFields.mFull) & UNDERRUN_MASK,
(underruns.mBitFields.mPartial) & UNDERRUN_MASK,
(underruns.mBitFields.mEmpty) & UNDERRUN_MASK,
mostRecent, ftDump->mFramesReady);
}
}
} // namespace android
| rex-xxx/mt6572_x201 | frameworks/av/services/audioflinger/FastMixer.cpp | C++ | gpl-2.0 | 36,413 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-02-09 08:44
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
dependencies = [
('statusboard', '0005_merge'),
]
operations = [
migrations.CreateModel(
name='Maintenance',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
('scheduled', models.DateTimeField()),
('name', models.CharField(max_length=255)),
('description', models.TextField()),
],
options={
'abstract': False,
},
),
]
| edigiacomo/django-statusboard | statusboard/migrations/0006_maintenance.py | Python | gpl-2.0 | 1,099 |
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import the Joomla modellist library
jimport('joomla.application.component.modeladmin');
/**
* HelloWorldList Model
*/
class RentalModelPayment extends JModelAdmin
{
/*
* Method to get the payment form
*
*/
public function getPaymentForm($data = array(), $loadData = true)
{
JForm::addFormPath(JPATH_LIBRARIES . '/frenchconnections/forms');
$form = $this->loadForm('com_rental.helloworld', 'payment', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
// TO DO - This is a bit messy - most likely should remove this method simply use
// if then else logic in getForm to determine the form to use. A separate
// method could be called to determine form to load based on layout etc
$data = JFactory::getApplication()->getUserState('com_rental.renewal.data', array());
$data['id'] = $id = $this->getState($this->getName() . '.id', '');
$form->bind($data);
return $form;
}
public function getForm($data = array(), $loadData = true)
{
JForm::addFormPath(JPATH_LIBRARIES . '/frenchconnections/forms');
$form = $this->loadForm('com_rental.helloworld', 'account', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
return $form;
}
public function getBillingDetails($data = array())
{
$model = JModelLegacy::getInstance('Property', 'RentalModel', array('ignore_request' => true));
$property_id = $data['id'];
$property = $model->getItem($property_id);
$owner_id = $property->created_by;
if (!$owner_id)
{
// Uh oh, no owner id. With out card billing details payment will fail anyway...
return $data;
}
$user = JFactory::getUser($owner_id);
// Get the dispatcher and load the user's plugins.
$dispatcher = JEventDispatcher::getInstance();
JPluginHelper::importPlugin('user');
$user_data = new JObject;
$user_data->id = $owner_id;
// Trigger the data preparation event.
$dispatcher->trigger('onContentPrepareData', array('com_users.user', &$user_data));
$data['BillingFirstnames'] = $user_data->firstname;
$data['BillingSurname'] = $user_data->surname;
$data['BillingAddress1'] = $user_data->address1;
$data['BillingAddress2'] = $user_data->address2;
$data['BillingCity'] = $user_data->city;
$data['BillingPostCode'] = $user_data->postal_code;
$data['BillingEmailAddress'] = $user->email;
$data['BillingCountry'] = $user_data->country;
$data['BillingState'] = $user_data->state;
return $data;
}
private function _getOWnerID(int $property_id = null)
{
}
public function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_rental.edit.listing.data', array());
// Which layout are we working on?
$layout = JFactory::getApplication()->input->get('layout', '', 'string');
// If this is a the payment layout/view then we need to pre-load some data into the form.
// In particular, we need the property listing id.
if ($layout == 'payment')
{
}
return $data;
}
/*
* param JForm $form The JForm instance for the view being edited
* param array $data The form data as derived from the view (may be empty)
*
* @return void
*
*/
protected function preprocessForm(JForm $form, $data)
{
// Get the input form data
$input = JFactory::getApplication()->input;
// And tease out whether the use_invoice_address field is ticked or not
$formData = $input->get('jform', array(), 'array');
$filter = JFilterInput::getInstance();
$use_invoice_address = $filter->clean($formData['use_invoice_address'], 'int');
if ($use_invoice_address)
{
// Make the billing details optional
$fieldset = $form->getFieldset('billing-details');
foreach ($fieldset as $field)
{
$form->setFieldAttribute($field->fieldname, 'required', 'false');
}
}
}
public function getTable($type = 'Property', $prefix = 'RentalTable', $options = array())
{
return JTable::getInstance($type, $prefix, $options);
}
}
| adster101/French-Connections- | administrator/components/com_rental/models/payment.php | PHP | gpl-2.0 | 4,322 |
<?php
class E_Register_NowLog__Admin {
public function __construct() {
add_action( 'wp_ajax_tribe_logging_controls', array( $this, 'listen' ) );
add_action( 'init', array( $this, 'serve_log_downloads' ) );
add_action( 'init', array( $this, 'register_script' ) );
}
/**
* Returns the HTML comprising the event log section for use in the
* Events > Settings > Help screen.
*
* @return string
*/
public function display_log() {
$log_choices = $this->get_available_logs();
$log_engines = $this->get_log_engines();
$log_levels = $this->get_logging_levels();
$log_entries = $this->get_log_entries();
$download_url = $this->get_log_url();
$this->setup_script();
ob_start();
include trailingslashit( E_Register_NowMain::instance()->plugin_path ) . 'src/admin-views/event-log.php';
return ob_get_clean();
}
/**
* Listens for changes to the event log settings updating and returning
* an appropriate response.
*/
public function listen() {
$fields = wp_parse_args( $_POST, array(
'check' => '',
'log-level' => '',
'log-engine' => '',
) );
foreach ( $fields as &$single_field ) {
$single_field = sanitize_text_field( $single_field );
}
if ( ! wp_verify_nonce( $fields['check'], 'logging-controls' ) ) {
return;
}
/**
* Fires before log settings are committed.
*
* This will not happen unless a nonce check has already passed.
*/
do_action( 'tribe_common_update_log_settings' );
$this->update_logging_level( $fields['log-level'] );
$this->update_logging_engine( $fields['log-engine'] );
/**
* Fires immediately after log settings have been committed.
*/
do_action( 'tribe_common_updated_log_settings' );
$data = array(
'logs' => $this->get_available_logs(),
);
if ( ! empty( $fields['log-view'] ) ) {
$data['entries'] = $this->get_log_entries( $fields['log-view'] );
}
wp_send_json_success( $data );
}
/**
* Sets the current logging level to the provided level (if it is a valid
* level, else will set the level to 'default').
*
* @param string $level
*/
protected function update_logging_level( $level ) {
$this->log_manager()->set_level( $level );
}
/**
* Sets the current logging engine to the provided class (if it is a valid
* and currently available logging class, else will set this to null - ie
* no logging).
*
* @param string $engine
*/
protected function update_logging_engine( $engine ) {
try {
$this->log_manager()->set_current_logger( $engine );
}
catch ( Exception $e ) {
// The class name did not relate to a valid logging engine
}
}
/**
* Register our script early.
*/
public function register_script() {
wp_register_script(
'tribe-common-logging-controls',
tribe_resource_url( 'admin-log-controls.js', false, 'common' ),
array( 'jquery' ),
E_Register_NowMain::VERSION,
true
);
}
/**
* Adds a script to handle the event log settings.
*/
protected function setup_script() {
wp_enqueue_script( 'tribe-common-logging-controls' );
wp_localize_script( 'tribe-common-logging-controls', 'tribe_logger_data', array(
'check' => wp_create_nonce( 'logging-controls' )
) );
}
/**
* Returns a list of logs that are available for perusal.
*
* @return array
*/
protected function get_available_logs() {
$available_logs = $this->current_logger()->list_available_logs();
if ( empty( $available_logs ) ) {
return array( '' => _x( 'None currently available', 'log selector', 'tribe-common' ) );
}
return $available_logs;
}
/**
* Returns a list of logging engines that are available for use.
*
* @return array
*/
protected function get_log_engines(){
$available_engines = $this->log_manager()->get_logging_engines();
if ( empty( $available_engines ) ) {
return array( '' => _x( 'None currently available', 'log engines', 'tribe-common' ) );
}
$engine_list = array();
foreach ( $available_engines as $class_name => $engine ) {
/**
* @var E_Register_NowLog__Logger $engine
*/
$engine_list[ $class_name ] = $engine->get_name();
}
return $engine_list;
}
/**
* Returns all log entries for the current or specified log.
*
* @return array
*/
protected function get_log_entries( $log = null ) {
$logger = $this->current_logger();
$logger->use_log( $log );
return $logger->retrieve();
}
/**
* Returns an array of logging levels arranged as key:value pairs, with
* each key being the level code and the value being the human-friendly
* description.
*
* @return array
*/
protected function get_logging_levels() {
$levels = array();
$available_levels = $this->log_manager()->get_logging_levels();
foreach ( $available_levels as $logging_level ) {
$levels[ $logging_level[0] ] = $logging_level[1];
}
return $levels;
}
/**
* Provides a URL that can be used to download the current or specified
* log.
*
* @param $log
*
* @return string
*/
protected function get_log_url( $log = null ) {
$query = array(
'tribe-common-log' => 'download',
'check' => wp_create_nonce( 'download_log' )
);
$log_download_url = add_query_arg( $query, get_admin_url( null, 'edit.php' ) );
return esc_url( $log_download_url );
}
/**
* Facilitate downloading of logs.
*/
public function serve_log_downloads() {
if ( empty( $_GET['tribe-common-log'] ) || 'download' !== $_GET['tribe-common-log'] ) {
return;
}
if ( ! wp_verify_nonce( @$_GET['check'], 'download_log' ) ) {
return;
}
if ( empty( $_GET['log'] ) || ! in_array( $_GET['log'], $this->get_available_logs() ) ) {
return;
}
$log_name = sanitize_file_name( $_GET['log'] );
$this->current_logger()->use_log( $log_name );
/**
* Provides an opportunity to modify the recommended filename for a downloaded
* log file.
*
* @param string $log_name
*/
$log_name = apply_filters( 'tribe_common_log_download_filename', $log_name );
header( 'Content-Disposition: attachment; filename="tribe-log-' . $log_name . '"' );
$output = fopen( 'php://output', 'w' );
foreach ( $this->current_logger()->retrieve() as $log_entry ) {
fputcsv( $output, $log_entry );
}
fclose( $output );
exit();
}
/**
* Returns a reference to the main log management object.
*
* @return E_Register_NowLog
*/
protected function log_manager() {
return E_Register_NowMain::instance()->log();
}
/**
* Returns the currently enabled logging object or null if it is not
* available.
*
* @return E_Register_NowLog__Logger|null
*/
protected function current_logger() {
return E_Register_NowMain::instance()->log()->get_current_logger();
}
} | romangrb/register-now-plugin | backup/event-tickets 1.2.3/common/src/e_register_now/Log/Admin.php | PHP | gpl-2.0 | 6,686 |
#ifndef UTIL_FACTORY_HPP
#define UTIL_FACTORY_HPP
#include "base.hpp"
#include <map>
#include "typeinfo.hpp"
namespace util
{
////////////////////////////////////////////////////////////////////////////////
// class template DefaultFactoryError
// Manages the "Unknown Type" error in an object factory
////////////////////////////////////////////////////////////////////////////////
template <typename IdentifierType, class AbstractProduct>
struct DefaultFactoryError
{
static AbstractProduct* onUnknownType(IdentifierType)
{
throw Exception("Unknown Type");
}
};
////////////////////////////////////////////////////////////////////////////////
// class template DefaultFactoryError
// Manages the "Unknown Type" error in an object factory
////////////////////////////////////////////////////////////////////////////////
template <typename IdentifierType, class AbstractProduct>
struct FactoryCreateFail
{
static AbstractProduct* onUnknownType(IdentifierType)
{
return 0;
}
};
////////////////////////////////////////////////////////////////////////////////
// class template Factory
// Implements a generic object factory
////////////////////////////////////////////////////////////////////////////////
//AbstractProduct* (*)()
template
<
class AbstractProduct,
typename IdentifierType,
typename ProductCreator = UtilFunction<AbstractProduct* ()>,
template<typename, class>
class FactoryErrorPolicy = FactoryCreateFail
>
class Factory
: public FactoryErrorPolicy<IdentifierType, AbstractProduct>
{
public:
bool Register(const IdentifierType& id, ProductCreator creator)
{
return associations_.insert(
typename IdToProductMap::value_type(id, creator)).second;
}
bool unRegister(const IdentifierType& id)
{
return associations_.erase(id) == 1;
}
AbstractProduct* createObject(const IdentifierType& id)
{
ProductCreator product_creator = creator(id);
return product_creator ? product_creator() : FactoryErrorPolicy<IdentifierType, AbstractProduct>::onUnknownType(id);
}
private:
ProductCreator creator(const IdentifierType& id)
{
typename IdToProductMap::const_iterator i = associations_.find(id);
if (i != associations_.end())
return i->second;
return ProductCreator();
}
private:
typedef std::map<IdentifierType, ProductCreator> IdToProductMap;
IdToProductMap associations_;
};
////////////////////////////////////////////////////////////////////////////////
// class template CloneFactory
// Implements a generic cloning factory
////////////////////////////////////////////////////////////////////////////////
template
<
class AbstractProduct,
class ProductCreator = UtilFunction<AbstractProduct* (AbstractProduct*)>,
template<typename, class>
class FactoryErrorPolicy = FactoryCreateFail
>
class CloneFactory
: public FactoryErrorPolicy<TypeInfo, AbstractProduct>
{
public:
bool Register(const TypeInfo& ti, ProductCreator creator)
{
return associations_.insert(
typename IdToProductMap::value_type(ti, creator)).second;
}
bool unRegister(const TypeInfo& id)
{
return associations_.erase(id) == 1;
}
AbstractProduct* createObject(AbstractProduct* model)
{
if (model == 0) return 0;
typename IdToProductMap::iterator i =
associations_.find(TypeInfo(typeid(*model)));
if (i != associations_.end())
return (i->second)(model);
return FactoryErrorPolicy<TypeInfo, AbstractProduct>::onUnknownType(typeid(*model));
}
private:
typedef std::map<TypeInfo, ProductCreator> IdToProductMap;
IdToProductMap associations_;
};
} // namespace util
#endif // UTIL_FACTORY_HPP
| joshua-meng/Util | src/util/factory.hpp | C++ | gpl-2.0 | 3,863 |
/* note: this requires gstreamer 0.10.x and a big list of plugins. */
/* it's currently hardcoded to use a big-endian alsasink as sink. */
#include <lib/base/ebase.h>
#include <lib/base/eerror.h>
#include <lib/base/init_num.h>
#include <lib/base/init.h>
#include <lib/base/nconfig.h>
#include <lib/base/object.h>
#include <lib/dvb/epgcache.h>
#include <lib/dvb/decoder.h>
#include <lib/components/file_eraser.h>
#include <lib/gui/esubtitle.h>
#include <lib/service/servicemp3.h>
#include <lib/service/service.h>
#include <lib/gdi/gpixmap.h>
#include <string>
#include <gst/gst.h>
#include <gst/pbutils/missing-plugins.h>
#include <sys/stat.h>
#define HTTP_TIMEOUT 30
/*
* UNUSED variable from service reference is now used as buffer flag for gstreamer
* REFTYPE:FLAGS:STYPE:SID:TSID:ONID:NS:PARENT_SID:PARENT_TSID:UNUSED
* D D X X X X X X X X
* 4097:0:1:0:0:0:0:0:0:0:URL:NAME (no buffering)
* 4097:0:1:0:0:0:0:0:0:1:URL:NAME (buffering enabled)
* 4097:0:1:0:0:0:0:0:0:3:URL:NAME (progressive download and buffering enabled)
*
* Progressive download requires buffering enabled, so it's mandatory to use flag 3 not 2
*/
typedef enum
{
BUFFERING_ENABLED = 0x00000001,
PROGRESSIVE_DOWNLOAD = 0x00000002
} eServiceMP3Flags;
typedef enum
{
GST_PLAY_FLAG_VIDEO = 0x00000001,
GST_PLAY_FLAG_AUDIO = 0x00000002,
GST_PLAY_FLAG_TEXT = 0x00000004,
GST_PLAY_FLAG_VIS = 0x00000008,
GST_PLAY_FLAG_SOFT_VOLUME = 0x00000010,
GST_PLAY_FLAG_NATIVE_AUDIO = 0x00000020,
GST_PLAY_FLAG_NATIVE_VIDEO = 0x00000040,
GST_PLAY_FLAG_DOWNLOAD = 0x00000080,
GST_PLAY_FLAG_BUFFERING = 0x00000100
} GstPlayFlags;
// eServiceFactoryMP3
/*
* gstreamer suffers from a bug causing sparse streams to loose sync, after pause/resume / skip
* see: https://bugzilla.gnome.org/show_bug.cgi?id=619434
* As a workaround, we run the subsink in sync=false mode
*/
#if GST_VERSION_MAJOR >= 1
#undef GSTREAMER_SUBTITLE_SYNC_MODE_BUG
#else
#define GSTREAMER_SUBTITLE_SYNC_MODE_BUG
#endif
/**/
eServiceFactoryMP3::eServiceFactoryMP3()
{
ePtr<eServiceCenter> sc;
eServiceCenter::getPrivInstance(sc);
if (sc)
{
std::list<std::string> extensions;
extensions.push_back("dts");
extensions.push_back("mp2");
extensions.push_back("mp3");
extensions.push_back("ogg");
extensions.push_back("ogm");
extensions.push_back("ogv");
extensions.push_back("mpg");
extensions.push_back("vob");
extensions.push_back("wav");
extensions.push_back("wave");
extensions.push_back("m4v");
extensions.push_back("mkv");
extensions.push_back("avi");
extensions.push_back("divx");
extensions.push_back("dat");
extensions.push_back("flac");
extensions.push_back("flv");
extensions.push_back("mp4");
extensions.push_back("mov");
extensions.push_back("m4a");
extensions.push_back("3gp");
extensions.push_back("3g2");
extensions.push_back("asf");
extensions.push_back("wmv");
extensions.push_back("wma");
sc->addServiceFactory(eServiceFactoryMP3::id, this, extensions);
}
m_service_info = new eStaticServiceMP3Info();
}
eServiceFactoryMP3::~eServiceFactoryMP3()
{
ePtr<eServiceCenter> sc;
eServiceCenter::getPrivInstance(sc);
if (sc)
sc->removeServiceFactory(eServiceFactoryMP3::id);
}
DEFINE_REF(eServiceFactoryMP3)
// iServiceHandler
RESULT eServiceFactoryMP3::play(const eServiceReference &ref, ePtr<iPlayableService> &ptr)
{
// check resources...
ptr = new eServiceMP3(ref);
return 0;
}
RESULT eServiceFactoryMP3::record(const eServiceReference &ref, ePtr<iRecordableService> &ptr)
{
ptr=0;
return -1;
}
RESULT eServiceFactoryMP3::list(const eServiceReference &, ePtr<iListableService> &ptr)
{
ptr=0;
return -1;
}
RESULT eServiceFactoryMP3::info(const eServiceReference &ref, ePtr<iStaticServiceInformation> &ptr)
{
ptr = m_service_info;
return 0;
}
class eMP3ServiceOfflineOperations: public iServiceOfflineOperations
{
DECLARE_REF(eMP3ServiceOfflineOperations);
eServiceReference m_ref;
public:
eMP3ServiceOfflineOperations(const eServiceReference &ref);
RESULT deleteFromDisk(int simulate);
RESULT getListOfFilenames(std::list<std::string> &);
RESULT reindex();
};
DEFINE_REF(eMP3ServiceOfflineOperations);
eMP3ServiceOfflineOperations::eMP3ServiceOfflineOperations(const eServiceReference &ref): m_ref((const eServiceReference&)ref)
{
}
RESULT eMP3ServiceOfflineOperations::deleteFromDisk(int simulate)
{
if (!simulate)
{
std::list<std::string> res;
if (getListOfFilenames(res))
return -1;
eBackgroundFileEraser *eraser = eBackgroundFileEraser::getInstance();
if (!eraser)
eDebug("FATAL !! can't get background file eraser");
for (std::list<std::string>::iterator i(res.begin()); i != res.end(); ++i)
{
// eDebug("Removing %s...", i->c_str());
if (eraser)
eraser->erase(i->c_str());
else
::unlink(i->c_str());
}
}
return 0;
}
RESULT eMP3ServiceOfflineOperations::getListOfFilenames(std::list<std::string> &res)
{
res.clear();
res.push_back(m_ref.path);
return 0;
}
RESULT eMP3ServiceOfflineOperations::reindex()
{
return -1;
}
RESULT eServiceFactoryMP3::offlineOperations(const eServiceReference &ref, ePtr<iServiceOfflineOperations> &ptr)
{
ptr = new eMP3ServiceOfflineOperations(ref);
return 0;
}
// eStaticServiceMP3Info
// eStaticServiceMP3Info is seperated from eServiceMP3 to give information
// about unopened files.
// probably eServiceMP3 should use this class as well, and eStaticServiceMP3Info
// should have a database backend where ID3-files etc. are cached.
// this would allow listing the mp3 database based on certain filters.
DEFINE_REF(eStaticServiceMP3Info)
eStaticServiceMP3Info::eStaticServiceMP3Info()
{
}
RESULT eStaticServiceMP3Info::getName(const eServiceReference &ref, std::string &name)
{
if ( ref.name.length() )
name = ref.name;
else
{
size_t last = ref.path.rfind('/');
if (last != std::string::npos)
name = ref.path.substr(last+1);
else
name = ref.path;
}
return 0;
}
int eStaticServiceMP3Info::getLength(const eServiceReference &ref)
{
return -1;
}
int eStaticServiceMP3Info::getInfo(const eServiceReference &ref, int w)
{
switch (w)
{
case iServiceInformation::sTimeCreate:
{
struct stat s;
if (stat(ref.path.c_str(), &s) == 0)
{
return s.st_mtime;
}
}
break;
case iServiceInformation::sFileSize:
{
struct stat s;
if (stat(ref.path.c_str(), &s) == 0)
{
return s.st_size;
}
}
break;
}
return iServiceInformation::resNA;
}
long long eStaticServiceMP3Info::getFileSize(const eServiceReference &ref)
{
struct stat s;
if (stat(ref.path.c_str(), &s) == 0)
{
return s.st_size;
}
return 0;
}
RESULT eStaticServiceMP3Info::getEvent(const eServiceReference &ref, ePtr<eServiceEvent> &evt, time_t start_time)
{
if (ref.path.find("://") != std::string::npos)
{
eServiceReference equivalentref(ref);
equivalentref.type = eServiceFactoryMP3::id;
equivalentref.path.clear();
return eEPGCache::getInstance()->lookupEventTime(equivalentref, start_time, evt);
}
evt = 0;
return -1;
}
DEFINE_REF(eStreamBufferInfo)
eStreamBufferInfo::eStreamBufferInfo(int percentage, int inputrate, int outputrate, int space, int size)
: bufferPercentage(percentage),
inputRate(inputrate),
outputRate(outputrate),
bufferSpace(space),
bufferSize(size)
{
}
int eStreamBufferInfo::getBufferPercentage() const
{
return bufferPercentage;
}
int eStreamBufferInfo::getAverageInputRate() const
{
return inputRate;
}
int eStreamBufferInfo::getAverageOutputRate() const
{
return outputRate;
}
int eStreamBufferInfo::getBufferSpace() const
{
return bufferSpace;
}
int eStreamBufferInfo::getBufferSize() const
{
return bufferSize;
}
DEFINE_REF(eServiceMP3InfoContainer);
eServiceMP3InfoContainer::eServiceMP3InfoContainer()
: doubleValue(0.0), bufferValue(NULL), bufferData(NULL), bufferSize(0)
{
}
eServiceMP3InfoContainer::~eServiceMP3InfoContainer()
{
if (bufferValue)
{
#if GST_VERSION_MAJOR >= 1
gst_buffer_unmap(bufferValue, &map);
#endif
gst_buffer_unref(bufferValue);
bufferValue = NULL;
bufferData = NULL;
bufferSize = 0;
}
}
double eServiceMP3InfoContainer::getDouble(unsigned int index) const
{
return doubleValue;
}
unsigned char *eServiceMP3InfoContainer::getBuffer(unsigned int &size) const
{
size = bufferSize;
return bufferData;
}
void eServiceMP3InfoContainer::setDouble(double value)
{
doubleValue = value;
}
void eServiceMP3InfoContainer::setBuffer(GstBuffer *buffer)
{
bufferValue = buffer;
gst_buffer_ref(bufferValue);
#if GST_VERSION_MAJOR < 1
bufferData = GST_BUFFER_DATA(bufferValue);
bufferSize = GST_BUFFER_SIZE(bufferValue);
#else
gst_buffer_map(bufferValue, &map, GST_MAP_READ);
bufferData = map.data;
bufferSize = map.size;
#endif
}
// eServiceMP3
int eServiceMP3::ac3_delay = 0,
eServiceMP3::pcm_delay = 0;
eServiceMP3::eServiceMP3(eServiceReference ref):
m_nownext_timer(eTimer::create(eApp)),
m_ref(ref),
m_pump(eApp, 1)
{
m_subtitle_sync_timer = eTimer::create(eApp);
m_streamingsrc_timeout = 0;
m_stream_tags = 0;
m_currentAudioStream = -1;
m_currentSubtitleStream = -1;
m_cachedSubtitleStream = 0; /* report the first subtitle stream to be 'cached'. TODO: use an actual cache. */
m_subtitle_widget = 0;
m_currentTrickRatio = 1.0;
m_buffer_size = 5 * 1024 * 1024;
m_ignore_buffering_messages = 0;
m_is_live = false;
m_use_prefillbuffer = false;
m_paused = false;
m_seek_paused = false;
m_extra_headers = "";
m_download_buffer_path = "";
m_prev_decoder_time = -1;
m_decoder_time_valid_state = 0;
m_errorInfo.missing_codec = "";
audioSink = videoSink = NULL;
CONNECT(m_subtitle_sync_timer->timeout, eServiceMP3::pushSubtitles);
CONNECT(m_pump.recv_msg, eServiceMP3::gstPoll);
CONNECT(m_nownext_timer->timeout, eServiceMP3::updateEpgCacheNowNext);
m_aspect = m_width = m_height = m_framerate = m_progressive = -1;
m_state = stIdle;
m_subtitles_paused = false;
// eDebug("eServiceMP3::construct!");
const char *filename = m_ref.path.c_str();
const char *ext = strrchr(filename, '.');
if (!ext)
ext = filename + strlen(filename);
m_sourceinfo.is_video = FALSE;
m_sourceinfo.audiotype = atUnknown;
if ( (strcasecmp(ext, ".mpeg") && strcasecmp(ext, ".mpg") && strcasecmp(ext, ".vob") && strcasecmp(ext, ".bin") && strcasecmp(ext, ".dat") ) == 0 )
{
m_sourceinfo.containertype = ctMPEGPS;
m_sourceinfo.is_video = TRUE;
}
else if ( strcasecmp(ext, ".ts") == 0 )
{
m_sourceinfo.containertype = ctMPEGTS;
m_sourceinfo.is_video = TRUE;
}
else if ( strcasecmp(ext, ".mkv") == 0 )
{
m_sourceinfo.containertype = ctMKV;
m_sourceinfo.is_video = TRUE;
}
else if ( strcasecmp(ext, ".ogm") == 0 || strcasecmp(ext, ".ogv") == 0)
{
m_sourceinfo.containertype = ctOGG;
m_sourceinfo.is_video = TRUE;
}
else if ( strcasecmp(ext, ".avi") == 0 || strcasecmp(ext, ".divx") == 0)
{
m_sourceinfo.containertype = ctAVI;
m_sourceinfo.is_video = TRUE;
}
else if ( strcasecmp(ext, ".mp4") == 0 || strcasecmp(ext, ".mov") == 0 || strcasecmp(ext, ".m4v") == 0 || strcasecmp(ext, ".3gp") == 0 || strcasecmp(ext, ".3g2") == 0)
{
m_sourceinfo.containertype = ctMP4;
m_sourceinfo.is_video = TRUE;
}
else if ( strcasecmp(ext, ".asf") == 0 || strcasecmp(ext, ".wmv") == 0)
{
m_sourceinfo.containertype = ctASF;
m_sourceinfo.is_video = TRUE;
}
else if ( strcasecmp(ext, ".m4a") == 0 )
{
m_sourceinfo.containertype = ctMP4;
m_sourceinfo.audiotype = atAAC;
}
else if ( strcasecmp(ext, ".mp3") == 0 )
m_sourceinfo.audiotype = atMP3;
else if ( strcasecmp(ext, ".wma") == 0 )
m_sourceinfo.audiotype = atWMA;
else if ( (strncmp(filename, "/autofs/", 8) || strncmp(filename+strlen(filename)-13, "/track-", 7) || strcasecmp(ext, ".wav")) == 0 )
m_sourceinfo.containertype = ctCDA;
if ( strcasecmp(ext, ".dat") == 0 )
{
m_sourceinfo.containertype = ctVCD;
m_sourceinfo.is_video = TRUE;
}
if ( strstr(filename, "://") )
m_sourceinfo.is_streaming = TRUE;
gchar *uri;
if ( m_sourceinfo.is_streaming )
{
uri = g_strdup_printf ("%s", filename);
m_streamingsrc_timeout = eTimer::create(eApp);;
CONNECT(m_streamingsrc_timeout->timeout, eServiceMP3::sourceTimeout);
std::string config_str;
if (eConfigManager::getConfigBoolValue("config.mediaplayer.useAlternateUserAgent"))
{
m_useragent = eConfigManager::getConfigValue("config.mediaplayer.alternateUserAgent");
}
if (m_useragent.empty())
m_useragent = "Enigma2 Mediaplayer";
m_extra_headers = eConfigManager::getConfigValue("config.mediaplayer.extraHeaders");
if ( m_ref.getData(7) & BUFFERING_ENABLED )
{
m_use_prefillbuffer = true;
if ( m_ref.getData(7) & PROGRESSIVE_DOWNLOAD )
{
/* progressive download buffering */
if (::access("/hdd/movie", X_OK) >= 0)
{
/* It looks like /hdd points to a valid mount, so we can store a download buffer on it */
m_download_buffer_path = "/hdd/gstreamer_XXXXXXXXXX";
}
}
}
}
else if ( m_sourceinfo.containertype == ctCDA )
{
int i_track = atoi(filename+18);
uri = g_strdup_printf ("cdda://%i", i_track);
}
else if ( m_sourceinfo.containertype == ctVCD )
{
int ret = -1;
int fd = open(filename,O_RDONLY);
if (fd >= 0)
{
char* tmp = new char[128*1024];
ret = read(fd, tmp, 128*1024);
close(fd);
delete [] tmp;
}
if ( ret == -1 ) // this is a "REAL" VCD
uri = g_strdup_printf ("vcd://");
else
uri = g_filename_to_uri(filename, NULL, NULL);
}
else
uri = g_filename_to_uri(filename, NULL, NULL);
// eDebug("eServiceMP3::playbin uri=%s", uri);
#if GST_VERSION_MAJOR < 1
m_gst_playbin = gst_element_factory_make("playbin2", "playbin");
#else
m_gst_playbin = gst_element_factory_make("playbin", "playbin");
#endif
if ( m_gst_playbin )
{
guint flags;
g_object_get(G_OBJECT (m_gst_playbin), "flags", &flags, NULL);
/* avoid video conversion, let the (hardware) sinks handle that */
flags |= GST_PLAY_FLAG_NATIVE_VIDEO;
/* volume control is done by hardware */
flags &= ~GST_PLAY_FLAG_SOFT_VOLUME;
if ( m_sourceinfo.is_streaming )
{
g_signal_connect (G_OBJECT (m_gst_playbin), "notify::source", G_CALLBACK (playbinNotifySource), this);
if (m_download_buffer_path != "")
{
/* use progressive download buffering */
flags |= GST_PLAY_FLAG_DOWNLOAD;
g_signal_connect(G_OBJECT(m_gst_playbin), "element-added", G_CALLBACK(handleElementAdded), this);
/* limit file size */
g_object_set(m_gst_playbin, "ring-buffer-max-size", (guint64)(8LL * 1024LL * 1024LL), NULL);
}
/*
* regardless whether or not we configured a progressive download file, use a buffer as well
* (progressive download might not work for all formats)
*/
flags |= GST_PLAY_FLAG_BUFFERING;
/* increase the default 2 second / 2 MB buffer limitations to 5s / 5MB */
g_object_set(G_OBJECT(m_gst_playbin), "buffer-duration", 5LL * GST_SECOND, NULL);
g_object_set(G_OBJECT(m_gst_playbin), "buffer-size", m_buffer_size, NULL);
}
g_object_set (G_OBJECT (m_gst_playbin), "flags", flags, NULL);
g_object_set (G_OBJECT (m_gst_playbin), "uri", uri, NULL);
GstElement *subsink = gst_element_factory_make("subsink", "subtitle_sink");
if (!subsink)
eDebug("eServiceMP3::sorry, can't play: missing gst-plugin-subsink");
else
{
m_subs_to_pull_handler_id = g_signal_connect (subsink, "new-buffer", G_CALLBACK (gstCBsubtitleAvail), this);
g_object_set (G_OBJECT (subsink), "caps", gst_caps_from_string("text/plain; text/x-plain; text/x-raw; text/x-pango-markup; video/x-dvd-subpicture; subpicture/x-pgs"), NULL);
g_object_set (G_OBJECT (m_gst_playbin), "text-sink", subsink, NULL);
g_object_set (G_OBJECT (m_gst_playbin), "current-text", m_currentSubtitleStream, NULL);
}
GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE (m_gst_playbin));
#if GST_VERSION_MAJOR < 1
gst_bus_set_sync_handler(bus, gstBusSyncHandler, this);
#else
gst_bus_set_sync_handler(bus, gstBusSyncHandler, this, NULL);
#endif
gst_object_unref(bus);
char srt_filename[ext - filename + 5];
strncpy(srt_filename,filename, ext - filename);
srt_filename[ext - filename] = '\0';
strcat(srt_filename, ".srt");
if (::access(srt_filename, R_OK) >= 0)
{
eDebug("eServiceMP3::subtitle uri: %s", g_filename_to_uri(srt_filename, NULL, NULL));
g_object_set (G_OBJECT (m_gst_playbin), "suburi", g_filename_to_uri(srt_filename, NULL, NULL), NULL);
}
} else
{
m_event((iPlayableService*)this, evUser+12);
m_gst_playbin = 0;
m_errorInfo.error_message = "failed to create GStreamer pipeline!\n";
eDebug("eServiceMP3::sorry, can't play: %s",m_errorInfo.error_message.c_str());
}
g_free(uri);
}
eServiceMP3::~eServiceMP3()
{
// disconnect subtitle callback
GstElement *subsink = gst_bin_get_by_name(GST_BIN(m_gst_playbin), "subtitle_sink");
if (subsink)
{
g_signal_handler_disconnect (subsink, m_subs_to_pull_handler_id);
gst_object_unref(subsink);
}
if (m_subtitle_widget) m_subtitle_widget->destroy();
m_subtitle_widget = 0;
if (m_gst_playbin)
{
// disconnect sync handler callback
GstBus *bus = gst_pipeline_get_bus(GST_PIPELINE (m_gst_playbin));
#if GST_VERSION_MAJOR < 1
gst_bus_set_sync_handler(bus, NULL, NULL);
#else
gst_bus_set_sync_handler(bus, NULL, NULL, NULL);
#endif
gst_object_unref(bus);
}
if (m_state == stRunning)
stop();
if (m_stream_tags)
gst_tag_list_free(m_stream_tags);
if (audioSink)
{
gst_object_unref(GST_OBJECT(audioSink));
audioSink = NULL;
}
if (videoSink)
{
gst_object_unref(GST_OBJECT(videoSink));
videoSink = NULL;
}
if (m_gst_playbin)
{
gst_object_unref (GST_OBJECT (m_gst_playbin));
// eDebug("eServiceMP3::destruct!");
}
}
void eServiceMP3::updateEpgCacheNowNext()
{
bool update = false;
ePtr<eServiceEvent> next = 0;
ePtr<eServiceEvent> ptr = 0;
eServiceReference ref(m_ref);
ref.type = eServiceFactoryMP3::id;
ref.path.clear();
if (eEPGCache::getInstance() && eEPGCache::getInstance()->lookupEventTime(ref, -1, ptr) >= 0)
{
ePtr<eServiceEvent> current = m_event_now;
if (!current || !ptr || current->getEventId() != ptr->getEventId())
{
update = true;
m_event_now = ptr;
time_t next_time = ptr->getBeginTime() + ptr->getDuration();
if (eEPGCache::getInstance()->lookupEventTime(ref, next_time, ptr) >= 0)
{
next = ptr;
m_event_next = ptr;
}
}
}
int refreshtime = 60;
if (!next)
{
next = m_event_next;
}
if (next)
{
time_t now = eDVBLocalTimeHandler::getInstance()->nowTime();
refreshtime = (int)(next->getBeginTime() - now) + 3;
if (refreshtime <= 0 || refreshtime > 60)
{
refreshtime = 60;
}
}
m_nownext_timer->startLongTimer(refreshtime);
if (update)
{
m_event((iPlayableService*)this, evUpdatedEventInfo);
}
}
DEFINE_REF(eServiceMP3);
DEFINE_REF(eServiceMP3::GstMessageContainer);
RESULT eServiceMP3::connectEvent(const Slot2<void,iPlayableService*,int> &event, ePtr<eConnection> &connection)
{
connection = new eConnection((iPlayableService*)this, m_event.connect(event));
return 0;
}
RESULT eServiceMP3::start()
{
ASSERT(m_state == stIdle);
m_state = stRunning;
m_subtitles_paused = false;
if (m_gst_playbin)
{
// eDebug("eServiceMP3::starting pipeline");
gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
updateEpgCacheNowNext();
}
m_event(this, evStart);
return 0;
}
void eServiceMP3::sourceTimeout()
{
eDebug("eServiceMP3::http source timeout! issuing eof...");
m_event((iPlayableService*)this, evEOF);
}
RESULT eServiceMP3::stop()
{
ASSERT(m_state != stIdle);
if (m_state == stStopped)
return -1;
eDebug("eServiceMP3::stop %s", m_ref.path.c_str());
gst_element_set_state(m_gst_playbin, GST_STATE_NULL);
m_state = stStopped;
m_subtitles_paused = false;
m_nownext_timer->stop();
if (m_streamingsrc_timeout)
m_streamingsrc_timeout->stop();
return 0;
}
RESULT eServiceMP3::setTarget(int target)
{
return -1;
}
RESULT eServiceMP3::pause(ePtr<iPauseableService> &ptr)
{
ptr=this;
return 0;
}
RESULT eServiceMP3::setSlowMotion(int ratio)
{
if (!ratio)
return 0;
eDebug("eServiceMP3::setSlowMotion ratio=%f",1.0/(gdouble)ratio);
return trickSeek(1.0/(gdouble)ratio);
}
RESULT eServiceMP3::setFastForward(int ratio)
{
eDebug("eServiceMP3::setFastForward ratio=%i",ratio);
return trickSeek(ratio);
}
// iPausableService
RESULT eServiceMP3::pause()
{
if (!m_gst_playbin || m_state != stRunning)
return -1;
m_subtitles_paused = true;
m_subtitle_sync_timer->start(1, true);
trickSeek(0.0);
return 0;
}
RESULT eServiceMP3::unpause()
{
if (!m_gst_playbin || m_state != stRunning)
return -1;
m_subtitles_paused = false;
m_subtitle_sync_timer->start(1, true);
trickSeek(1.0);
return 0;
}
/* iSeekableService */
RESULT eServiceMP3::seek(ePtr<iSeekableService> &ptr)
{
ptr = this;
return 0;
}
RESULT eServiceMP3::getLength(pts_t &pts)
{
if (!m_gst_playbin)
return -1;
if (m_state != stRunning)
return -1;
GstFormat fmt = GST_FORMAT_TIME;
gint64 len;
#if GST_VERSION_MAJOR < 1
if (!gst_element_query_duration(m_gst_playbin, &fmt, &len))
#else
if (!gst_element_query_duration(m_gst_playbin, fmt, &len))
#endif
return -1;
/* len is in nanoseconds. we have 90 000 pts per second. */
pts = len / 11111LL;
return 0;
}
RESULT eServiceMP3::seekToImpl(pts_t to)
{
/* convert pts to nanoseconds */
gint64 time_nanoseconds = to * 11111LL;
if (!gst_element_seek (m_gst_playbin, m_currentTrickRatio, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT),
GST_SEEK_TYPE_SET, time_nanoseconds,
GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE))
{
eDebug("eServiceMP3::seekTo failed");
return -1;
}
if (m_paused)
{
m_seek_paused = true;
gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING);
}
return 0;
}
RESULT eServiceMP3::seekTo(pts_t to)
{
RESULT ret = -1;
if (m_gst_playbin)
{
m_prev_decoder_time = -1;
m_decoder_time_valid_state = 0;
ret = seekToImpl(to);
}
return ret;
}
RESULT eServiceMP3::trickSeek(gdouble ratio)
{
if (!m_gst_playbin)
return -1;
if (ratio > -0.01 && ratio < 0.01)
{
gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED);
return 0;
}
m_currentTrickRatio = ratio;
bool validposition = false;
gint64 pos = 0;
pts_t pts;
if (getPlayPosition(pts) >= 0)
{
validposition = true;
pos = pts * 11111LL;
}
gst_element_set_state(m_gst_playbin, GST_STATE_PLAYING);
if (validposition)
{
if (ratio >= 0.0)
{
gst_element_seek(m_gst_playbin, ratio, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT | GST_SEEK_FLAG_SKIP), GST_SEEK_TYPE_SET, pos, GST_SEEK_TYPE_SET, -1);
}
else
{
/* note that most elements will not support negative speed */
gst_element_seek(m_gst_playbin, ratio, GST_FORMAT_TIME, (GstSeekFlags)(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_SKIP), GST_SEEK_TYPE_SET, 0, GST_SEEK_TYPE_SET, pos);
}
}
m_prev_decoder_time = -1;
m_decoder_time_valid_state = 0;
return 0;
}
RESULT eServiceMP3::seekRelative(int direction, pts_t to)
{
if (!m_gst_playbin)
return -1;
pts_t ppos;
if (getPlayPosition(ppos) < 0) return -1;
ppos += to * direction;
if (ppos < 0)
ppos = 0;
return seekTo(ppos);
}
#if GST_VERSION_MAJOR < 1
gint eServiceMP3::match_sinktype(GstElement *element, gpointer type)
{
return strcmp(g_type_name(G_OBJECT_TYPE(element)), (const char*)type);
}
#else
gint eServiceMP3::match_sinktype(const GValue *velement, const gchar *type)
{
GstElement *element = GST_ELEMENT_CAST(g_value_get_object(velement));
return strcmp(g_type_name(G_OBJECT_TYPE(element)), type);
}
#endif
RESULT eServiceMP3::getPlayPosition(pts_t &pts)
{
gint64 pos;
pts = 0;
if (!m_gst_playbin)
return -1;
if (m_state != stRunning)
return -1;
if (audioSink || videoSink)
{
g_signal_emit_by_name(audioSink ? audioSink : videoSink, "get-decoder-time", &pos);
if (!GST_CLOCK_TIME_IS_VALID(pos)) return -1;
}
else
{
GstFormat fmt = GST_FORMAT_TIME;
#if GST_VERSION_MAJOR < 1
if (!gst_element_query_position(m_gst_playbin, &fmt, &pos))
#else
if (!gst_element_query_position(m_gst_playbin, fmt, &pos))
#endif
{
// eDebug("gst_element_query_position failed in getPlayPosition");
return -1;
}
}
/* pos is in nanoseconds. we have 90 000 pts per second. */
pts = pos / 11111LL;
return 0;
}
RESULT eServiceMP3::setTrickmode(int trick)
{
/* trickmode is not yet supported by our dvbmediasinks. */
return -1;
}
RESULT eServiceMP3::isCurrentlySeekable()
{
int ret = 3; /* just assume that seeking and fast/slow winding are possible */
if (!m_gst_playbin)
return 0;
if (m_state != stRunning)
return 0;
return ret;
}
RESULT eServiceMP3::info(ePtr<iServiceInformation>&i)
{
i = this;
return 0;
}
RESULT eServiceMP3::getName(std::string &name)
{
std::string title = m_ref.getName();
if (title.empty())
{
name = m_ref.path;
size_t n = name.rfind('/');
if (n != std::string::npos)
name = name.substr(n + 1);
}
else
name = title;
return 0;
}
RESULT eServiceMP3::getEvent(ePtr<eServiceEvent> &evt, int nownext)
{
evt = nownext ? m_event_next : m_event_now;
if (!evt)
return -1;
return 0;
}
int eServiceMP3::getInfo(int w)
{
const gchar *tag = 0;
switch (w)
{
case sServiceref: return m_ref;
case sVideoHeight: return m_height;
case sVideoWidth: return m_width;
case sFrameRate: return m_framerate;
case sProgressive: return m_progressive;
case sAspect: return m_aspect;
case sTagTitle:
case sTagArtist:
case sTagAlbum:
case sTagTitleSortname:
case sTagArtistSortname:
case sTagAlbumSortname:
case sTagDate:
case sTagComposer:
case sTagGenre:
case sTagComment:
case sTagExtendedComment:
case sTagLocation:
case sTagHomepage:
case sTagDescription:
case sTagVersion:
case sTagISRC:
case sTagOrganization:
case sTagCopyright:
case sTagCopyrightURI:
case sTagContact:
case sTagLicense:
case sTagLicenseURI:
case sTagCodec:
case sTagAudioCodec:
case sTagVideoCodec:
case sTagEncoder:
case sTagLanguageCode:
case sTagKeywords:
case sTagChannelMode:
case sUser+12:
return resIsString;
case sTagTrackGain:
case sTagTrackPeak:
case sTagAlbumGain:
case sTagAlbumPeak:
case sTagReferenceLevel:
case sTagBeatsPerMinute:
case sTagImage:
case sTagPreviewImage:
case sTagAttachment:
return resIsPyObject;
case sTagTrackNumber:
tag = GST_TAG_TRACK_NUMBER;
break;
case sTagTrackCount:
tag = GST_TAG_TRACK_COUNT;
break;
case sTagAlbumVolumeNumber:
tag = GST_TAG_ALBUM_VOLUME_NUMBER;
break;
case sTagAlbumVolumeCount:
tag = GST_TAG_ALBUM_VOLUME_COUNT;
break;
case sTagBitrate:
tag = GST_TAG_BITRATE;
break;
case sTagNominalBitrate:
tag = GST_TAG_NOMINAL_BITRATE;
break;
case sTagMinimumBitrate:
tag = GST_TAG_MINIMUM_BITRATE;
break;
case sTagMaximumBitrate:
tag = GST_TAG_MAXIMUM_BITRATE;
break;
case sTagSerial:
tag = GST_TAG_SERIAL;
break;
case sTagEncoderVersion:
tag = GST_TAG_ENCODER_VERSION;
break;
case sTagCRC:
tag = "has-crc";
break;
default:
return resNA;
}
if (!m_stream_tags || !tag)
return 0;
guint value;
if (gst_tag_list_get_uint(m_stream_tags, tag, &value))
return (int) value;
return 0;
}
std::string eServiceMP3::getInfoString(int w)
{
if ( m_sourceinfo.is_streaming )
{
switch (w)
{
case sProvider:
return "IPTV";
case sServiceref:
{
eServiceReference ref(m_ref);
ref.type = eServiceFactoryMP3::id;
ref.path.clear();
return ref.toString();
}
default:
break;
}
}
if ( !m_stream_tags && w < sUser && w > 26 )
return "";
const gchar *tag = 0;
switch (w)
{
case sTagTitle:
tag = GST_TAG_TITLE;
break;
case sTagArtist:
tag = GST_TAG_ARTIST;
break;
case sTagAlbum:
tag = GST_TAG_ALBUM;
break;
case sTagTitleSortname:
tag = GST_TAG_TITLE_SORTNAME;
break;
case sTagArtistSortname:
tag = GST_TAG_ARTIST_SORTNAME;
break;
case sTagAlbumSortname:
tag = GST_TAG_ALBUM_SORTNAME;
break;
case sTagDate:
GDate *date;
GstDateTime *date_time;
if (gst_tag_list_get_date(m_stream_tags, GST_TAG_DATE, &date))
{
gchar res[5];
snprintf(res, sizeof(res), "%04d", g_date_get_year(date));
g_date_free(date);
return (std::string)res;
}
#if GST_VERSION_MAJOR >= 1
else if (gst_tag_list_get_date_time(m_stream_tags, GST_TAG_DATE_TIME, &date_time))
{
if (gst_date_time_has_year(date_time))
{
gchar res[5];
snprintf(res, sizeof(res), "%04d", gst_date_time_get_year(date_time));
gst_date_time_unref(date_time);
return (std::string)res;
}
gst_date_time_unref(date_time);
}
#endif
break;
case sTagComposer:
tag = GST_TAG_COMPOSER;
break;
case sTagGenre:
tag = GST_TAG_GENRE;
break;
case sTagComment:
tag = GST_TAG_COMMENT;
break;
case sTagExtendedComment:
tag = GST_TAG_EXTENDED_COMMENT;
break;
case sTagLocation:
tag = GST_TAG_LOCATION;
break;
case sTagHomepage:
tag = GST_TAG_HOMEPAGE;
break;
case sTagDescription:
tag = GST_TAG_DESCRIPTION;
break;
case sTagVersion:
tag = GST_TAG_VERSION;
break;
case sTagISRC:
tag = GST_TAG_ISRC;
break;
case sTagOrganization:
tag = GST_TAG_ORGANIZATION;
break;
case sTagCopyright:
tag = GST_TAG_COPYRIGHT;
break;
case sTagCopyrightURI:
tag = GST_TAG_COPYRIGHT_URI;
break;
case sTagContact:
tag = GST_TAG_CONTACT;
break;
case sTagLicense:
tag = GST_TAG_LICENSE;
break;
case sTagLicenseURI:
tag = GST_TAG_LICENSE_URI;
break;
case sTagCodec:
tag = GST_TAG_CODEC;
break;
case sTagAudioCodec:
tag = GST_TAG_AUDIO_CODEC;
break;
case sTagVideoCodec:
tag = GST_TAG_VIDEO_CODEC;
break;
case sTagEncoder:
tag = GST_TAG_ENCODER;
break;
case sTagLanguageCode:
tag = GST_TAG_LANGUAGE_CODE;
break;
case sTagKeywords:
tag = GST_TAG_KEYWORDS;
break;
case sTagChannelMode:
tag = "channel-mode";
break;
case sUser+12:
return m_errorInfo.error_message;
default:
return "";
}
if ( !tag )
return "";
gchar *value;
if (m_stream_tags && gst_tag_list_get_string(m_stream_tags, tag, &value))
{
std::string res = value;
g_free(value);
return res;
}
return "";
}
ePtr<iServiceInfoContainer> eServiceMP3::getInfoObject(int w)
{
eServiceMP3InfoContainer *container = new eServiceMP3InfoContainer;
ePtr<iServiceInfoContainer> retval = container;
const gchar *tag = 0;
bool isBuffer = false;
switch (w)
{
case sTagTrackGain:
tag = GST_TAG_TRACK_GAIN;
break;
case sTagTrackPeak:
tag = GST_TAG_TRACK_PEAK;
break;
case sTagAlbumGain:
tag = GST_TAG_ALBUM_GAIN;
break;
case sTagAlbumPeak:
tag = GST_TAG_ALBUM_PEAK;
break;
case sTagReferenceLevel:
tag = GST_TAG_REFERENCE_LEVEL;
break;
case sTagBeatsPerMinute:
tag = GST_TAG_BEATS_PER_MINUTE;
break;
case sTagImage:
tag = GST_TAG_IMAGE;
isBuffer = true;
break;
case sTagPreviewImage:
tag = GST_TAG_PREVIEW_IMAGE;
isBuffer = true;
break;
case sTagAttachment:
tag = GST_TAG_ATTACHMENT;
isBuffer = true;
break;
default:
break;
}
if (m_stream_tags && tag)
{
if (isBuffer)
{
const GValue *gv_buffer = gst_tag_list_get_value_index(m_stream_tags, tag, 0);
if ( gv_buffer )
{
GstBuffer *buffer;
buffer = gst_value_get_buffer (gv_buffer);
container->setBuffer(buffer);
}
}
else
{
gdouble value = 0.0;
gst_tag_list_get_double(m_stream_tags, tag, &value);
container->setDouble(value);
}
}
return retval;
}
RESULT eServiceMP3::audioChannel(ePtr<iAudioChannelSelection> &ptr)
{
ptr = this;
return 0;
}
RESULT eServiceMP3::audioTracks(ePtr<iAudioTrackSelection> &ptr)
{
ptr = this;
return 0;
}
RESULT eServiceMP3::subtitle(ePtr<iSubtitleOutput> &ptr)
{
ptr = this;
return 0;
}
RESULT eServiceMP3::audioDelay(ePtr<iAudioDelay> &ptr)
{
ptr = this;
return 0;
}
int eServiceMP3::getNumberOfTracks()
{
return m_audioStreams.size();
}
int eServiceMP3::getCurrentTrack()
{
if (m_currentAudioStream == -1)
g_object_get (G_OBJECT (m_gst_playbin), "current-audio", &m_currentAudioStream, NULL);
return m_currentAudioStream;
}
RESULT eServiceMP3::selectTrack(unsigned int i)
{
bool validposition = false;
pts_t ppos = 0;
if (getPlayPosition(ppos) >= 0)
{
validposition = true;
ppos -= 90000;
if (ppos < 0)
ppos = 0;
}
int ret = selectAudioStream(i);
if (!ret)
{
if (validposition)
{
/* flush */
seekTo(ppos);
}
}
return ret;
}
int eServiceMP3::selectAudioStream(int i)
{
int current_audio;
g_object_set (G_OBJECT (m_gst_playbin), "current-audio", i, NULL);
g_object_get (G_OBJECT (m_gst_playbin), "current-audio", ¤t_audio, NULL);
if ( current_audio == i )
{
eDebug ("eServiceMP3::switched to audio stream %i", current_audio);
m_currentAudioStream = i;
return 0;
}
return -1;
}
int eServiceMP3::getCurrentChannel()
{
return STEREO;
}
RESULT eServiceMP3::selectChannel(int i)
{
eDebug("eServiceMP3::selectChannel(%i)",i);
return 0;
}
RESULT eServiceMP3::getTrackInfo(struct iAudioTrackInfo &info, unsigned int i)
{
if (i >= m_audioStreams.size())
return -2;
info.m_description = m_audioStreams[i].codec;
/* if (m_audioStreams[i].type == atMPEG)
info.m_description = "MPEG";
else if (m_audioStreams[i].type == atMP3)
info.m_description = "MP3";
else if (m_audioStreams[i].type == atAC3)
info.m_description = "AC3";
else if (m_audioStreams[i].type == atAAC)
info.m_description = "AAC";
else if (m_audioStreams[i].type == atDTS)
info.m_description = "DTS";
else if (m_audioStreams[i].type == atPCM)
info.m_description = "PCM";
else if (m_audioStreams[i].type == atOGG)
info.m_description = "OGG";
else if (m_audioStreams[i].type == atFLAC)
info.m_description = "FLAC";
else
info.m_description = "???";*/
if (info.m_language.empty())
info.m_language = m_audioStreams[i].language_code;
return 0;
}
subtype_t getSubtitleType(GstPad* pad, gchar *g_codec=NULL)
{
subtype_t type = stUnknown;
#if GST_VERSION_MAJOR < 1
GstCaps* caps = gst_pad_get_negotiated_caps(pad);
#else
GstCaps* caps = gst_pad_get_current_caps(pad);
#endif
if (!caps && !g_codec)
{
caps = gst_pad_get_allowed_caps(pad);
}
if (caps && !gst_caps_is_empty(caps))
{
GstStructure* str = gst_caps_get_structure(caps, 0);
if (str)
{
const gchar *g_type = gst_structure_get_name(str);
// eDebug("getSubtitleType::subtitle probe caps type=%s", g_type ? g_type : "(null)");
if (g_type)
{
if ( !strcmp(g_type, "video/x-dvd-subpicture") )
type = stVOB;
else if ( !strcmp(g_type, "text/x-pango-markup") )
type = stSRT;
else if ( !strcmp(g_type, "text/plain") || !strcmp(g_type, "text/x-plain") || !strcmp(g_type, "text/x-raw") )
type = stPlainText;
else if ( !strcmp(g_type, "subpicture/x-pgs") )
type = stPGS;
else
eDebug("getSubtitleType::unsupported subtitle caps %s (%s)", g_type, g_codec ? g_codec : "(null)");
}
}
}
else if ( g_codec )
{
// eDebug("getSubtitleType::subtitle probe codec tag=%s", g_codec);
if ( !strcmp(g_codec, "VOB") )
type = stVOB;
else if ( !strcmp(g_codec, "SubStation Alpha") || !strcmp(g_codec, "SSA") )
type = stSSA;
else if ( !strcmp(g_codec, "ASS") )
type = stASS;
else if ( !strcmp(g_codec, "SRT") )
type = stSRT;
else if ( !strcmp(g_codec, "UTF-8 plain text") )
type = stPlainText;
else
eDebug("getSubtitleType::unsupported subtitle codec %s", g_codec);
}
else
eDebug("getSubtitleType::unidentifiable subtitle stream!");
return type;
}
void eServiceMP3::gstBusCall(GstMessage *msg)
{
if (!msg)
return;
gchar *sourceName;
GstObject *source;
source = GST_MESSAGE_SRC(msg);
if (!GST_IS_OBJECT(source))
return;
sourceName = gst_object_get_name(source);
#if 0
gchar *string;
if (gst_message_get_structure(msg))
string = gst_structure_to_string(gst_message_get_structure(msg));
else
string = g_strdup(GST_MESSAGE_TYPE_NAME(msg));
// eDebug("eTsRemoteSource::gst_message from %s: %s", sourceName, string);
g_free(string);
#endif
switch (GST_MESSAGE_TYPE (msg))
{
case GST_MESSAGE_EOS:
m_event((iPlayableService*)this, evEOF);
break;
case GST_MESSAGE_STATE_CHANGED:
{
if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
break;
GstState old_state, new_state;
gst_message_parse_state_changed(msg, &old_state, &new_state, NULL);
if(old_state == new_state)
break;
eDebug("eServiceMP3::state transition %s -> %s", gst_element_state_get_name(old_state), gst_element_state_get_name(new_state));
GstStateChange transition = (GstStateChange)GST_STATE_TRANSITION(old_state, new_state);
switch(transition)
{
case GST_STATE_CHANGE_NULL_TO_READY:
{
} break;
case GST_STATE_CHANGE_READY_TO_PAUSED:
{
#if GST_VERSION_MAJOR >= 1
GValue result = { 0, };
#endif
GstIterator *children;
GstElement *subsink = gst_bin_get_by_name(GST_BIN(m_gst_playbin), "subtitle_sink");
if (subsink)
{
#ifdef GSTREAMER_SUBTITLE_SYNC_MODE_BUG
/*
* HACK: disable sync mode for now, gstreamer suffers from a bug causing sparse streams to loose sync, after pause/resume / skip
* see: https://bugzilla.gnome.org/show_bug.cgi?id=619434
* Sideeffect of using sync=false is that we receive subtitle buffers (far) ahead of their
* display time.
* Not too far ahead for subtitles contained in the media container.
* But for external srt files, we could receive all subtitles at once.
* And not just once, but after each pause/resume / skip.
* So as soon as gstreamer has been fixed to keep sync in sparse streams, sync needs to be re-enabled.
*/
g_object_set (G_OBJECT (subsink), "sync", FALSE, NULL);
#endif
#if 0
/* we should not use ts-offset to sync with the decoder time, we have to do our own decoder timekeeping */
g_object_set (G_OBJECT (subsink), "ts-offset", -2LL * GST_SECOND, NULL);
/* late buffers probably will not occur very often */
g_object_set (G_OBJECT (subsink), "max-lateness", 0LL, NULL);
/* avoid prerolling (it might not be a good idea to preroll a sparse stream) */
g_object_set (G_OBJECT (subsink), "async", TRUE, NULL);
#endif
// eDebug("eServiceMP3::subsink properties set!");
gst_object_unref(subsink);
}
if (audioSink)
{
gst_object_unref(GST_OBJECT(audioSink));
audioSink = NULL;
}
if (videoSink)
{
gst_object_unref(GST_OBJECT(videoSink));
videoSink = NULL;
}
children = gst_bin_iterate_recurse(GST_BIN(m_gst_playbin));
#if GST_VERSION_MAJOR < 1
audioSink = GST_ELEMENT_CAST(gst_iterator_find_custom(children, (GCompareFunc)match_sinktype, (gpointer)"GstDVBAudioSink"));
#else
if (gst_iterator_find_custom(children, (GCompareFunc)match_sinktype, &result, (gpointer)"GstDVBAudioSink"))
{
audioSink = GST_ELEMENT_CAST(g_value_dup_object(&result));
g_value_unset(&result);
}
#endif
gst_iterator_free(children);
children = gst_bin_iterate_recurse(GST_BIN(m_gst_playbin));
#if GST_VERSION_MAJOR < 1
videoSink = GST_ELEMENT_CAST(gst_iterator_find_custom(children, (GCompareFunc)match_sinktype, (gpointer)"GstDVBVideoSink"));
#else
if (gst_iterator_find_custom(children, (GCompareFunc)match_sinktype, &result, (gpointer)"GstDVBVideoSink"))
{
videoSink = GST_ELEMENT_CAST(g_value_dup_object(&result));
g_value_unset(&result);
}
#endif
gst_iterator_free(children);
m_is_live = (gst_element_get_state(m_gst_playbin, NULL, NULL, 0LL) == GST_STATE_CHANGE_NO_PREROLL);
setAC3Delay(ac3_delay);
setPCMDelay(pcm_delay);
} break;
case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
{
if ( m_sourceinfo.is_streaming && m_streamingsrc_timeout )
m_streamingsrc_timeout->stop();
m_paused = false;
if (m_seek_paused)
{
m_seek_paused = false;
gst_element_set_state(m_gst_playbin, GST_STATE_PAUSED);
}
} break;
case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
{
m_paused = true;
} break;
case GST_STATE_CHANGE_PAUSED_TO_READY:
{
if (audioSink)
{
gst_object_unref(GST_OBJECT(audioSink));
audioSink = NULL;
}
if (videoSink)
{
gst_object_unref(GST_OBJECT(videoSink));
videoSink = NULL;
}
} break;
case GST_STATE_CHANGE_READY_TO_NULL:
{
} break;
}
break;
}
case GST_MESSAGE_ERROR:
{
gchar *debug;
GError *err;
gst_message_parse_error (msg, &err, &debug);
g_free (debug);
eWarning("Gstreamer error: %s (%i) from %s", err->message, err->code, sourceName );
if ( err->domain == GST_STREAM_ERROR )
{
if ( err->code == GST_STREAM_ERROR_CODEC_NOT_FOUND )
{
if ( g_strrstr(sourceName, "videosink") )
m_event((iPlayableService*)this, evUser+11);
else if ( g_strrstr(sourceName, "audiosink") )
m_event((iPlayableService*)this, evUser+10);
}
}
g_error_free(err);
break;
}
case GST_MESSAGE_INFO:
{
gchar *debug;
GError *inf;
gst_message_parse_info (msg, &inf, &debug);
g_free (debug);
if ( inf->domain == GST_STREAM_ERROR && inf->code == GST_STREAM_ERROR_DECODE )
{
if ( g_strrstr(sourceName, "videosink") )
m_event((iPlayableService*)this, evUser+14);
}
g_error_free(inf);
break;
}
case GST_MESSAGE_TAG:
{
GstTagList *tags, *result;
gst_message_parse_tag(msg, &tags);
result = gst_tag_list_merge(m_stream_tags, tags, GST_TAG_MERGE_REPLACE);
if (result)
{
if (m_stream_tags)
gst_tag_list_free(m_stream_tags);
m_stream_tags = result;
}
const GValue *gv_image = gst_tag_list_get_value_index(tags, GST_TAG_IMAGE, 0);
if ( gv_image )
{
GstBuffer *buf_image;
buf_image = gst_value_get_buffer (gv_image);
int fd = open("/tmp/.id3coverart", O_CREAT|O_WRONLY|O_TRUNC, 0644);
if (fd >= 0)
{
guint8 *data;
gsize size;
#if GST_VERSION_MAJOR < 1
data = GST_BUFFER_DATA(buf_image);
size = GST_BUFFER_SIZE(buf_image);
#else
GstMapInfo map;
gst_buffer_map(buf_image, &map, GST_MAP_READ);
data = map.data;
size = map.size;
#endif
int ret = write(fd, data, size);
#if GST_VERSION_MAJOR >= 1
gst_buffer_unmap(buf_image, &map);
#endif
close(fd);
// eDebug("eServiceMP3::/tmp/.id3coverart %d bytes written ", ret);
}
m_event((iPlayableService*)this, evUser+13);
}
gst_tag_list_free(tags);
m_event((iPlayableService*)this, evUpdatedInfo);
break;
}
case GST_MESSAGE_ASYNC_DONE:
{
if(GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
break;
gint i, n_video = 0, n_audio = 0, n_text = 0;
g_object_get (m_gst_playbin, "n-video", &n_video, NULL);
g_object_get (m_gst_playbin, "n-audio", &n_audio, NULL);
g_object_get (m_gst_playbin, "n-text", &n_text, NULL);
eDebug("eServiceMP3::async-done - %d video, %d audio, %d subtitle", n_video, n_audio, n_text);
if ( n_video + n_audio <= 0 )
stop();
m_audioStreams.clear();
m_subtitleStreams.clear();
for (i = 0; i < n_audio; i++)
{
audioStream audio;
gchar *g_codec, *g_lang;
GstTagList *tags = NULL;
GstPad* pad = 0;
g_signal_emit_by_name (m_gst_playbin, "get-audio-pad", i, &pad);
#if GST_VERSION_MAJOR < 1
GstCaps* caps = gst_pad_get_negotiated_caps(pad);
#else
GstCaps* caps = gst_pad_get_current_caps(pad);
#endif
if (!caps)
continue;
GstStructure* str = gst_caps_get_structure(caps, 0);
const gchar *g_type = gst_structure_get_name(str);
eDebug("AUDIO STRUCT=%s", g_type);
audio.type = gstCheckAudioPad(str);
audio.language_code = "und";
audio.codec = g_type;
g_codec = NULL;
g_lang = NULL;
g_signal_emit_by_name (m_gst_playbin, "get-audio-tags", i, &tags);
#if GST_VERSION_MAJOR < 1
if (tags && gst_is_tag_list(tags))
#else
if (tags && GST_IS_TAG_LIST(tags))
#endif
{
if (gst_tag_list_get_string(tags, GST_TAG_AUDIO_CODEC, &g_codec))
{
audio.codec = std::string(g_codec);
g_free(g_codec);
}
if (gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang))
{
audio.language_code = std::string(g_lang);
g_free(g_lang);
}
gst_tag_list_free(tags);
}
eDebug("eServiceMP3::audio stream=%i codec=%s language=%s", i, audio.codec.c_str(), audio.language_code.c_str());
m_audioStreams.push_back(audio);
gst_caps_unref(caps);
}
for (i = 0; i < n_text; i++)
{
gchar *g_codec = NULL, *g_lang = NULL;
GstTagList *tags = NULL;
g_signal_emit_by_name (m_gst_playbin, "get-text-tags", i, &tags);
subtitleStream subs;
subs.language_code = "und";
#if GST_VERSION_MAJOR < 1
if (tags && gst_is_tag_list(tags))
#else
if (tags && GST_IS_TAG_LIST(tags))
#endif
{
if (gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang))
{
subs.language_code = g_lang;
g_free(g_lang);
}
gst_tag_list_get_string(tags, GST_TAG_SUBTITLE_CODEC, &g_codec);
gst_tag_list_free(tags);
}
eDebug("eServiceMP3::subtitle stream=%i language=%s codec=%s", i, subs.language_code.c_str(), g_codec ? g_codec : "(null)");
GstPad* pad = 0;
g_signal_emit_by_name (m_gst_playbin, "get-text-pad", i, &pad);
if ( pad )
g_signal_connect (G_OBJECT (pad), "notify::caps", G_CALLBACK (gstTextpadHasCAPS), this);
subs.type = getSubtitleType(pad, g_codec);
g_free(g_codec);
m_subtitleStreams.push_back(subs);
}
m_event((iPlayableService*)this, evUpdatedInfo);
if ( m_errorInfo.missing_codec != "" )
{
if (m_errorInfo.missing_codec.find("video/") == 0 || (m_errorInfo.missing_codec.find("audio/") == 0 && m_audioStreams.empty()))
m_event((iPlayableService*)this, evUser+12);
}
break;
}
case GST_MESSAGE_ELEMENT:
{
const GstStructure *msgstruct = gst_message_get_structure(msg);
if (msgstruct)
{
if ( gst_is_missing_plugin_message(msg) )
{
GstCaps *caps = NULL;
gst_structure_get (msgstruct, "detail", GST_TYPE_CAPS, &caps, NULL);
if (caps)
{
std::string codec = (const char*) gst_caps_to_string(caps);
gchar *description = gst_missing_plugin_message_get_description(msg);
if ( description )
{
eDebug("eServiceMP3::m_errorInfo.missing_codec = %s", codec.c_str());
m_errorInfo.error_message = "GStreamer plugin " + (std::string)description + " not available!\n";
m_errorInfo.missing_codec = codec.substr(0,(codec.find_first_of(',')));
g_free(description);
}
gst_caps_unref(caps);
}
}
else
{
const gchar *eventname = gst_structure_get_name(msgstruct);
if ( eventname )
{
if (!strcmp(eventname, "eventSizeChanged") || !strcmp(eventname, "eventSizeAvail"))
{
gst_structure_get_int (msgstruct, "aspect_ratio", &m_aspect);
gst_structure_get_int (msgstruct, "width", &m_width);
gst_structure_get_int (msgstruct, "height", &m_height);
if (strstr(eventname, "Changed"))
m_event((iPlayableService*)this, evVideoSizeChanged);
}
else if (!strcmp(eventname, "eventFrameRateChanged") || !strcmp(eventname, "eventFrameRateAvail"))
{
gst_structure_get_int (msgstruct, "frame_rate", &m_framerate);
if (strstr(eventname, "Changed"))
m_event((iPlayableService*)this, evVideoFramerateChanged);
}
else if (!strcmp(eventname, "eventProgressiveChanged") || !strcmp(eventname, "eventProgressiveAvail"))
{
gst_structure_get_int (msgstruct, "progressive", &m_progressive);
if (strstr(eventname, "Changed"))
m_event((iPlayableService*)this, evVideoProgressiveChanged);
}
else if (!strcmp(eventname, "redirect"))
{
const char *uri = gst_structure_get_string(msgstruct, "new-location");
// eDebug("redirect to %s", uri);
gst_element_set_state (m_gst_playbin, GST_STATE_NULL);
g_object_set(G_OBJECT (m_gst_playbin), "uri", uri, NULL);
gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
}
}
}
}
break;
}
case GST_MESSAGE_BUFFERING:
if (m_state == stRunning && m_sourceinfo.is_streaming)
{
GstBufferingMode mode;
gst_message_parse_buffering(msg, &(m_bufferInfo.bufferPercent));
// eDebug("Buffering %u percent done", m_bufferInfo.bufferPercent);
gst_message_parse_buffering_stats(msg, &mode, &(m_bufferInfo.avgInRate), &(m_bufferInfo.avgOutRate), &(m_bufferInfo.bufferingLeft));
m_event((iPlayableService*)this, evBuffering);
/*
* we don't react to buffer level messages, unless we are configured to use a prefill buffer
* (even if we are not configured to, we still use the buffer, but we rely on it to remain at the
* healthy level at all times, without ever having to pause the stream)
*
* Also, it does not make sense to pause the stream if it is a live stream
* (in which case the sink will not produce data while paused, so we won't
* recover from an empty buffer)
*/
if (m_use_prefillbuffer && !m_is_live && --m_ignore_buffering_messages <= 0)
{
if (m_bufferInfo.bufferPercent == 100)
{
GstState state;
gst_element_get_state(m_gst_playbin, &state, NULL, 0LL);
if (state != GST_STATE_PLAYING)
{
// eDebug("start playing");
gst_element_set_state (m_gst_playbin, GST_STATE_PLAYING);
}
/*
* when we start the pipeline, the contents of the buffer will immediately drain
* into the (hardware buffers of the) sinks, so we will receive low buffer level
* messages right away.
* Ignore the first few buffering messages, giving the buffer the chance to recover
* a bit, before we start handling empty buffer states again.
*/
m_ignore_buffering_messages = 5;
}
else if (m_bufferInfo.bufferPercent == 0)
{
// eDebug("start pause");
gst_element_set_state (m_gst_playbin, GST_STATE_PAUSED);
m_ignore_buffering_messages = 0;
}
else
{
m_ignore_buffering_messages = 0;
}
}
}
break;
case GST_MESSAGE_STREAM_STATUS:
{
GstStreamStatusType type;
GstElement *owner;
gst_message_parse_stream_status (msg, &type, &owner);
if ( type == GST_STREAM_STATUS_TYPE_CREATE && m_sourceinfo.is_streaming )
{
if ( GST_IS_PAD(source) )
owner = gst_pad_get_parent_element(GST_PAD(source));
else if ( GST_IS_ELEMENT(source) )
owner = GST_ELEMENT(source);
else
owner = 0;
if ( owner )
{
GstState state;
gst_element_get_state(m_gst_playbin, &state, NULL, 0LL);
GstElementFactory *factory = gst_element_get_factory(GST_ELEMENT(owner));
const gchar *name = gst_plugin_feature_get_name(GST_PLUGIN_FEATURE(factory));
if (!strcmp(name, "souphttpsrc") && (state == GST_STATE_READY) && !m_streamingsrc_timeout->isActive())
{
m_streamingsrc_timeout->start(HTTP_TIMEOUT*1000, true);
g_object_set (G_OBJECT (owner), "timeout", HTTP_TIMEOUT, NULL);
// eDebug("eServiceMP3::GST_STREAM_STATUS_TYPE_CREATE -> setting timeout on %s to %is", name, HTTP_TIMEOUT);
}
}
if ( GST_IS_PAD(source) )
gst_object_unref(owner);
}
break;
}
default:
break;
}
g_free (sourceName);
}
void eServiceMP3::handleMessage(GstMessage *msg)
{
if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_STATE_CHANGED && GST_MESSAGE_SRC(msg) != GST_OBJECT(m_gst_playbin))
{
/*
* ignore verbose state change messages for all active elements;
* we only need to handle state-change events for the playbin
*/
gst_message_unref(msg);
return;
}
m_pump.send(new GstMessageContainer(1, msg, NULL, NULL));
}
GstBusSyncReply eServiceMP3::gstBusSyncHandler(GstBus *bus, GstMessage *message, gpointer user_data)
{
eServiceMP3 *_this = (eServiceMP3*)user_data;
if (_this) _this->handleMessage(message);
return GST_BUS_DROP;
}
void eServiceMP3::playbinNotifySource(GObject *object, GParamSpec *unused, gpointer user_data)
{
GstElement *source = NULL;
eServiceMP3 *_this = (eServiceMP3*)user_data;
g_object_get(object, "source", &source, NULL);
if (source)
{
if (g_object_class_find_property(G_OBJECT_GET_CLASS(source), "ssl-strict") != 0)
{
g_object_set(G_OBJECT(source), "ssl-strict", FALSE, NULL);
}
if (g_object_class_find_property(G_OBJECT_GET_CLASS(source), "user-agent") != 0 && !_this->m_useragent.empty())
{
g_object_set(G_OBJECT(source), "user-agent", _this->m_useragent.c_str(), NULL);
}
if (g_object_class_find_property(G_OBJECT_GET_CLASS(source), "extra-headers") != 0 && !_this->m_extra_headers.empty())
{
#if GST_VERSION_MAJOR < 1
GstStructure *extras = gst_structure_empty_new("extras");
#else
GstStructure *extras = gst_structure_new_empty("extras");
#endif
size_t pos = 0;
while (pos != std::string::npos)
{
std::string name, value;
size_t start = pos;
size_t len = std::string::npos;
pos = _this->m_extra_headers.find(':', pos);
if (pos != std::string::npos)
{
len = pos - start;
pos++;
name = _this->m_extra_headers.substr(start, len);
start = pos;
len = std::string::npos;
pos = _this->m_extra_headers.find('|', pos);
if (pos != std::string::npos)
{
len = pos - start;
pos++;
}
value = _this->m_extra_headers.substr(start, len);
}
if (!name.empty() && !value.empty())
{
GValue header;
// eDebug("setting extra-header '%s:%s'", name.c_str(), value.c_str());
memset(&header, 0, sizeof(GValue));
g_value_init(&header, G_TYPE_STRING);
g_value_set_string(&header, value.c_str());
gst_structure_set_value(extras, name.c_str(), &header);
}
else
{
eDebug("Invalid header format %s", _this->m_extra_headers.c_str());
break;
}
}
if (gst_structure_n_fields(extras) > 0)
{
g_object_set(G_OBJECT(source), "extra-headers", extras, NULL);
}
gst_structure_free(extras);
}
gst_object_unref(source);
}
}
void eServiceMP3::handleElementAdded(GstBin *bin, GstElement *element, gpointer user_data)
{
eServiceMP3 *_this = (eServiceMP3*)user_data;
if (_this)
{
gchar *elementname = gst_element_get_name(element);
if (g_str_has_prefix(elementname, "queue2"))
{
if (_this->m_download_buffer_path != "")
{
g_object_set(G_OBJECT(element), "temp-template", _this->m_download_buffer_path.c_str(), NULL);
}
else
{
g_object_set(G_OBJECT(element), "temp-template", NULL, NULL);
}
}
else if (g_str_has_prefix(elementname, "uridecodebin")
#if GST_VERSION_MAJOR < 1
|| g_str_has_prefix(elementname, "decodebin2"))
#else
|| g_str_has_prefix(elementname, "decodebin"))
#endif
{
/*
* Listen for queue2 element added to uridecodebin/decodebin2 as well.
* Ignore other bins since they may have unrelated queues
*/
g_signal_connect(element, "element-added", G_CALLBACK(handleElementAdded), user_data);
}
g_free(elementname);
}
}
audiotype_t eServiceMP3::gstCheckAudioPad(GstStructure* structure)
{
if (!structure)
return atUnknown;
if ( gst_structure_has_name (structure, "audio/mpeg"))
{
gint mpegversion, layer = -1;
if (!gst_structure_get_int (structure, "mpegversion", &mpegversion))
return atUnknown;
switch (mpegversion) {
case 1:
{
gst_structure_get_int (structure, "layer", &layer);
if ( layer == 3 )
return atMP3;
else
return atMPEG;
break;
}
case 2:
return atAAC;
case 4:
return atAAC;
default:
return atUnknown;
}
}
else if ( gst_structure_has_name (structure, "audio/x-ac3") || gst_structure_has_name (structure, "audio/ac3") )
return atAC3;
else if ( gst_structure_has_name (structure, "audio/x-dts") || gst_structure_has_name (structure, "audio/dts") )
return atDTS;
#if GST_VERSION_MAJOR < 1
else if ( gst_structure_has_name (structure, "audio/x-raw-int") )
#else
else if ( gst_structure_has_name (structure, "audio/x-raw") )
#endif
return atPCM;
return atUnknown;
}
void eServiceMP3::gstPoll(ePtr<GstMessageContainer> const &msg)
{
switch (msg->getType())
{
case 1:
{
GstMessage *gstmessage = *((GstMessageContainer*)msg);
if (gstmessage)
{
gstBusCall(gstmessage);
}
break;
}
case 2:
{
GstBuffer *buffer = *((GstMessageContainer*)msg);
if (buffer)
{
pullSubtitle(buffer);
}
break;
}
case 3:
{
GstPad *pad = *((GstMessageContainer*)msg);
gstTextpadHasCAPS_synced(pad);
break;
}
}
}
eAutoInitPtr<eServiceFactoryMP3> init_eServiceFactoryMP3(eAutoInitNumbers::service+1, "eServiceFactoryMP3");
void eServiceMP3::gstCBsubtitleAvail(GstElement *subsink, GstBuffer *buffer, gpointer user_data)
{
eServiceMP3 *_this = (eServiceMP3*)user_data;
if (_this->m_currentSubtitleStream < 0)
{
if (buffer) gst_buffer_unref(buffer);
return;
}
_this->m_pump.send(new GstMessageContainer(2, NULL, NULL, buffer));
}
void eServiceMP3::gstTextpadHasCAPS(GstPad *pad, GParamSpec * unused, gpointer user_data)
{
eServiceMP3 *_this = (eServiceMP3*)user_data;
gst_object_ref (pad);
_this->m_pump.send(new GstMessageContainer(3, NULL, pad, NULL));
}
void eServiceMP3::gstTextpadHasCAPS_synced(GstPad *pad)
{
GstCaps *caps = NULL;
g_object_get (G_OBJECT (pad), "caps", &caps, NULL);
if (caps)
{
subtitleStream subs;
// eDebug("gstTextpadHasCAPS:: signal::caps = %s", gst_caps_to_string(caps));
// eDebug("gstGhostpadHasCAPS_synced %p %d", pad, m_subtitleStreams.size());
if (m_currentSubtitleStream >= 0 && m_currentSubtitleStream < (int)m_subtitleStreams.size())
subs = m_subtitleStreams[m_currentSubtitleStream];
else {
subs.type = stUnknown;
subs.pad = pad;
}
if ( subs.type == stUnknown )
{
GstTagList *tags = NULL;
gchar *g_lang = NULL;
g_signal_emit_by_name (m_gst_playbin, "get-text-tags", m_currentSubtitleStream, &tags);
subs.language_code = "und";
subs.type = getSubtitleType(pad);
#if GST_VERSION_MAJOR < 1
if (tags && gst_is_tag_list(tags))
#else
if (tags && GST_IS_TAG_LIST(tags))
#endif
{
if (gst_tag_list_get_string(tags, GST_TAG_LANGUAGE_CODE, &g_lang))
{
subs.language_code = std::string(g_lang);
g_free(g_lang);
}
}
if (m_currentSubtitleStream >= 0 && m_currentSubtitleStream < (int)m_subtitleStreams.size())
m_subtitleStreams[m_currentSubtitleStream] = subs;
else
m_subtitleStreams.push_back(subs);
}
// eDebug("gstGhostpadHasCAPS:: m_gst_prev_subtitle_caps=%s equal=%i",gst_caps_to_string(m_gst_prev_subtitle_caps),gst_caps_is_equal(m_gst_prev_subtitle_caps, caps));
gst_caps_unref (caps);
}
}
void eServiceMP3::pullSubtitle(GstBuffer *buffer)
{
if (buffer && m_currentSubtitleStream >= 0 && m_currentSubtitleStream < (int)m_subtitleStreams.size())
{
#if GST_VERSION_MAJOR < 1
gint64 buf_pos = GST_BUFFER_TIMESTAMP(buffer);
size_t len = GST_BUFFER_SIZE(buffer);
#else
GstMapInfo map;
if(!gst_buffer_map(buffer, &map, GST_MAP_READ))
{
eDebug("eServiceMP3::pullSubtitle gst_buffer_map failed");
return;
}
gint64 buf_pos = GST_BUFFER_PTS(buffer);
size_t len = map.size;
eDebug("gst_buffer_get_size %zu map.size %zu", gst_buffer_get_size(buffer), len);
#endif
gint64 duration_ns = GST_BUFFER_DURATION(buffer);
int subType = m_subtitleStreams[m_currentSubtitleStream].type;
// eDebug("pullSubtitle type=%d size=%zu", subType, len);
if ( subType )
{
if ( subType < stVOB )
{
int delay = eConfigManager::getConfigIntValue("config.subtitles.pango_subtitles_delay");
int subtitle_fps = eConfigManager::getConfigIntValue("config.subtitles.pango_subtitles_fps");
double convert_fps = 1.0;
if (subtitle_fps > 1 && m_framerate > 0)
convert_fps = subtitle_fps / (double)m_framerate;
#if GST_VERSION_MAJOR < 1
std::string line((const char*)GST_BUFFER_DATA(buffer), len);
#else
std::string line((const char*)map.data, len);
#endif
// eDebug("got new text subtitle @ buf_pos = %lld ns (in pts=%lld), dur=%lld: '%s' ", buf_pos, buf_pos/11111, duration_ns, line.c_str());
uint32_t start_ms = ((buf_pos / 1000000ULL) * convert_fps) + delay;
uint32_t end_ms = start_ms + (duration_ns / 1000000ULL);
m_subtitle_pages.insert(subtitle_pages_map_pair_t(end_ms, subtitle_page_t(start_ms, end_ms, line)));
m_subtitle_sync_timer->start(1, true);
}
else
{
eDebug("unsupported subpicture... ignoring");
}
}
#if GST_VERSION_MAJOR >= 1
gst_buffer_unmap(buffer, &map);
#endif
}
}
void eServiceMP3::pushSubtitles()
{
pts_t running_pts = 0;
int32_t next_timer = 0, decoder_ms, start_ms, end_ms, diff_start_ms, diff_end_ms;
subtitle_pages_map_t::iterator current;
// wait until clock is stable
if (getPlayPosition(running_pts) < 0)
m_decoder_time_valid_state = 0;
if (m_decoder_time_valid_state < 4)
{
m_decoder_time_valid_state++;
if (m_prev_decoder_time == running_pts)
m_decoder_time_valid_state = 0;
if (m_decoder_time_valid_state < 4)
{
//eDebug("*** push subtitles, waiting for clock to stabilise");
m_prev_decoder_time = running_pts;
next_timer = 50;
goto exit;
}
//eDebug("*** push subtitles, clock stable");
}
decoder_ms = running_pts / 90;
#if 0
// eDebug("\n*** all subs: ");
for (current = m_subtitle_pages.begin(); current != m_subtitle_pages.end(); current++)
{
start_ms = current->second.start_ms;
end_ms = current->second.end_ms;
diff_start_ms = start_ms - decoder_ms;
diff_end_ms = end_ms - decoder_ms;
// eDebug(" start: %d, end: %d, diff_start: %d, diff_end: %d: %s",
start_ms, end_ms, diff_start_ms, diff_end_ms, current->second.text.c_str());
}
// eDebug("\n\n");
#endif
for (current = m_subtitle_pages.lower_bound(decoder_ms); current != m_subtitle_pages.end(); current++)
{
start_ms = current->second.start_ms;
end_ms = current->second.end_ms;
diff_start_ms = start_ms - decoder_ms;
diff_end_ms = end_ms - decoder_ms;
#if 0
// eDebug("*** next subtitle: decoder: %d, start: %d, end: %d, duration_ms: %d, diff_start: %d, diff_end: %d : %s",
decoder_ms, start_ms, end_ms, end_ms - start_ms, diff_start_ms, diff_end_ms, current->second.text.c_str());
#endif
if (diff_end_ms < 0)
{
//eDebug("*** current sub has already ended, skip: %d\n", diff_end_ms);
continue;
}
if (diff_start_ms > 20)
{
//eDebug("*** current sub in the future, start timer, %d\n", diff_start_ms);
next_timer = diff_start_ms;
goto exit;
}
// showtime
if (m_subtitle_widget)
{
//eDebug("*** current sub actual, show!");
ePangoSubtitlePage pango_page;
gRGB rgbcol(0xD0,0xD0,0xD0);
pango_page.m_elements.push_back(ePangoSubtitlePageElement(rgbcol, current->second.text.c_str()));
pango_page.m_show_pts = start_ms * 90; // actually completely unused by widget!
if (!m_subtitles_paused)
pango_page.m_timeout = end_ms - decoder_ms; // take late start into account
else
pango_page.m_timeout = 60000; //paused, subs must stay on (60s for now), avoid timeout in lib/gui/esubtitle.cpp: m_hide_subtitles_timer->start(m_pango_page.m_timeout, true);
m_subtitle_widget->setPage(pango_page);
}
//eDebug("*** no next sub scheduled, check NEXT subtitle");
}
// no more subs in cache, fall through
exit:
if (next_timer == 0)
{
//eDebug("*** next timer = 0, set default timer!");
next_timer = 1000;
}
m_subtitle_sync_timer->start(next_timer, true);
// eDebug("\n\n");
}
RESULT eServiceMP3::enableSubtitles(iSubtitleUser *user, struct SubtitleTrack &track)
{
if (m_currentSubtitleStream != track.pid)
{
g_object_set (G_OBJECT (m_gst_playbin), "current-text", -1, NULL);
m_subtitle_sync_timer->stop();
m_subtitle_pages.clear();
m_prev_decoder_time = -1;
m_decoder_time_valid_state = 0;
m_currentSubtitleStream = track.pid;
m_cachedSubtitleStream = m_currentSubtitleStream;
g_object_set (G_OBJECT (m_gst_playbin), "current-text", m_currentSubtitleStream, NULL);
m_subtitle_widget = user;
eDebug ("eServiceMP3::switched to subtitle stream %i", m_currentSubtitleStream);
#ifdef GSTREAMER_SUBTITLE_SYNC_MODE_BUG
/*
* when we're running the subsink in sync=false mode,
* we have to force a seek, before the new subtitle stream will start
*/
seekRelative(-1, 90000);
#endif
}
return 0;
}
RESULT eServiceMP3::disableSubtitles()
{
eDebug("eServiceMP3::disableSubtitles");
m_currentSubtitleStream = -1;
m_cachedSubtitleStream = m_currentSubtitleStream;
g_object_set (G_OBJECT (m_gst_playbin), "current-text", m_currentSubtitleStream, NULL);
m_subtitle_sync_timer->stop();
m_subtitle_pages.clear();
m_prev_decoder_time = -1;
m_decoder_time_valid_state = 0;
if (m_subtitle_widget) m_subtitle_widget->destroy();
m_subtitle_widget = 0;
return 0;
}
RESULT eServiceMP3::getCachedSubtitle(struct SubtitleTrack &track)
{
bool autoturnon = eConfigManager::getConfigBoolValue("config.subtitles.pango_autoturnon", true);
if (!autoturnon)
return -1;
if (m_cachedSubtitleStream >= 0 && m_cachedSubtitleStream < (int)m_subtitleStreams.size())
{
track.type = 2;
track.pid = m_cachedSubtitleStream;
track.page_number = int(m_subtitleStreams[m_cachedSubtitleStream].type);
track.magazine_number = 0;
return 0;
}
return -1;
}
RESULT eServiceMP3::getSubtitleList(std::vector<struct SubtitleTrack> &subtitlelist)
{
// eDebug("eServiceMP3::getSubtitleList");
int stream_idx = 0;
for (std::vector<subtitleStream>::iterator IterSubtitleStream(m_subtitleStreams.begin()); IterSubtitleStream != m_subtitleStreams.end(); ++IterSubtitleStream)
{
subtype_t type = IterSubtitleStream->type;
switch(type)
{
case stUnknown:
case stVOB:
case stPGS:
break;
default:
{
struct SubtitleTrack track;
track.type = 2;
track.pid = stream_idx;
track.page_number = int(type);
track.magazine_number = 0;
track.language_code = IterSubtitleStream->language_code;
subtitlelist.push_back(track);
}
}
stream_idx++;
}
// eDebug("eServiceMP3::getSubtitleList finished");
return 0;
}
RESULT eServiceMP3::streamed(ePtr<iStreamedService> &ptr)
{
ptr = this;
return 0;
}
ePtr<iStreamBufferInfo> eServiceMP3::getBufferCharge()
{
return new eStreamBufferInfo(m_bufferInfo.bufferPercent, m_bufferInfo.avgInRate, m_bufferInfo.avgOutRate, m_bufferInfo.bufferingLeft, m_buffer_size);
}
int eServiceMP3::setBufferSize(int size)
{
m_buffer_size = size;
g_object_set (G_OBJECT (m_gst_playbin), "buffer-size", m_buffer_size, NULL);
return 0;
}
int eServiceMP3::getAC3Delay()
{
return ac3_delay;
}
int eServiceMP3::getPCMDelay()
{
return pcm_delay;
}
void eServiceMP3::setAC3Delay(int delay)
{
ac3_delay = delay;
if (!m_gst_playbin || m_state != stRunning)
return;
else
{
int config_delay_int = delay;
/*
* NOTE: We only look for dvbmediasinks.
* If either the video or audio sink is of a different type,
* we have no chance to get them synced anyway.
*/
if (videoSink)
{
config_delay_int += eConfigManager::getConfigIntValue("config.av.generalAC3delay");
}
else
{
// eDebug("dont apply ac3 delay when no video is running!");
config_delay_int = 0;
}
if (audioSink)
{
eTSMPEGDecoder::setHwAC3Delay(config_delay_int);
}
}
}
void eServiceMP3::setPCMDelay(int delay)
{
pcm_delay = delay;
if (!m_gst_playbin || m_state != stRunning)
return;
else
{
int config_delay_int = delay;
/*
* NOTE: We only look for dvbmediasinks.
* If either the video or audio sink is of a different type,
* we have no chance to get them synced anyway.
*/
if (videoSink)
{
config_delay_int += eConfigManager::getConfigIntValue("config.av.generalPCMdelay");
}
else
{
// eDebug("dont apply pcm delay when no video is running!");
config_delay_int = 0;
}
if (audioSink)
{
eTSMPEGDecoder::setHwPCMDelay(config_delay_int);
}
}
}
| opendroid-Team/enigma2-4.1 | lib/service/servicemp3.cpp | C++ | gpl-2.0 | 67,814 |
<?php
function plugin_beforescript_convert()
{
global $vars;
$qm = get_qm();
$page = $vars['page'];
if (! (PKWK_READONLY > 0 or is_freeze($page) or plugin_beforescript_is_edit_auth($page))) {
return $qm->replace('fmt_err_not_editable', '#html', $page);
}
$args = func_get_args();
$addscript = array_pop($args);
$qt = get_qt();
$qt->appendv('beforescript', $addscript);
return "";
}
function plugin_beforescript_is_edit_auth($page, $user = '')
{
global $edit_auth, $edit_auth_pages, $auth_method_type;
if (! $edit_auth) {
return FALSE;
}
// Checked by:
$target_str = '';
if ($auth_method_type == 'pagename') {
$target_str = $page; // Page name
} else if ($auth_method_type == 'contents') {
$target_str = join('', get_source($page)); // Its contents
}
foreach($edit_auth_pages as $regexp => $users) {
if (preg_match($regexp, $target_str)) {
if ($user == '' || in_array($user, explode(',', $users))) {
return TRUE;
}
}
}
return FALSE;
}
?>
| open-qhm/qhm | plugin/beforescript.inc.php | PHP | gpl-2.0 | 990 |
<?php
/**************
* @package WordPress
* @subpackage Cuckoothemes
* @since Cuckoothemes 1.0
* URL http://cuckoothemes.com
**************
*
*
*
** Name : Button shortcodes
*/
function shortcode_button( $atts, $content = null) {
extract(shortcode_atts(array(
"title" => 'Button Title',
"color" => '#4F4F4F',
"titlecolor" => '#ffffff',
"width" => '225px',
"url" => 'http://www.cuckoothemes.com',
"target" => '',
"left" => '',
"top" => '',
"right" => '',
"bottom"=> ''
), $atts));
switch(isset($atts["align"]) ? $atts["align"] : ''){
case 'left':
$align = 'alignleft';
break;
case 'right':
$align = 'alignright';
break;
default :
$align = 'alignnone';
break;
}
$left = ($left == null ? '' : ' margin-left:'.$left.';');
$right = ($right == null ? '' : ' margin-right:'.$right.';');
$top = ($top == null ? '' : ' margin-top:'.$top.';');
$bottom = ($bottom == null ? '' : ' margin-bottom:'.$bottom.';');
$color = ($color == null ? '' : ' background-color:'.$color.';');
$titlecolor = ( $titlecolor == null ? '' : ' color:'.$titlecolor.'!important;' );
$width = ( $width == null ? '' : ' width:'.$width.';' );
$style = 'style="' .$titlecolor.$color.$left.$right.$top.$bottom.$width. '"';
$target_show = ($target == null ? '' : 'target="'.$target.'"');
return '<a class="btn-short '.$align.'" '.$style.' title="'.$title.'" '.$target_show.' href="'.$url.'">'.wptexturize($title).'</a>';
}
add_shortcode('btn', 'shortcode_button');
?> | rlhardrock/buhos | wp-content/themes/cuckootap/cuckootap/admin/shortcodes/button/button_shortcodes.php | PHP | gpl-2.0 | 1,544 |
jQuery('.js_mobile_menu').click(function(){
jQuery('body').toggleClass('mobile_menu_opened');
}); | saintcode/cenotexplore | src/wordpress/wp-content/themes/cenotexplore/js/main.js | JavaScript | gpl-2.0 | 101 |
package org.itomi.kakuro.model;
import java.util.Observable;
import org.itomi.kakuro.integer.Tuple;
import org.itomi.kakuro.model.grid.Density;
import org.itomi.kakuro.model.grid.Grid;
import org.itomi.kakuro.model.grid.ImmutableSubMatrix;
public class KakuroInstance extends Observable {
private int horizontal;
private int vertical;
private Grid grid;
public KakuroInstance(int x, int y) {
this.horizontal = x;
this.vertical = y;
grid = new Grid().initialize(x, y);
}
public Grid getGrid() {
return grid;
}
public int getHorizontalLength() {
return horizontal;
}
public int getVerticalLength() {
return vertical;
}
public void notifyObservers() {
notifyObservers(this);
}
public Density getDensity() {
return grid.getFillProportion();
}
public ImmutableSubMatrix getNeighbours(Tuple<Integer, Integer> position) {
return grid.getNeighbours(position);
}
}
| itomi/kakuro | CommonFiles/src/org/itomi/kakuro/model/KakuroInstance.java | Java | gpl-2.0 | 955 |
import Vue from 'vue'
import App from './App.vue'
import vuetify from './plugins/vuetify';
import store from './plugins/store'
import router from './plugins/router'
import '@mdi/font/css/materialdesignicons.css'
import './style.scss'
Vue.config.productionTip = false
new Vue({
vuetify,
store,
router,
render: h => h(App)
}).$mount('#app')
| kevashcraft/EagleLogger | app/src/main.js | JavaScript | gpl-2.0 | 350 |
<?php
namespace Intraxia\Gistpen\View;
use Intraxia\Gistpen\Contract\Templating;
use Intraxia\Gistpen\Params\Repository as Params;
use Intraxia\Jaxion\Contract\Core\HasActions;
use Intraxia\Jaxion\Contract\Core\HasFilters;
/**
* This class registers all of the settings page views
*
* @package WP_Gistpen
* @author James DiGioia <jamesorodig@gmail.com>
* @link http://jamesdigioia.com/wp-gistpen/
* @since 0.5.0
*/
class Settings implements HasActions, HasFilters {
/**
* Params service.
*
* @var Params
*/
private $params;
/**
* Templating service.
*
* @var Templating
*/
protected $template;
/**
* Plugin basename.
*
* @var string
*/
protected $basename;
/**
* Site URL.
*
* @var string
*/
protected $url;
/**
* Initialize the class and set its properties.
*
* @param Params $params
* @param Templating $template
* @param string $basename
* @param string $url
*
* @internal param Site $site
* @internal param EntityManager $em
* @since 0.5.0
*/
public function __construct( Params $params, Templating $template, $basename, $url ) {
$this->params = $params;
$this->template = $template;
$this->basename = $basename;
$this->url = $url;
}
/**
* Register the administration menu for this plugin into the WordPress Dashboard menu.
*
* @since 0.1.0
*/
public function add_plugin_admin_menu() {
add_options_page(
__( 'WP-Gistpen Settings', 'wp-gistpen' ),
__( 'Gistpens', 'wp-gistpen' ),
'edit_posts',
'wp-gistpen',
array( $this, 'display_plugin_admin_page' )
);
}
/**
* Render the settings page for this plugin.
*
* @since 0.1.0
*/
public function display_plugin_admin_page() {
echo '<div id="settings-app"></div>';
}
/**
* Add settings action link to the plugins page.
*
* @since 0.1.0
*
* @param array $links
*
* @return array
*/
public function add_action_links( $links ) {
return array_merge(
array(
'settings' => '<a href="' . admin_url( 'options-general.php?page=wp-gistpen' ) . '">' . __( 'Settings', 'wp-gistpen' ) . '</a>',
),
$links
);
}
/**
* Register the settings page (obviously)
*
* @since 0.3.0
*/
public function register_setting() {
register_setting( 'wp-gistpen', 'wp-gistpen' );
}
/**
* {@inheritDoc}
*
* @return array[]
*/
public function action_hooks() {
return array(
array(
'hook' => 'admin_menu',
'method' => 'add_plugin_admin_menu',
),
array(
'hook' => 'admin_init',
'method' => 'register_setting',
),
);
}
/**
* {@inheritDoc}
*
* @return array[]
*/
public function filter_hooks() {
return array(
array(
'hook' => 'plugin_action_links_' . $this->basename,
'method' => 'add_action_links',
),
);
}
}
| mAAdhaTTah/WP-Gistpen | app/View/Settings.php | PHP | gpl-2.0 | 2,831 |
/*
* *************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
* *************************************************************************************
*/
package com.espertech.esper.client.hook;
/**
* Factory for {@link VirtualDataWindow}.
* <p>
* Register an implementation of this interface with the engine before use:
* configuration.addPlugInVirtualDataWindow("test", "vdw", SupportVirtualDWFactory.class.getName());
*/
public interface VirtualDataWindowFactory {
/**
* Return a virtual data window to handle the specific event type, named window or paramaters
* as provided in the context.
* @param context provides contextual information such as event type, named window name and parameters.
* @return virtual data window
*/
public VirtualDataWindow create(VirtualDataWindowContext context);
}
| intelie/esper | esper/src/main/java/com/espertech/esper/client/hook/VirtualDataWindowFactory.java | Java | gpl-2.0 | 1,433 |
package de.hsbremen.kss.genetic.selection;
import java.util.List;
import org.apache.commons.lang3.Validate;
import de.hsbremen.kss.model.Plan;
import de.hsbremen.kss.util.RandomUtils;
public class OnlyTheBestSelection implements Selection {
private final RandomUtils randomUtils;
private final double best;
public OnlyTheBestSelection(final RandomUtils randomUtils, final double best) {
Validate.inclusiveBetween(0, 1, best);
this.randomUtils = randomUtils;
this.best = best;
}
@Override
public Plan select(final List<Plan> sortedPopulation) {
final int num = (int) (sortedPopulation.size() * this.best);
return this.randomUtils.randomElement(sortedPopulation.subList(0, num));
}
}
| hvoss/logistik | src/main/java/de/hsbremen/kss/genetic/selection/OnlyTheBestSelection.java | Java | gpl-2.0 | 760 |
<?php
App::uses('Planet', 'Model');
/**
* Planet Test Case
*
*/
class PlanetTest extends CakeTestCase {
/**
* Fixtures
*
* @var array
*/
public $fixtures = array(
'app.planet'
);
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->Planet = ClassRegistry::init('Planet');
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
unset($this->Planet);
parent::tearDown();
}
}
| tommykrueger/ExoPlanetSystems | backend/app/Test/Case/Model/PlanetTest.php | PHP | gpl-2.0 | 464 |
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Paypal\Test\Unit\Model\Payflow;
use Magento\Paypal\Model\Config;
use Magento\Paypal\Model\Info;
use Magento\Paypal\Model\Payflow\AvsEmsCodeMapper;
use Magento\Sales\Api\Data\OrderPaymentInterface;
use PHPUnit_Framework_MockObject_MockObject as MockObject;
class AvsEmsCodeMapperTest extends \PHPUnit\Framework\TestCase
{
/**
* @var AvsEmsCodeMapper
*/
private $mapper;
/**
* @inheritdoc
*/
protected function setUp()
{
$this->mapper = new AvsEmsCodeMapper();
}
/**
* Checks different variations for AVS codes mapping.
*
* @covers \Magento\Paypal\Model\Payflow\AvsEmsCodeMapper::getCode
* @param string $avsZip
* @param string $avsStreet
* @param string $expected
* @dataProvider getCodeDataProvider
*/
public function testGetCode($avsZip, $avsStreet, $expected)
{
/** @var OrderPaymentInterface|MockObject $orderPayment */
$orderPayment = $this->getMockBuilder(OrderPaymentInterface::class)
->disableOriginalConstructor()
->getMock();
$orderPayment->expects(self::once())
->method('getMethod')
->willReturn(Config::METHOD_PAYFLOWPRO);
$orderPayment->expects(self::once())
->method('getAdditionalInformation')
->willReturn([
Info::PAYPAL_AVSZIP => $avsZip,
Info::PAYPAL_AVSADDR => $avsStreet
]);
self::assertEquals($expected, $this->mapper->getCode($orderPayment));
}
/**
* Checks a test case, when payment order is not Payflow payment method.
*
* @covers \Magento\Paypal\Model\Payflow\AvsEmsCodeMapper::getCode
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The "some_payment" does not supported by Payflow AVS mapper.
*/
public function testGetCodeWithException()
{
/** @var OrderPaymentInterface|MockObject $orderPayment */
$orderPayment = $this->getMockBuilder(OrderPaymentInterface::class)
->disableOriginalConstructor()
->getMock();
$orderPayment->expects(self::exactly(2))
->method('getMethod')
->willReturn('some_payment');
$this->mapper->getCode($orderPayment);
}
/**
* Gets list of AVS codes.
*
* @return array
*/
public function getCodeDataProvider()
{
return [
['avsZip' => null, 'avsStreet' => null, 'expected' => ''],
['avsZip' => null, 'avsStreet' => 'Y', 'expected' => ''],
['avsZip' => 'Y', 'avsStreet' => null, 'expected' => ''],
['avsZip' => 'Y', 'avsStreet' => 'Y', 'expected' => 'Y'],
['avsZip' => 'N', 'avsStreet' => 'Y', 'expected' => 'A'],
['avsZip' => 'Y', 'avsStreet' => 'N', 'expected' => 'Z'],
['avsZip' => 'N', 'avsStreet' => 'N', 'expected' => 'N'],
['avsZip' => 'X', 'avsStreet' => 'Y', 'expected' => ''],
['avsZip' => 'N', 'avsStreet' => 'X', 'expected' => ''],
['avsZip' => '', 'avsStreet' => 'Y', 'expected' => ''],
['avsZip' => 'N', 'avsStreet' => '', 'expected' => '']
];
}
}
| kunj1988/Magento2 | app/code/Magento/Paypal/Test/Unit/Model/Payflow/AvsEmsCodeMapperTest.php | PHP | gpl-2.0 | 3,347 |
<?php
// +--------------------------------------------------------------------------+
// | Image_Graph aka GraPHPite |
// +--------------------------------------------------------------------------+
// | Copyright (C) 2003, 2004 Jesper Veggerby Hansen |
// | Email pear.nosey@veggerby.dk |
// | Web http://graphpite.sourceforge.net |
// | PEAR http://pear.php.net/pepr/pepr-proposal-show.php?id=145 |
// +--------------------------------------------------------------------------+
// | 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 |
// +--------------------------------------------------------------------------+
/**
* Image_Graph aka GraPHPite - PEAR PHP OO Graph Rendering Utility.
* @package layout
* @copyright Copyright (C) 2003, 2004 Jesper Veggerby Hansen
* @license http://www.gnu.org/licenses/lgpl.txt GNU Lesser General Public License
* @author Jesper Veggerby Hansen <pear.nosey@veggerby.dk>
* @version $Id: Constants.php,v 1.1 2008/01/24 01:06:07 tye Exp $
*/
/**
* Define the area to be maximized
*/
define("IMAGE_GRAPH_AREA_MAX", 0);
/**
* Define the area to be left aligned
*/
define("IMAGE_GRAPH_AREA_LEFT", 1);
/**
* Define the area to be top aligned
*/
define("IMAGE_GRAPH_AREA_TOP", 2);
/**
* Define the area to be right aligned
*/
define("IMAGE_GRAPH_AREA_RIGHT", 3);
/**
* Define the area to be bottom aligned
*/
define("IMAGE_GRAPH_AREA_BOTTOM", 4);
/**
* Define the area to have an absoute position
*/
define("IMAGE_GRAPH_AREA_ABSOLUTE", 5);
/**
* Define an area size to be absolute, ie. exact pixel size
*/
define("IMAGE_GRAPH_POS_ABSOLUTE", 0);
/**
* Define an area size to be relative, ie. percentage of "total size"
*/
define("IMAGE_GRAPH_POS_RELATIVE", 1);
?> | cuong09m/krwe | emailmarketer/admin/functions/amcharts/graphpite/Image/Graph/Layout/Constants.php | PHP | gpl-2.0 | 2,942 |
class UserPrizesController < UserResourcesController
end
| ifunam/salva | app/controllers/user_prizes_controller.rb | Ruby | gpl-2.0 | 57 |
#!/usr/bin/env python
# This is the MIT License
# http://www.opensource.org/licenses/mit-license.php
#
# Copyright (c) 2007,2008 Nick Galbreath
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#
# Version 1.0 - 21-Apr-2007
# initial
# Version 2.0 - 16-Nov-2008
# made class Gmetric thread safe
# made gmetrix xdr writers _and readers_
# Now this only works for gmond 2.X packets, not tested with 3.X
#
# Version 3.0 - 09-Jan-2011 Author: Vladimir Vuksan
# Made it work with the Ganglia 3.1 data format
#
# Version 3.1 - 30-Apr-2011 Author: Adam Tygart
# Added Spoofing support
from xdrlib import Packer, Unpacker
import socket, re
slope_str2int = {'zero':0,
'positive':1,
'negative':2,
'both':3,
'unspecified':4}
# could be autogenerated from previous but whatever
slope_int2str = {0: 'zero',
1: 'positive',
2: 'negative',
3: 'both',
4: 'unspecified'}
class Gmetric:
"""
Class to send gmetric/gmond 2.X packets
Thread safe
"""
type = ('', 'string', 'uint16', 'int16', 'uint32', 'int32', 'float',
'double', 'timestamp')
protocol = ('udp', 'multicast')
def __init__(self, host, port, protocol):
if protocol not in self.protocol:
raise ValueError("Protocol must be one of: " + str(self.protocol))
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if protocol == 'multicast':
self.socket.setsockopt(socket.IPPROTO_IP,
socket.IP_MULTICAST_TTL, 20)
self.hostport = (host, int(port))
#self.socket.connect(self.hostport)
def send(self, NAME, VAL, TYPE='', UNITS='', SLOPE='both',
TMAX=60, DMAX=0, GROUP="", SPOOF=""):
if SLOPE not in slope_str2int:
raise ValueError("Slope must be one of: " + str(self.slope.keys()))
if TYPE not in self.type:
raise ValueError("Type must be one of: " + str(self.type))
if len(NAME) == 0:
raise ValueError("Name must be non-empty")
( meta_msg, data_msg ) = gmetric_write(NAME, VAL, TYPE, UNITS, SLOPE, TMAX, DMAX, GROUP, SPOOF)
# print msg
self.socket.sendto(meta_msg, self.hostport)
self.socket.sendto(data_msg, self.hostport)
def gmetric_write(NAME, VAL, TYPE, UNITS, SLOPE, TMAX, DMAX, GROUP, SPOOF):
"""
Arguments are in all upper-case to match XML
"""
packer = Packer()
HOSTNAME="test"
if SPOOF == "":
SPOOFENABLED=0
else :
SPOOFENABLED=1
# Meta data about a metric
packer.pack_int(128)
if SPOOFENABLED == 1:
packer.pack_string(SPOOF)
else:
packer.pack_string(HOSTNAME)
packer.pack_string(NAME)
packer.pack_int(SPOOFENABLED)
packer.pack_string(TYPE)
packer.pack_string(NAME)
packer.pack_string(UNITS)
packer.pack_int(slope_str2int[SLOPE]) # map slope string to int
packer.pack_uint(int(TMAX))
packer.pack_uint(int(DMAX))
# Magic number. Indicates number of entries to follow. Put in 1 for GROUP
if GROUP == "":
packer.pack_int(0)
else:
packer.pack_int(1)
packer.pack_string("GROUP")
packer.pack_string(GROUP)
# Actual data sent in a separate packet
data = Packer()
data.pack_int(128+5)
if SPOOFENABLED == 1:
data.pack_string(SPOOF)
else:
data.pack_string(HOSTNAME)
data.pack_string(NAME)
data.pack_int(SPOOFENABLED)
data.pack_string("%s")
data.pack_string(str(VAL))
return ( packer.get_buffer() , data.get_buffer() )
def gmetric_read(msg):
unpacker = Unpacker(msg)
values = dict()
unpacker.unpack_int()
values['TYPE'] = unpacker.unpack_string()
values['NAME'] = unpacker.unpack_string()
values['VAL'] = unpacker.unpack_string()
values['UNITS'] = unpacker.unpack_string()
values['SLOPE'] = slope_int2str[unpacker.unpack_int()]
values['TMAX'] = unpacker.unpack_uint()
values['DMAX'] = unpacker.unpack_uint()
unpacker.done()
return values
def get_gmetrics(path):
data = open(path).read()
start = 0
out = []
while True:
m = re.search('udp_send_channel +\{([^}]+)\}', data[start:], re.M)
if not m:
break
start += m.end()
tokens = re.split('\s+', m.group(1).strip())
host = tokens[tokens.index('host')+2]
port = int(tokens[tokens.index('port')+2])
out.append(Gmetric(host, port, 'udp'))
return out
if __name__ == '__main__':
import optparse
parser = optparse.OptionParser()
parser.add_option("", "--protocol", dest="protocol", default="udp",
help="The gmetric internet protocol, either udp or multicast, default udp")
parser.add_option("", "--host", dest="host", default="127.0.0.1",
help="GMond aggregator hostname to send data to")
parser.add_option("", "--port", dest="port", default="8649",
help="GMond aggregator port to send data to")
parser.add_option("", "--name", dest="name", default="",
help="The name of the metric")
parser.add_option("", "--value", dest="value", default="",
help="The value of the metric")
parser.add_option("", "--units", dest="units", default="",
help="The units for the value, e.g. 'kb/sec'")
parser.add_option("", "--slope", dest="slope", default="both",
help="The sign of the derivative of the value over time, one of zero, positive, negative, both, default both")
parser.add_option("", "--type", dest="type", default="",
help="The value data type, one of string, int8, uint8, int16, uint16, int32, uint32, float, double")
parser.add_option("", "--tmax", dest="tmax", default="60",
help="The maximum time in seconds between gmetric calls, default 60")
parser.add_option("", "--dmax", dest="dmax", default="0",
help="The lifetime in seconds of this metric, default=0, meaning unlimited")
parser.add_option("", "--group", dest="group", default="",
help="Group metric belongs to. If not specified Ganglia will show it as no_group")
parser.add_option("", "--spoof", dest="spoof", default="",
help="the address to spoof (ip:host). If not specified the metric will not be spoofed")
(options,args) = parser.parse_args()
g = Gmetric(options.host, options.port, options.protocol)
g.send(options.name, options.value, options.type, options.units,
options.slope, options.tmax, options.dmax, options.group, options.spoof)
| vollmerk/sysadm-tools | ganglia/lib/gmetric.py | Python | gpl-2.0 | 7,815 |
<?php
namespace ResponsiveMenu\Repositories;
use ResponsiveMenu\Models\Option;
use ResponsiveMenu\Collections\OptionsCollection;
use ResponsiveMenu\Database\Database;
use ResponsiveMenu\Factories\OptionFactory;
class OptionRepository {
protected static $table = 'responsive_menu';
public function __construct(Database $db, OptionFactory $factory, array $defaults) {
$this->db = $db;
$this->factory = $factory;
$this->defaults = $defaults;
}
public function all() {
$options = $this->db->all(self::$table);
$collection = new OptionsCollection;
foreach($options as $option)
$collection->add($this->factory->build($option->name, $option->value));
return $collection;
}
public function update(Option $option) {
return $this->db->update(self::$table,
['value' => $option->getFiltered()],
['name' => $option->getName()]
);
}
public function create(Option $option) {
$arguments['name'] = $option->getName();
$arguments['value'] = $option->getFiltered();
$arguments['created_at'] = $this->db->mySqlTime();
return $this->db->insert(self::$table, $arguments);
}
public function remove($name) {
return $this->db->delete(self::$table, $name);
}
public function buildFromArray(array $array) {
$collection = new OptionsCollection;
foreach(array_merge($this->defaults, $array) as $name => $value):
$option = $this->factory->build($name, $value);
$option->setValue($option->getFiltered());
$collection->add($option);
endforeach;
return $collection;
}
}
| dans-lweb/immunoconcept | wp-content/plugins/responsive-menu/src/app/Repositories/OptionRepository.php | PHP | gpl-2.0 | 1,582 |
<?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
*
* http://www.lockon.co.jp/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
namespace Eccube\Controller\Admin\Content;
use Eccube\Application;
use Symfony\Component\HttpFoundation\Request;
class LayoutController
{
public function index(Application $app, Request $request, $id = 1)
{
$device_type_id = $app['config']['device_type_pc'];
// 一覧表示用
$PageLayouts = $app['eccube.repository.page_layout']
->findBy(array(
'device_type_id' => $device_type_id,
));
$Targets = $app['eccube.repository.master.target']->getAll();
// 編集対象ページ
/* @var $TargetPageLayout \Eccube\Entity\PageLayout */
$TargetPageLayout = $app['eccube.repository.page_layout']->get($device_type_id, $id);
// 未使用ブロックの取得
$Blocs = $app['orm.em']->getRepository('Eccube\Entity\Bloc')
->findBy(array(
'device_type_id' => $device_type_id,
));
$BlocPositions = $TargetPageLayout->getBlocPositions();
foreach ($Blocs as $Bloc) {
if (!$BlocPositions->containsKey($Bloc->getBlocId())) {
$UnuseBlocPosition = new \Eccube\Entity\BlocPosition();
$UnuseBlocPosition
->setDeviceTypeId($device_type_id)
->setPageId($id)
->setTargetId($app['config']['target_id_unused'])
->setAnywhere(0)
->setBlocRow(0)
->setBlocId($Bloc->getBlocId())
->setBloc($Bloc)
->setPageLayout($TargetPageLayout);
$TargetPageLayout->addBlocPosition($UnuseBlocPosition);
}
}
$form = $app['form.factory']
->createBuilder()
->getForm();
if ('POST' === $request->getMethod()) {
$form->handleRequest($request);
if ($form->isValid()) {
// 消す
$blocCount = count($BlocPositions);
foreach ($BlocPositions as $BlocPosition) {
if ($BlocPosition->getPageId() == $id || $BlocPosition->getAnywhere() == 0) {
$TargetPageLayout->removeBlocPosition($BlocPosition);
$app['orm.em']->remove($BlocPosition);
}
}
$app['orm.em']->flush();
$TargetHash = $this->getTragetHash($Targets);
// TODO: collection を利用
$data = $request->request->all();
for ($i = 1; $i <= $blocCount; $i++) {
// bloc_id が取得できない場合は INSERT しない
if (!isset($data['id_' . $i])) {
continue;
}
// 未使用は INSERT しない
if ($TargetHash[$data['target_id_' . $i]] === $app['config']['target_id_unused']) {
continue;
}
// 他のページに anywhere が存在する場合は INSERT しない
$anywhere = (isset($data['anywhere_' . $i]) && $data['anywhere_' . $i] == 1) ? 1 : 0;
if (isset($data['anywhere_' . $i]) && $data['anywhere_' . $i] == 1) {
$Other = $app['orm.em']->getRepository('Eccube\Entity\BlocPosition')
->findBy(array(
'anywhere' => 1,
'bloc_id' => $data['id_' . $i],
'device_type_id' => $device_type_id,
));
if (count($Other) > 0) {
continue;
}
}
$BlocPosition = new \Eccube\Entity\BlocPosition();
$Bloc = $app['orm.em']->getRepository('Eccube\Entity\Bloc')
->findOneBy(array(
'bloc_id' => $data['id_' . $i],
'device_type_id' => $device_type_id,
));
$BlocPosition
->setDeviceTypeId($device_type_id)
->setPageId($id)
->setBlocId($data['id_' . $i])
->setBlocRow($data['top_' . $i])
->setTargetId($TargetHash[$data['target_id_' . $i]])
->setBloc($Bloc)
->setPageLayout($TargetPageLayout)
->setAnywhere($anywhere);
if ($id == 0) {
$BlocPosition->setAnywhere(0);
}
$TargetPageLayout->addBlocPosition($BlocPosition);
}
$app['orm.em']->persist($TargetPageLayout);
$app['orm.em']->flush();
$app['session']->getFlashBag()->add('admin.success', 'admin.register.complete');
return $app->redirect($app['url_generator']->generate('admin_content_layout_edit', array('id' => $id)));
}
}
return $app['view']->render('Content/layout.twig', array(
'form' => $form->createView(),
'TargetPageLayout' => $TargetPageLayout,
'Targets' => $Targets,
'PageLayouts' => $PageLayouts,
));
}
public function getTragetHash($Targets)
{
$TargetHash = array();
foreach ($Targets as $key => $Target) {
$TargetHash[$Target->getName()] = $key;
}
return $TargetHash;
}
}
| Yammy/ec-cube | src/Eccube/Controller/Admin/Content/LayoutController.php | PHP | gpl-2.0 | 6,478 |
package corgis.energy.domain;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
/**
*
*/
public class Industrial {
// Natural gas price in the industrial sector (including supplemental gaseous fuels) in dollars per million BTU.
private Integer naturalGas;
// Distillate fuel oil price in the industrial sector in dollars per million BTU.
private Integer distillateFuelOil;
// Other petroleum products average price in the industrial sector in dollars per million BTU.
private Integer otherPetroleumProducts;
// Coal price in the industrial sector in dollars per million BTU.
private Integer coal;
// Kerosene price in the industrial sector in dollars per million BTU.
private Integer kerosene;
// LPG price in the industrial sector in dollars per million BTU.
private Integer liquefiedPetroleumGases;
/**
* Natural gas price in the industrial sector (including supplemental gaseous fuels) in dollars per million BTU.
* @return Integer
*/
public Integer getNaturalGas() {
return this.naturalGas;
}
/**
* Distillate fuel oil price in the industrial sector in dollars per million BTU.
* @return Integer
*/
public Integer getDistillateFuelOil() {
return this.distillateFuelOil;
}
/**
* Other petroleum products average price in the industrial sector in dollars per million BTU.
* @return Integer
*/
public Integer getOtherPetroleumProducts() {
return this.otherPetroleumProducts;
}
/**
* Coal price in the industrial sector in dollars per million BTU.
* @return Integer
*/
public Integer getCoal() {
return this.coal;
}
/**
* Kerosene price in the industrial sector in dollars per million BTU.
* @return Integer
*/
public Integer getKerosene() {
return this.kerosene;
}
/**
* LPG price in the industrial sector in dollars per million BTU.
* @return Integer
*/
public Integer getLiquefiedPetroleumGases() {
return this.liquefiedPetroleumGases;
}
/**
* Creates a string based representation of this Industrial.
* @return String
*/
public String toString() {
return "Industrial[" +naturalGas+", "+distillateFuelOil+", "+otherPetroleumProducts+", "+coal+", "+kerosene+", "+liquefiedPetroleumGases+"]";
}
/**
* Internal constructor to create a Industrial from a representation.
* @param json_data The raw json data that will be parsed.
*/
public Industrial(JSONObject json_data) {
//System.out.println(json_data);
try {
// Natural Gas
this.naturalGas = ((Number)json_data.get("Natural Gas")).intValue();
} catch (NullPointerException e) {
System.err.println("Could not convert the response to a Industrial; the field naturalGas was missing.");
e.printStackTrace();
} catch (ClassCastException e) {
System.err.println("Could not convert the response to a Industrial; the field naturalGas had the wrong structure.");
e.printStackTrace();
}
try {
// Distillate Fuel Oil
this.distillateFuelOil = ((Number)json_data.get("Distillate Fuel Oil")).intValue();
} catch (NullPointerException e) {
System.err.println("Could not convert the response to a Industrial; the field distillateFuelOil was missing.");
e.printStackTrace();
} catch (ClassCastException e) {
System.err.println("Could not convert the response to a Industrial; the field distillateFuelOil had the wrong structure.");
e.printStackTrace();
}
try {
// Other Petroleum Products
this.otherPetroleumProducts = ((Number)json_data.get("Other Petroleum Products")).intValue();
} catch (NullPointerException e) {
System.err.println("Could not convert the response to a Industrial; the field otherPetroleumProducts was missing.");
e.printStackTrace();
} catch (ClassCastException e) {
System.err.println("Could not convert the response to a Industrial; the field otherPetroleumProducts had the wrong structure.");
e.printStackTrace();
}
try {
// Coal
this.coal = ((Number)json_data.get("Coal")).intValue();
} catch (NullPointerException e) {
System.err.println("Could not convert the response to a Industrial; the field coal was missing.");
e.printStackTrace();
} catch (ClassCastException e) {
System.err.println("Could not convert the response to a Industrial; the field coal had the wrong structure.");
e.printStackTrace();
}
try {
// Kerosene
this.kerosene = ((Number)json_data.get("Kerosene")).intValue();
} catch (NullPointerException e) {
System.err.println("Could not convert the response to a Industrial; the field kerosene was missing.");
e.printStackTrace();
} catch (ClassCastException e) {
System.err.println("Could not convert the response to a Industrial; the field kerosene had the wrong structure.");
e.printStackTrace();
}
try {
// Liquefied Petroleum Gases
this.liquefiedPetroleumGases = ((Number)json_data.get("Liquefied Petroleum Gases")).intValue();
} catch (NullPointerException e) {
System.err.println("Could not convert the response to a Industrial; the field liquefiedPetroleumGases was missing.");
e.printStackTrace();
} catch (ClassCastException e) {
System.err.println("Could not convert the response to a Industrial; the field liquefiedPetroleumGases had the wrong structure.");
e.printStackTrace();
}
}
} | RealTimeWeb/datasets | datasets/java/energy/src/corgis/energy/domain/Industrial.java | Java | gpl-2.0 | 6,075 |
using System;
using System.Linq;
using System.Collections.Generic;
using Foundation;
using UIKit;
namespace SaveData.UI
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
public override UIWindow Window {
get;
set;
}
// This method is invoked when the application is about to move from active to inactive state.
// OpenGL applications should use this method to pause.
public override void OnResignActivation (UIApplication application)
{
}
// This method should be used to release shared resources and it should store the application state.
// If your application supports background exection this method is called instead of WillTerminate
// when the user quits.
public override void DidEnterBackground (UIApplication application)
{
}
// This method is called as part of the transiton from background to active state.
public override void WillEnterForeground (UIApplication application)
{
}
// This method is called when the application is about to terminate. Save data, if needed.
public override void WillTerminate (UIApplication application)
{
}
}
}
| aragorn55/ClassSampleCode | mobiledev/SaveData/SaveData.UI/AppDelegate.cs | C# | gpl-2.0 | 1,413 |
# -*- coding: utf-8 -*-
import pcapy
import Storage_Classes
from collections import defaultdict
#from scapy.layers.all import *
from scapy.layers.dot11 import Dot11, RadioTap
################################################################
VERBOSE = 1
### auxiliary functions ###
def show_short(p, label):
if ( VERBOSE >= 1 ):
## show
#print p.num, p.timestamp, p.dot11.addr2, \
#label, "[" + str(p.dot11.type) + ", " + str(p.dot11.subtype) + "]", \
#p.get_rssi(), "dBm"
###################################################################################
### modified: # ETH- 'public': 00:0f:61:5d:5c:01 / ETH - 'eth':00:0f:61:5d:5c:00 'eth':00:0f:61:53:1f:00
if (str(p.dot11.addr2) == '00:0b:0e:84:00:46'):
print p.timestamp, p.get_rssi(), "dBm" # das time-format hier sind microseconds als kleinste Einheit. Damit ist die letzte Zahl vor dem Komma die Sekunde.
################################################################
### ANALYZE FUNCTIONS ###
def analyze_beacon(p):
#print p.num, p.timestamp, p.dot11.addr2, "BEACON:", p.get_rssi(), "dBm"
show_short(p, "BEACON")
# ## sanity check ## FIXME won't work!! is this a wrong sanity check..?
# if ( not p.dot11.addr2 == p.dot11.addr3 ):
# print
# print "ERR: BEACON INVALID"
# p.show()
# raise Exception("ERR: BEACON INVALID")
# if ( p.dot11.addr2 == "00:00:00:00:00:00" ):
# print
# print "ERR: BEACON INVALID"
# p.show()
# raise Exception("ERR: BEACON INVALID")
## store
senders[p.dot11.addr2].store(p)
def analyze_regular(p):
## some packet types are not correctly dissected
## ---> e.g. Block ACK Req
## ---> TODO (what shall we do with them?)
if ( not p.dot11.addr2 ):
#####################################
##### THIS IS COMPLETELY UNCOMMENTED TO STOP THIS DISSECTION EXCEPTTION !!! (stephan)
#####################################
#show_short(p, "<<not recognized>>.")
#p.show_stephan()
#show_short(p, "Packet.")
##############################
##was: show(p.dot11) ... just guessing
##############################
#print
# dat = raw_input()
######################raise Exception("uncorrect dissection exception")
return
## BRANCH: "no" sender..
## ---> some packets have no proper sender information
## ---> just ignore them!!
if ( p.dot11.addr2 == "00:00:00:00:00:00" ):
show_short(p, "<<ignored>>")
return
## BRANCH: regular packet
else:
show_short(p, "Packet.")
## store
senders[p.dot11.addr2].store(p)
### general analyze function
### --> hands packets over to specialized ones
def analyze(p):
## Control frames have no useful sender information
## ---> we don't want them. just drop it.
## BRANCH: control frames
try:
if ( p.dot11.type == 1 ):
# BRANCH: ACK (sender unclear...)
if ( p.dot11.subtype == 13 ):
if ( VERBOSE >= 1 ):
macheNix=1
################################################################################################
###modified:
#print p.num, "ignoring ACK (1, 13)", p.get_rssi(), "dBm"
################################################################################################
return
if ( p.dot11.subtype == 12 ):
if ( VERBOSE >= 1 ):
macheNix=1
################################################################################################
###modified:
#print p.num, "ignoring CTS (1, 12)", p.get_rssi(), "dBm"
################################################################################################
return
if ( p.dot11.subtype == 8 ):
if ( VERBOSE >= 1 ):
macheNix=1
################################################################################################
###modified:
#print p.num, "ignoring Block ACK Req (1, 12)", p.get_rssi(), "dBm"
################################################################################################
return
## BRANCH: managemet frames
if ( p.dot11.type == 0 ):
# BRANCH: BEACON
if ( p.dot11.subtype == 8 ):
analyze_beacon(p)
return
# elif ( p.dot11.type == 2 ):
# if ( p.dot11.subtype == 4 ):
# analyze_regular(p)
# dat = raw_input()
# return
except AttributeError:
if ( VERBOSE >= 1 ):
print p.num, "ignoring malformed packet", p.get_rssi(), "dBm"
return
## default
## ---> most packets can just be treated the same..
analyze_regular(p)
# show(p.dot11)
# print
# dat = raw_input()
################################################################
### PCAP READING AND DECODING ###
## TODO do they have to be global?
pcapy_reader = False
packet_num = False
senders = False
def get_next():
global packet_num
pkt = pcapy_reader.next()
if ( type(pkt[0]) == type(None)):
return None
p = Storage_Classes.Packet()
packet_num += 1
p.num = packet_num
p.timestamp = pkt[0].getts()
p.tap = RadioTap()
p.tap.dissect(pkt[1])
p.dot11 = p.tap.payload
#print "----->", ord(pkt[1][14])
p.rssi = ord(pkt[1][14]) - 256
return p
### public ###
def parse(file_name, num=100):
global pcapy_reader
global senders
## init
pcapy_reader = pcapy.open_offline(file_name)
packet_num = 0
senders = defaultdict(Storage_Classes.Sender)
print "Reading", file_name, "..."
i = 0
while ( i != num): ## like a for loop, but e.g. -1 means "to infinity"
if ( i % 20000 == 0 ):
print i
p = get_next()
if ( p == None ):
print "EOF", i
break
analyze(p)
i += 1
# dat = raw_input()
## FIXME how to close this?
#pcapy.close()
### statictics
print
print "----------------------------------------"
print "Senders:", len(senders)
## TODO count total in this module not in the Sender class
print "used packets:", Storage_Classes.Sender.total ## TODO maybe this shuld also be returned from "parse"
return senders
| stephansigg/IPSN_localisation_passive-DF | Data_CaseStudies/CaseStudy_1312_initial/pcap_analyzer/Pcap_Parser.py | Python | gpl-2.0 | 6,609 |
# Rekall Memory Forensics
#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""Plugins to inspect flows."""
import base64
import json
import os
import time
import arrow
from rekall import plugin
from rekall import utils
from rekall_agent import common
from rekall_agent import flow
from rekall_agent import result_collections
from rekall_agent import serializer
from rekall_agent.locations import files
from rekall_agent.ui import renderers
CANNED_CONDITIONS = dict(
OS_WINDOWS="any from agent_info() where key=='system' and value=='Windows'",
OS_LINUX="any from agent_info() where key=='system' and value=='Linux'",
OS_OSX="any from agent_info() where key=='system' and value=='Darwin'",
)
class AgentControllerShowFlows(common.AbstractControllerCommand):
name = "show_flows"
__args = [
dict(name="limit", type="IntParser", default=20,
help="Total results to display"),
]
table_header = [
dict(name="state", width=8),
dict(name="flow_id", width=14),
dict(name="type", width=18),
dict(name="created", width=19),
dict(name="last_active", width=19),
dict(name="collections"),
]
def collect_db(self, collection):
# Now show all the flows.
for i, row in enumerate(collection.query(order_by="created desc")):
if i > self.plugin_args.limit:
break
ticket = flow.FlowStatus.from_json(
row["ticket_data"], session=self.session)
last_active = row["last_active"]
if last_active:
last_active = arrow.Arrow.fromtimestamp(last_active)
collections = [x.location.get_canonical().to_path()
for x in ticket.collections]
yield dict(state=row["status"],
flow_id=row["flow_id"],
type=row["type"],
created=arrow.Arrow.fromtimestamp(row["created"]),
last_active=last_active,
collections=collections)
def _check_pending_flow(self, row):
"""Check for flow tickets.
For pending flows, it is possible that the worker just has not caught
up. We try to show it anyway by checking for the tickets.
"""
if row["state"] == "Pending":
ticket_location = self._config.server.ticket_for_server(
"FlowStatus", row["flow_id"], self.client_id)
# The client will actually add a nonce to this so we need to find
# all subobjects.
for sub_object in ticket_location.list_files():
# The subobject is a canonical path, we need to authorize it.
data = self._config.server.canonical_for_server(
sub_object.location).read_file()
if data:
ticket = flow.FlowStatus.from_json(
data, session=self.session)
row["state"] = "%s(*)" % ticket.status
row["collections"] = [sub_object.location.to_path()]
row["last_active"] = ticket.timestamp
def collect(self):
if not self.client_id:
raise plugin.PluginError("Client ID must be specified.")
with flow.FlowStatsCollection.load_from_location(
self._config.server.flow_db_for_server(self.client_id),
session=self.session) as collection:
rows = list(self.collect_db(collection))
common.THREADPOOL.map(self._check_pending_flow, rows)
for row in rows:
row["collections"] = [
renderers.UILink("gs", x) for x in row["collections"]]
row["flow_id"] = renderers.UILink("f", row["flow_id"])
yield row
class AgentControllerShowHunts(AgentControllerShowFlows):
name = "show_hunts"
__args = [
dict(name="queue", default="All",
help="The hunt queue."),
]
def collect(self):
with flow.FlowStatsCollection.load_from_location(
self._config.server.flow_db_for_server(
queue=self.plugin_args.queue),
session=self.session) as collection:
for row in self.collect_db(collection):
row["flow_id"] = renderers.UILink("h", row["flow_id"])
yield row
class SerializedObjectInspectorMixin(object):
"""A plugin Mixin which inspects a SerializedObject."""
__args = [
dict(name="verbosity", type="IntParser", default=0,
help="If non zero show all fields."),
]
table_header = [
dict(name="Field", type="TreeNode", max_depth=5, width=20),
dict(name="Value", width=60),
dict(name="Description")
]
def _explain(self, obj, depth=0, ignore_fields=None):
if isinstance(obj, serializer.SerializedObject):
for x in self._collect_serialized_object(
obj, depth=depth, ignore_fields=ignore_fields):
yield x
elif isinstance(obj, basestring):
yield dict(Value=obj)
elif isinstance(obj, list):
yield dict(Value=", ".join(obj))
else:
raise RuntimeError("Unable to render object %r" % obj)
def _collect_list(self, list_obj, field, descriptor, depth):
yield dict(
Field=field,
Value="(Array)",
Description=descriptor.get("doc", ""),
highlight="important" if descriptor.get("user") else "",
depth=depth)
for i, value in enumerate(list_obj):
for row in self._explain(value, depth=depth):
row["Field"] = "[%s] %s" % (i, row.get("Field", ""))
if descriptor.get("user"):
row["highlight"] = "important"
yield row
def _collect_dict(self, dict_obj, field, descriptor, depth):
yield dict(
Field=field,
Value="(Dict)",
Description=descriptor.get("doc", ""),
highlight="important" if descriptor.get("user") else "",
depth=depth)
for key, value in sorted(dict_obj.iteritems()):
for row in self._explain(value, depth=depth+1):
row["Field"] = ". " + key
if descriptor.get("user"):
row["highlight"] = "important"
yield row
def _collect_serialized_object(self, flow_obj, depth=0, ignore_fields=None):
for descriptor in flow_obj.get_descriptors():
# Skip hidden fields if verbosity is low.
if self.plugin_args.verbosity < 2 and descriptor.get("hidden"):
continue
field = descriptor["name"]
# Only show requested fields in non-verbose mode.
if (not self.plugin_args.verbosity and
ignore_fields and field in ignore_fields):
continue
if not flow_obj.HasMember(field):
continue
value = flow_obj.GetMember(field)
if isinstance(value, serializer.SerializedObject):
display_value = "(%s)" % value.__class__.__name__
elif isinstance(value, str):
display_value = base64.b64encode(value)
elif isinstance(value, unicode):
display_value = value
elif isinstance(value, list):
for x in self._collect_list(value, field, descriptor, depth):
yield x
continue
elif isinstance(value, dict):
for x in self._collect_dict(value, field, descriptor, depth):
yield x
continue
else:
display_value = utils.SmartUnicode(value)
if (not self.plugin_args.verbosity and len(display_value) > 45):
display_value = display_value[:45] + " ..."
yield dict(
Field=field,
Value=display_value,
Description=descriptor.get("doc", ""),
highlight="important" if descriptor.get("user") else "",
depth=depth)
if (isinstance(value, serializer.SerializedObject)):
for row in self._explain(value, depth=depth+1):
yield row
class InspectFlow(SerializedObjectInspectorMixin,
common.AbstractControllerCommand):
name = "inspect_flow"
__args = [
dict(name="flow_id", required=True, positional=True,
help="The flow to examine"),
]
table_header = [
dict(name="divider", type="Divider")
] + SerializedObjectInspectorMixin.table_header
def _get_collection(self, client_id):
return flow.FlowStatsCollection.load_from_location(
self._config.server.flow_db_for_server(client_id),
session=self.session)
def get_flow_object(self, flow_id=None):
if flow_id is None:
flow_id = self.plugin_args.flow_id
return flow.Flow.from_json(
self._config.server.flows_for_server(flow_id).read_file(),
session=self.session)
def collect(self):
flow_obj = self.get_flow_object(self.plugin_args.flow_id)
with self._get_collection(flow_obj.client_id) as collection:
yield dict(divider="Flow Object (%s)" % flow_obj.__class__.__name__)
for x in self._explain(flow_obj, ignore_fields=set([
"ticket", "actions"
])):
yield x
for row in collection.query(flow_id=self.plugin_args.flow_id):
ticket = flow.FlowStatus.from_json(row["ticket_data"],
session=self.session)
yield dict(divider="Flow Status Ticket")
for x in self._explain(ticket, ignore_fields=set([
"location", "client_id", "flow_id", "collections"
])):
yield x
if ticket.collections:
yield dict(divider="Collections")
for collection in ticket.collections:
link = renderers.UILink(
"gs", collection.location.get_canonical().to_path())
yield dict(
Field=collection.__class__.__name__,
Value=link,
Description="", nowrap=True)
if ticket.files:
yield dict(divider="Uploads")
for upload in ticket.files:
link = renderers.UILink(
"gs", upload.get_canonical().to_path())
yield dict(Value=link, nowrap=True)
if ticket.error:
yield dict(divider="Error")
yield dict(Field="ticket.error", Value=ticket.error)
if ticket.backtrace:
yield dict(divider="Backtrace")
yield dict(Field="ticket.backtrace", Value=ticket.backtrace)
class InspectHunt(InspectFlow):
name = "inspect_hunt"
__args = [
dict(name="limit", type="IntParser", default=20,
help="Limit of rows to display"),
dict(name="graph_clients", type="Bool",
help="Also plot a graph of client participation."),
]
table_header = [
dict(name="divider", type="Divider"),
dict(name="Field", width=20),
dict(name="Time", width=20),
dict(name="Value", width=20),
dict(name="Description")
]
def _get_collection(self):
return flow.HuntStatsCollection.load_from_location(
self._config.server.hunt_db_for_server(self.plugin_args.flow_id),
session=self.session)
def graph_clients(self, collection):
"""Draw a graph of client engagement."""
# This is optionally dependent on presence of matplotlib.
try:
from matplotlib import pyplot
except ImportError:
raise plugin.PluginError(
"You must have matplotlib installed to plot graphs.")
total_clients = 0
base = None
data_x = []
data_y = []
for row in collection.query(order_by="executed"):
total_clients += 1
if base is None:
base = row["executed"]
data_x.append(row["executed"] - base)
data_y.append(total_clients)
fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.plot(data_x, data_y)
start_time = arrow.Arrow.fromtimestamp(base)
ax.set_title("Clients in Hunt %s" % self.plugin_args.flow_id)
ax.set_xlabel("Seconds after %s (%s)" % (
start_time.ctime(), start_time.humanize()))
ax.set_ylabel("Total Client Count")
pyplot.show()
def collect(self):
with self._get_collection() as collection:
flow_obj = self.get_flow_object(self.plugin_args.flow_id)
if self.plugin_args.graph_clients:
self.graph_clients(collection)
yield dict(divider="Flow Object (%s)" % flow_obj.__class__.__name__)
for x in self._explain(flow_obj, ignore_fields=set([
"ticket", "actions"
])):
yield x
yield dict(divider="Summary")
yield dict(Field="Total Clients",
Value=list(collection.query(
"select count(*) as c from tbl_default"
))[0]["c"])
yield dict(Field="Successful Clients",
Value=list(collection.query(
"select count(*) as c from tbl_default "
"where status = 'Done'"))[0]["c"])
yield dict(Field="Errors Clients",
Value=list(collection.query(
"select count(*) as c from tbl_default "
"where status = 'Error'"))[0]["c"])
total = 0
yield dict(divider="Results")
for row in collection.query(
status="Done", limit=self.plugin_args.limit):
ticket = flow.FlowStatus.from_json(row["ticket_data"],
session=self.session)
for result in ticket.collections:
if total > self.plugin_args.limit:
break
yield dict(Field=ticket.client_id,
Time=ticket.timestamp,
Value=renderers.UILink(
"gs", result.location.to_path()),
nowrap=True)
total += 1
yield dict(divider="Uploads")
total = 0
for row in collection.query(
status="Done", limit=self.plugin_args.limit):
ticket = flow.FlowStatus.from_json(row["ticket_data"],
session=self.session)
for result in ticket.files:
if total > self.plugin_args.limit:
break
yield dict(Field=ticket.client_id,
Time=ticket.timestamp,
Value=renderers.UILink(
"gs", result.to_path()),
nowrap=True)
total += 1
for row in collection.query(
status="Error", limit=self.plugin_args.limit):
ticket = flow.FlowStatus.from_json(row["ticket_data"],
session=self.session)
yield dict(Field=ticket.client_id,
Time=ticket.timestamp,
Value=ticket.error, nowrap=True)
class AgentControllerRunFlow(SerializedObjectInspectorMixin,
common.AbstractControllerCommand):
name = "launch_flow"
__args = [
dict(name="flow", type="Choices", positional=True, required=True,
choices=utils.JITIteratorCallable(
utils.get_all_subclasses, flow.Flow),
help="The flow to launch"),
dict(name="args", type="Any", positional=True, default={},
help="Arguments to the flow (use explain_flow to see valid args)."
"This may also be a JSON encoded string"),
dict(name="queue",
help="Which queue to schedule the hunt on."),
dict(name="condition",
help="An EFilter query to evaluate if the flow should be run."),
# This should only be set if no condition is specified.
dict(name="canned_condition", type="Choices", default=None,
choices=CANNED_CONDITIONS,
help="Canned conditions for the hunt."),
dict(name="live", type="Choices", default="API",
choices=["API", "Memory"],
help="Live mode to use"),
dict(name="quota", type="IntParser", default=3600,
help="Total number of CPU seconds allowed for this flow."),
]
def make_flow_object(self):
flow_cls = flow.Flow.ImplementationByClass(self.plugin_args.flow)
if not flow_cls:
raise plugin.PluginError("Unknown flow %s" % self.plugin_args.flow)
args = self.plugin_args.args
if isinstance(args, basestring):
try:
args = json.loads(args)
except Exception as e:
raise plugin.PluginError(
"args should be a JSON string of a dict: %s" % e)
if not isinstance(args, dict):
raise plugin.PluginError("args should be a dict")
flow_obj = flow_cls.from_primitive(args, session=self.session)
flow_obj.client_id = self.client_id
flow_obj.queue = self.plugin_args.queue
flow_obj.session.live = self.plugin_args.live
# If a canned condition was specified automatically add it.
if self.plugin_args.canned_condition:
flow_obj.condition = CANNED_CONDITIONS[
self.plugin_args.canned_condition]
elif self.plugin_args.condition:
flow_obj.condition = self.plugin_args.condition
# Specify flow quota.
flow_obj.quota.user_time = self.plugin_args.quota
return flow_obj
def collect(self):
# Now launch the flow.
flow_obj = self.make_flow_object()
flow_obj.start()
for x in self._explain(flow_obj):
yield x
class AgentControllerRunHunt(AgentControllerRunFlow):
"""Launch a hunt on many clients at once.
Rekall does not treat hunts as different or special entities - a hunt is
just a flow which targets multiple systems. However, for users it is
sometimes helpful to think in terms of a "hunt". This plugin makes it easier
to launch the hunt.
"""
name = "launch_hunt"
__args = [
# Flows are scheduled on the client's flow queue but hunts are generally
# scheduled on a Label Queue (e.g. the All queue schedules to all
# agents).
dict(name="queue", default="All",
help="Which queue to schedule the hunt on."),
]
class AgentControllerExplainFlows(common.AbstractControllerCommand):
"""Explain all the parameters a flow may take."""
name = "explain_flow"
__args = [
dict(name="flow", type="Choices", positional=True, required=True,
choices=utils.JITIteratorCallable(
utils.get_all_subclasses, flow.Flow),
help="The flow to explain"),
dict(name="verbosity", type="IntParser", default=0,
help="If non zero show all fields."),
dict(name="recursive", type="Bool",
help="Show recursively nested fields."),
]
table_header = [
dict(name="Field", type="TreeNode", max_depth=5),
dict(name="Type"),
dict(name="Description")
]
table_options = dict(
auto_widths=True,
)
def _explain(self, flow_cls, depth=0):
for descriptor in flow_cls.get_descriptors():
user_accessible = descriptor.get("user")
if self.plugin_args.verbosity < 1 and not user_accessible:
continue
field = descriptor["name"]
field_type = descriptor.get("type", "string")
field_description = field_type
if isinstance(field_type, type):
field_description = "(%s)" % field_type.__name__
yield dict(Field=field,
Type=field_description,
Description=descriptor.get("doc", ""),
depth=depth)
if (self.plugin_args.recursive and
isinstance(field_type, type) and
issubclass(field_type, serializer.SerializedObject)):
for row in self._explain(field_type, depth=depth+1):
#row["Field"] = "%s.%s" % (field, row["Field"])
yield row
def collect(self):
flow_cls = flow.Flow.ImplementationByClass(self.plugin_args.flow)
for x in self._explain(flow_cls):
yield x
class AgentControllerExportCollections(common.AbstractControllerCommand):
"""Exports all collections from the hunt or flow."""
name = "export"
__args = [
dict(name="flow_id", positional=True, required=True,
help="The flow or hunt ID we should export."),
dict(name="dumpdir", positional=True, required=True,
help="The output directory we use export to.")
]
table_header = [
dict(name="divider", type="Divider"),
dict(name="Message")
]
def _collect_hunts(self, flow_obj):
with flow.HuntStatsCollection.load_from_location(
self._config.server.hunt_db_for_server(flow_obj.flow_id),
session=self.session) as hunt_db:
collections_by_type = {}
uploads = []
for row in hunt_db.query():
status = flow.HuntStatus.from_json(row["ticket_data"],
session=self.session)
for collection in status.collections:
collections_by_type.setdefault(
collection.collection_type, []).append(
(collection, status.client_id))
uploads.extend(status.files)
yield dict(divider="Exporting Collections")
# Now create a new collection by type into the output directory.
for output_location in common.THREADPOOL.imap_unordered(
self._dump_collection,
collections_by_type.iteritems()):
yield dict(Message=output_location.to_path())
yield dict(divider="Exporting files")
for output_location in common.THREADPOOL.imap_unordered(
self._dump_uploads,
uploads):
yield dict(Message=output_location.to_path())
def _collect_flows(self, flow_obj):
with flow.FlowStatsCollection.load_from_location(
self._config.server.flow_db_for_server(flow_obj.client_id),
session=self.session) as flow_db:
collections_by_type = {}
uploads = []
for row in flow_db.query(flow_id=flow_obj.flow_id):
status = flow.FlowStatus.from_json(row["ticket_data"],
session=self.session)
for collection in status.collections:
collections_by_type.setdefault(
collection.collection_type, []).append(
(collection, status.client_id))
uploads.extend(status.files)
yield dict(divider="Exporting Collections")
# Now create a new collection by type into the output directory.
for output_location in common.THREADPOOL.imap_unordered(
self._dump_collection,
collections_by_type.iteritems()):
yield dict(Message=output_location.to_path())
yield dict(divider="Exporting files")
for output_location in common.THREADPOOL.imap_unordered(
self._dump_uploads,
uploads):
yield dict(Message=output_location.to_path())
def _dump_uploads(self, download_location):
output_location = files.FileLocation.from_keywords(
path=os.path.join(self.plugin_args.dumpdir,
self.flow_id, "files",
download_location.to_path()),
session=self.session)
local_filename = self._config.server.canonical_for_server(
download_location).get_local_filename()
output_location.upload_local_file(local_filename)
return output_location
def _dump_collection(self, args):
type, collections = args
output_location = files.FileLocation.from_keywords(
path=os.path.join(self.plugin_args.dumpdir,
self.flow_id, "collections", type),
session=self.session)
# We assume all the collections of the same type are the same so we can
# just take the first one as the template for the output collection.
output_collection = collections[0][0].copy()
# Add another column for client_id.
output_collection.tables[0].columns.append(
result_collections.ColumnSpec.from_keywords(
name="client_id", session=self.session))
output_collection.location = output_location
with output_collection.create_temp_file():
common.THREADPOOL.map(
self._copy_single_location,
((output_collection, x, y) for x, y in collections))
return output_location
def _copy_single_location(self, args):
output_collection, canonical_collection, client_id = args
with canonical_collection.load_from_location(
self._config.server.canonical_for_server(
canonical_collection.location),
session=self.session) as collection:
for row in collection:
output_collection.insert(client_id=client_id, **row)
def collect(self):
self.flow_id = self.plugin_args.flow_id
if self.flow_id.startswith("f:") or self.flow_id.startswith("h:"):
self.flow_id = self.flow_id[2:]
flow_obj = flow.Flow.from_json(
self._config.server.flows_for_server(self.flow_id).read_file(),
session=self.session)
if flow_obj.is_hunt():
return self._collect_hunts(flow_obj)
else:
return self._collect_flows(flow_obj)
return []
class FlowLauncherAndWaiterMixin(object):
"""A mixin to implement launching and waiting for flows to complete."""
def launch_and_wait(self, flow_obj):
"""A Generator of messages."""
flow_db_location = self._config.server.flow_db_for_server(
self.client_id)
flow_db_stat = flow_db_location.stat()
flow_obj.start()
# Wait until the flow arrives.
while 1:
new_stat = flow_db_location.stat()
if flow_db_stat and new_stat.generation > flow_db_stat.generation:
with flow.FlowStatsCollection.load_from_location(
flow_db_location, session=self.session) as flow_db:
tickets = []
for row in flow_db.query(flow_id=flow_obj.flow_id):
if row["status"] in ["Done", "Error"]:
tickets.append(
flow.FlowStatus.from_json(row["ticket_data"],
session=self.session))
if tickets:
return tickets
time.sleep(2)
| rlugojr/rekall | rekall-agent/rekall_agent/ui/flows.py | Python | gpl-2.0 | 29,082 |
<div class="wrap" id="of_container">
<h2 style="display:none"></h2>
<div id="of-popup-save" class="of-save-popup">
<div class="of-save-save">Options Updated</div>
</div>
<div id="of-popup-reset" class="of-save-popup">
<div class="of-save-reset">Options Reset</div>
</div>
<div id="of-popup-fail" class="of-save-popup">
<div class="of-save-fail">Error!</div>
</div>
<span style="display: none;" id="hooks"><?php echo json_encode(of_get_header_classes_array()); ?></span>
<input type="hidden" id="reset" value="<?php if(isset($_REQUEST['reset'])) echo $_REQUEST['reset']; ?>" />
<input type="hidden" id="security" name="security" value="<?php echo wp_create_nonce('of_ajax_nonce'); ?>" />
<form id="of_form" method="post" action="<?php echo esc_attr( $_SERVER['REQUEST_URI'] ) ?>" enctype="multipart/form-data" >
<div id="header">
<div class="logo">
<h2><?php echo THEMENAME; ?></h2>
</div>
<div id="js-warning">Warning- This options panel will not work properly without javascript!</div>
<div class="icon-option"></div>
<div class="clear"></div>
</div>
<div id="info_bar">
<a>
<div id="expand_options" class="expand">Expand</div>
</a>
<img style="display:none" src="<?php echo ADMIN_DIR; ?>assets/images/loading-bottom.gif" class="ajax-loading-img ajax-loading-img-bottom" alt="Working..." />
<!-- Start of Support Button -->
<a href="http://bit.ly/1e0FkzU" target="blank"><button id="of_docs" type="button" class="button-primary" style="text-decoration: none;">
Buyer Support Forums
</button></a>
<!-- End of Support Button -->
<!-- Start of Support Button -->
<a href="http://bit.ly/1hjPhXZ" target="blank"><button id="of_docs" type="button" class="button-primary" style="text-decoration: none;">
Video Tutorials
</button></a>
<!-- End of Support Button -->
<!-- Start of Support Button -->
<a href="<?php echo get_template_directory_uri(); ?>/documentation/help.html" target="blank"><button id="of_docs" type="button" class="button-primary" style="text-decoration: none;">
Documentation
</button></a>
<!-- End of Support Button -->
<button id="of_save" type="button" class="button-primary">
<?php _e('Save All Changes');?>
</button>
</div><!--.info_bar-->
<div id="main">
<div id="of-nav">
<ul>
<?php echo $options_machine->Menu ?>
</ul>
</div>
<div id="content">
<?php echo $options_machine->Inputs /* Settings */ ?>
</div>
<div class="clear"></div>
</div>
<div class="save_bar">
<img style="display:none" src="<?php echo ADMIN_DIR; ?>assets/images/loading-bottom.gif" class="ajax-loading-img ajax-loading-img-bottom" alt="Working..." />
<button id ="of_save" type="button" class="button-primary"><?php _e('Save All Changes');?></button>
<button id ="of_reset" type="button" class="button submit-button reset-button" ><?php _e('Options Reset');?></button>
<img style="display:none" src="<?php echo ADMIN_DIR; ?>assets/images/loading-bottom.gif" class="ajax-reset-loading-img ajax-loading-img-bottom" alt="Working..." />
</div><!--.save_bar-->
</form>
<div style="clear:both;"></div>
</div><!--wrap--> | m-godefroid76/devrestofactory | wp-content/themes/kingsize/admin/front-end/options.php | PHP | gpl-2.0 | 3,266 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Wikibase.DataModel
{
public class IndexedList<K, V> : IEnumerable
{
private Dictionary<K, V> dictionary;
private Func<V, K> indexProvider;
public int Count { get { return dictionary.Count; } }
public V this[K key]
{
get
{
return dictionary[key];
}
}
public IndexedList(Func<V, K> indexProvider, List<V> values = null)
{
if (indexProvider == null)
{
throw new ArgumentNullException("The index provider must not be null");
}
this.dictionary = values == null ? new Dictionary<K, V>() : values.ToDictionary<V, K>(indexProvider);
this.indexProvider = indexProvider;
}
public void Add(V value)
{
dictionary.Add(indexProvider(value), value);
}
public void Set(V value)
{
dictionary[indexProvider(value)] = value;
}
public bool ContainsKey(K key)
{
return dictionary.ContainsKey(key);
}
public bool Remove(K key)
{
return dictionary.Remove(key);
}
public IEnumerator GetEnumerator()
{
return dictionary.Values.GetEnumerator();
}
}
}
| Benestar/wikibase.net | Wikibase.Net/DataModel/IndexedList.cs | C# | gpl-2.0 | 1,483 |
<?php
/**
* JBZoo App is universal Joomla CCK, application for YooTheme Zoo component
* @package jbzoo
* @version 2.x Pro
* @author JBZoo App http://jbzoo.com
* @copyright Copyright (C) JBZoo.com, All rights reserved.
* @license http://jbzoo.com/license-pro.php JBZoo Licence
* @coder Denis Smetannikov <denis@jbzoo.com>
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
/**
* Class Element
*/
abstract class JBCartElement
{
const DEFAULT_GROUP = '_default';
/**
* @var String
*/
public $identifier;
/**
* @var App
*/
public $app;
/**
* @var AppData
*/
public $config;
/**
* @var String
*/
protected $_group;
/**
* @var JBCartOrder
*/
protected $_order;
/**
* @var String
*/
protected $_type;
/**
* @var Element callbacks
*/
protected $_callbacks = array();
/**
* @var JBCartElementHelper
*/
protected $_jbcartelement = null;
/**
* @var SimpleXMLElement
*/
protected $_xmlData = null;
/**
* @var JSONData
*/
protected $_metaData = null;
/**
* @var string
*/
protected $_namespace = JBCart::ELEMENT_TYPE_DEFAULT;
/**
* @var JSONData
*/
protected $_data = array();
/**
* @var JBMoneyHelper
*/
protected $_jbmoney = array();
/**
* Constructor
* @param App $app
* @param string $type
* @param string $group
*/
public function __construct($app, $type, $group)
{
// set app
$this->app = $app;
$this->config = $this->app->data->create();
$this->_group = strtolower(trim($group));
$this->_type = strtolower(trim($type));
$this->_jbcartelement = $this->app->jbcartelement;
$this->_data = $this->app->data->create($this->_data);
}
/**
* Load custom languages
*/
protected function _loadLangs()
{
JFactory::getLanguage()->load('elem_' . $this->getElementType(), $this->getPath(), null, true);
}
/**
* Set new config data
* @param $config
*/
public function setConfig($config)
{
if (is_array($config)) {
$config = $this->app->data->create($config);
}
$this->config = $config;
}
/**
* Gets the elements type
* @return string
*/
public function getElementType()
{
return strtolower($this->_type);
}
/**
* Gets the elements type
* @return string
*/
public function getElementGroup()
{
return strtolower($this->_group);
}
/**
* Set data through data array.
* @param array $data
* @return $this
*/
public function bindData($data = array())
{
if (!empty($data)) {
foreach ($data as $key => $value) {
$this->set($key, $value);
}
}
return $this;
}
/**
* Gets the elements data
* @param $key
* @param null $default
* @return mixed
*/
public function get($key, $default = null)
{
$result = $this->_data->get($key, $default);
if ($result === null) {
$result = $default;
}
return $result;
}
/**
* Sets the elements data.
* @param $key
* @param $value
* @return $this
*/
public function set($key, $value)
{
$this->_data->set($key, $value);
return $this;
}
/**
* Gets data array
* @return array
*/
public function data()
{
return $this->_data;
}
/**
* Get element layout path and use override if exists
* @param null|string $layout
* @return string
*/
public function getLayout($layout = null)
{
// init vars
$type = $this->getElementType();
$group = $this->getElementGroup();
// set default
if (empty($layout)) {
$layout = $type . '.php';
} else if (strpos($layout, '.php') === false) {
$layout .= '.php';
}
// own layout
$layoutPath = $this->app->path->path("cart-elements:{$group}/{$type}/tmpl/{$layout}");
// parent option
if (empty($layoutPath)) {
$layoutPath = $this->app->path->path("cart-elements:{$group}/option/tmpl/{$layout}");
}
// parent group
if (empty($layoutPath)) {
$layoutPath = $this->app->path->path("cart-elements:core/{$group}/tmpl/{$layout}");
}
// global
if (empty($layoutPath)) {
$layoutPath = $this->app->path->path("cart-elements:core/element/tmpl/{$layout}");
}
return $layoutPath;
}
/**
* Get related order object
* @return JBCartOrder
*/
public function getOrder()
{
return $this->_order;
}
/**
* Get related type object
* @return String
*/
public function getType()
{
return $this->_type;
}
/**
* Get element group
* @return bool
*/
public function getGroup()
{
return $this->getMetadata('group');
}
/**
* Set related item object
* @param JBCartOrder $order
*/
public function setOrder(JBCartOrder $order)
{
$this->_order = $order;
}
/**
* Set related type object
* @param array $params
* @return bool
*/
public function hasValue($params = array())
{
$value = $this->get('value', $this->config->get('default'));
return !empty($value);
}
/**
* Renders the element
* @param array $params
* @return mixed|string
*/
public function render($params = array())
{
$paramLayout = $params->get('layout') ? $params->get('layout') . '.php' : null;
if ($layout = $this->getLayout($paramLayout)) {
return $this->renderLayout($layout, array(
'params' => $params,
'value' => $this->get('value'),
'order' => $this->getOrder(),
));
}
return null;
}
/**
* @param string $layout
* @param array $vars
* @return null|string
*/
protected function _partial($layout, $vars = array())
{
$vars['order'] = $this->getOrder();
if ($layout = $this->getLayout($layout . '.php')) {
return self::renderLayout($layout, $vars);
}
return null;
}
/**
* Renders the element using template layout file
* @param string $__layout layouts template file
* @param array $__args layouts template file args
* @return string
*/
protected function renderLayout($__layout, $__args = array())
{
// init vars
if (is_array($__args)) {
foreach ($__args as $__var => $__value) {
$$__var = $__value;
}
}
// render layout
$__html = '';
ob_start();
include($__layout);
$__html = ob_get_contents();
ob_end_clean();
return $__html;
}
/**
* Load elements css/js assets
* @return $this
*/
public function loadAssets()
{
$group = $this->getElementGroup();
$type = $this->getElementType();
$jbassets = $this->app->jbassets;
$jbassets->js('cart-elements:' . $group . '/' . $type . '/assets/js/' . $type . '.js');
$jbassets->css('cart-elements:' . $group . '/' . $type . '/assets/css/' . $type . '.css');
$jbassets->less('cart-elements:' . $group . '/' . $type . '/assets/less/' . $type . '.less');
return $this;
}
/**
* Load elements css/js config assets
* @return $this
*/
public function loadConfigAssets()
{
$this->app->path->register($this->app->path->path('helpers:fields'), 'fields');
return $this;
}
/**
* Register a callback function
* @param $method
*/
public function registerCallback($method)
{
if (!in_array(strtolower($method), $this->_callbacks)) {
$this->_callbacks[] = strtolower($method);
}
}
/**
* Execute elements callback function
* @param $method
* @param array $args
*/
public function callback($method, $args = array())
{
// try to call a elements class method
if (in_array(strtolower($method), $this->_callbacks) && method_exists($this, $method)) {
// call method
$res = call_user_func_array(array($this, $method), $args);
// output if method returns a string
if (is_string($res)) {
echo $res;
}
}
}
/**
* Get parameter form object to render input form
* @return AppParameterForm
*/
public function getConfigForm()
{
// get form
/** @var AppParameterForm $form */
$form = $this->app->parameterform->create();
$params = array();
$class = new ReflectionClass($this);
while ($class !== false) {
$xmlPath = preg_replace('#\.php$#i', '.xml', $class->getFileName());
if (file_exists($xmlPath)) {
$params[] = $xmlPath;
}
$class = $class->getParentClass();
}
$params = array_reverse($params);
// trigger configparams event
$event = $this->app->event->create($this, 'cart-element:configparams')->setReturnValue($params);
$params = $this->app->event->dispatcher->notify($event)->getReturnValue();
// skip if there are no config files
$params = array_filter($params);
if (empty($params)) {
return null;
}
// add config xml files
foreach ($params as $xml) {
$form->addXML($xml);
}
// set values
$form->setValues($this->config);
// add reference to element
$form->element = $this;
// trigger configform event
$this->app->jbevent->fire($this, 'cart-element:configform', compact('form'));
$fieldsPath = JPath::clean($this->getPath() . '/fields');
if (is_dir($fieldsPath)) {
$form->addElementPath($fieldsPath);
}
return $form;
}
/**
* Get elements xml meta data
* @param null $key
* @return bool
*/
public function getMetaData($key = null)
{
if (!isset($this->_metaData)) {
$data = array();
$xml = $this->loadXML();
if (!$xml) {
return false;
}
$data['type'] = $xml->attributes()->type ? (string)$xml->attributes()->type : 'Unknown';
$data['group'] = $xml->attributes()->group ? (string)$xml->attributes()->group : 'Unknown';
$data['hidden'] = $xml->attributes()->hidden ? (string)$xml->attributes()->hidden : 'false';
$data['core'] = $xml->attributes()->core ? (string)$xml->attributes()->core : 'false';
$data['system-tmpl'] = $xml->attributes()->{'system-tmpl'} ? (string)$xml->attributes()->{'system-tmpl'} : 'false';
$data['trusted'] = $xml->attributes()->trusted ? (string)$xml->attributes()->trusted : 'false';
$data['orderable'] = $xml->attributes()->orderable ? (string)$xml->attributes()->orderable : 'false';
$data['name'] = JText::_((string)$xml->name);
$data['creationdate'] = $xml->creationDate ? (string)$xml->creationDate : 'Unknown';
$data['author'] = $xml->author ? (string)$xml->author : 'Unknown';
$data['copyright'] = (string)$xml->copyright;
$data['authorEmail'] = (string)$xml->authorEmail;
$data['authorUrl'] = (string)$xml->authorUrl;
$data['version'] = (string)$xml->version;
$data['description'] = JText::_((string)$xml->description);
$this->_metaData = $this->app->data->create($data);
}
return $key == null ? $this->_metaData : $this->_metaData->get($key);
}
/**
* Retrieve Element XML file info
* @return SimpleXMLElement
*/
public function loadXML()
{
if (!isset($this->_xmlData)) {
$type = $this->getElementType();
$group = $this->getElementGroup();
$this->_xmlData = simplexml_load_file($this->app->path->path("cart-elements:$group/$type/$type.xml"));
}
return $this->_xmlData;
}
/**
* Gets the controle name for given name
* @param $name
* @param bool $array
* @return string
*/
public function getControlName($name, $array = false)
{
return $this->_namespace . '[' . $this->identifier . '][' . $name . ']' . ($array ? '[]' : '');
}
/**
* Check if element is accessible with users access rights
* @param null $user
* @return mixed
*/
public function canAccess($user = null)
{
return $this->app->user->canAccess($user, $this->config->get('access', $this->app->joomla->getDefaultAccess()));
}
/**
* Get path to element's base directory
* @return mixed
*/
public function getPath()
{
return $this->app->path->path("cart-elements:" . $this->getElementGroup() . '/' . $this->getElementType());
}
/**
* Check if element is system
* @return bool
*/
public function isSystemTmpl()
{
$systemTmpl = strtolower($this->getMetaData('system-tmpl'));
if ($systemTmpl == 'true') {
return true;
}
return false;
}
/**
* Check if element is core
* @return bool
*/
public function isCore()
{
$core = strtolower($this->getMetaData('core'));
if ($core == 'true') {
return true;
}
return false;
}
/**
* Check if element is core
* @return bool
*/
public function isHidden()
{
$hidden = strtolower($this->getMetaData('hidden'));
if ($hidden == 'true' || $hidden == '1') {
return true;
}
return false;
}
/**
* Renders the element in submission
* @param array $params
* @return string|void
*/
public function renderSubmission($params = array())
{
if ($layout = $this->getLayout('submission.php')) {
return self::renderLayout($layout, array(
'params' => $params,
'value' => $this->get('value'),
'order' => $this->getOrder(),
));
}
return null;
}
/**
* Validates the submitted element
* @param $value
* @param $params
* @return array
*/
public function validateSubmission($value, $params)
{
$params = $this->app->data->create($params);
$value = $this->app->data->create($value);
return array(
'value' => $this->app->validator
->create('textfilter', array(
'required' => (int)$params->get('required'),
'trim' => true,
))
->clean($value->get('value')),
);
}
/**
* @return string
*/
public function getName()
{
$name = $this->config->get('name');
if (empty($name)) {
$retult = $this->getMetaData('name');
} else {
$retult = JText::_($name);
}
$retult = JString::trim($retult);
return $retult;
}
/**
* @return JSONData
*/
public function getOrderData()
{
return $this->app->data->create(array(
'data' => $this->data(),
'config' => (array)$this->config,
));
}
/**
* @param null $default
* @return mixed
*/
public function getDescription($default = null)
{
return JText::_($this->config->get('description', $default));
}
/**
* @param bool $uniq
* @return string
*/
public function htmlId($uniq = false)
{
$id = 'jbcart-' . $this->identifier;
if ($uniq) {
return $this->app->jbstring->getId($id);
}
return $id;
}
/**
* @param string $methodName
* @param array $params
* @return mixed
*/
public function getAjaxUrl($methodName = 'ajax', array $params = array())
{
$urlParams = array(
'order_id' => $this->getOrder()->id,
'group' => $this->getElementGroup(),
'element' => $this->identifier,
);
return $this->app->jbrouter->elementOrder($methodName, $urlParams, $params);
}
/**
* @param $attrs
* @return mixed
*/
protected function _attrs($attrs)
{
return $this->app->jbhtml->buildAttrs($attrs);
}
/**
* @param string $positon
*/
public function saveConfig($positon = JBCart::DEFAULT_POSITION)
{
$config = JBModelConfig::model();
$list = $config->getGroup('cart.' . $this->getElementGroup());
$list[$positon][$this->identifier] = (array)$this->config;
$config->setGroup('cart.' . $this->getElementGroup(), $list);
}
}
/**
* Class JBCartElementException
*/
class JBCartElementException extends AppException
{
} | alexmixaylov/real | media/zoo/applications/jbuniversal/cart-elements/core/element/element.php | PHP | gpl-2.0 | 18,323 |
#include "hge-object-page.hpp"
hge::ui::ObjectPage::ObjectPage(QWidget *parent) :
QWidget(parent)
{
}
| Hossein-Noroozpour/HGE-Builder | hge-object-page.cpp | C++ | gpl-2.0 | 103 |
<?php
use mvc\interfaces\controllerActionInterface;
use mvc\controller\controllerClass;
use mvc\config\configClass as config;
use mvc\request\requestClass as request;
use mvc\routing\routingClass as routing;
use mvc\session\sessionClass as session;
use mvc\i18n\i18nClass as i18n;
use hook\log\logHookClass as log;
/**
* Description of ejemploClass
*
* @author Mariana Lopez, Andres Felipe Alvarez
*/
class deleteSelectActionClass extends controllerClass implements controllerActionInterface {
public function execute() {
try {
if (request::getInstance()->isMethod('POST')) {
$idsToDelete = request::getInstance()->getPost('chk');
foreach ($idsToDelete as $id) {
$ids = array(
usuarioTableClass::ID => $id
);
usuarioTableClass::delete($ids, true);
}
session::getInstance()->setSuccess(i18n::__(20003, null, 'default'));
log::register('EliminacionSeleccionado', usuarioTableClass::getNameTable(), null, session::getInstance()->getUserId());
routing::getInstance()->redirect('usuario', 'index');
} else {
routing::getInstance()->redirect('usuario', 'index');
}
} catch (PDOException $exc) {
session::getInstance()->setFlash('exc', $exc);
routing::getInstance()->forward('shfSecurity', 'exception');
}
}
}
| marianandres/CultExcelEnterprise1 | controller/usuario/deleteSelectActionClass.php | PHP | gpl-2.0 | 1,500 |
<?php $section = get_heckscher_section(); ?>
<div class="heckscherdropdown dropdown-<?php echo $section; ?>">
<?php if ( $section == 'guidelines') : ?>
<span class="more">More Guidelines</span>
<?php elseif ( $section == 'projects') : ?>
<span class="more">More Projects</span>
<?php else : ?>
<span class="more">More</span>
<?php endif; ?>
<div class="ddwrapper">
<ul><?php echo wp_list_pages(array(
'echo' => 0,
'title_li' => __(''),
'depth' => '1',
'link_before' => '<span>',
'link_after' => '</span>',
'child_of' => $post->post_parent,
'exclude' => $post->ID
)); ?></ul>
</div>
</div> | everythingtype/heckscher | parts/sibling-dropdown.php | PHP | gpl-2.0 | 627 |
import re
from geopy import exc
from geopy.compat import urlencode
from geopy.geocoders.base import DEFAULT_SENTINEL, Geocoder
from geopy.location import Location
from geopy.util import logger
__all__ = ("What3Words", )
class What3Words(Geocoder):
"""What3Words geocoder.
Documentation at:
https://docs.what3words.com/api/v2/
.. versionadded:: 1.5.0
.. versionchanged:: 1.15.0
API has been updated to v2.
"""
multiple_word_re = re.compile(
r"[^\W\d\_]+\.{1,1}[^\W\d\_]+\.{1,1}[^\W\d\_]+$", re.U
)
geocode_path = '/v2/forward'
reverse_path = '/v2/reverse'
def __init__(
self,
api_key,
format_string=None,
scheme='https',
timeout=DEFAULT_SENTINEL,
proxies=DEFAULT_SENTINEL,
user_agent=None,
ssl_context=DEFAULT_SENTINEL,
):
"""
:param str api_key: Key provided by What3Words
(https://accounts.what3words.com/register).
:param str format_string:
See :attr:`geopy.geocoders.options.default_format_string`.
:param str scheme: Must be ``https``.
.. deprecated:: 1.15.0
API v2 requires https. Don't use this parameter,
it's going to be removed in geopy 2.0.
Scheme other than ``https`` would result in a
:class:`geopy.exc.ConfigurationError` being thrown.
:param int timeout:
See :attr:`geopy.geocoders.options.default_timeout`.
:param dict proxies:
See :attr:`geopy.geocoders.options.default_proxies`.
:param str user_agent:
See :attr:`geopy.geocoders.options.default_user_agent`.
.. versionadded:: 1.12.0
:type ssl_context: :class:`ssl.SSLContext`
:param ssl_context:
See :attr:`geopy.geocoders.options.default_ssl_context`.
.. versionadded:: 1.14.0
"""
super(What3Words, self).__init__(
format_string=format_string,
# The `scheme` argument is present for the legacy reasons only.
# If a custom value has been passed, it should be validated.
# Otherwise use `https` instead of the `options.default_scheme`.
scheme=(scheme or 'https'),
timeout=timeout,
proxies=proxies,
user_agent=user_agent,
ssl_context=ssl_context,
)
if self.scheme != "https":
raise exc.ConfigurationError("What3Words now requires `https`.")
self.api_key = api_key
domain = 'api.what3words.com'
self.geocode_api = '%s://%s%s' % (self.scheme, domain, self.geocode_path)
self.reverse_api = '%s://%s%s' % (self.scheme, domain, self.reverse_path)
def _check_query(self, query):
"""
Check query validity with regex
"""
if not self.multiple_word_re.match(query):
return False
else:
return True
def geocode(self,
query,
lang='en',
exactly_one=True,
timeout=DEFAULT_SENTINEL):
"""
Return a location point for a `3 words` query. If the `3 words` address
doesn't exist, a :class:`geopy.exc.GeocoderQueryError` exception will be
thrown.
:param str query: The 3-word address you wish to geocode.
:param str lang: two character language codes as supported by
the API (https://docs.what3words.com/api/v2/#lang).
:param bool exactly_one: Return one result or a list of results, if
available. Due to the address scheme there is always exactly one
result for each `3 words` address, so this parameter is rather
useless for this geocoder.
.. versionchanged:: 1.14.0
``exactly_one=False`` now returns a list of a single location.
This option wasn't respected before.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder's initialization.
:rtype: :class:`geopy.location.Location` or a list of them, if
``exactly_one=False``.
"""
if not self._check_query(query):
raise exc.GeocoderQueryError(
"Search string must be 'word.word.word'"
)
params = {
'addr': self.format_string % query,
'lang': lang.lower(),
'key': self.api_key,
}
url = "?".join((self.geocode_api, urlencode(params)))
logger.debug("%s.geocode: %s", self.__class__.__name__, url)
return self._parse_json(
self._call_geocoder(url, timeout=timeout),
exactly_one=exactly_one
)
def _parse_json(self, resources, exactly_one=True):
"""
Parse type, words, latitude, and longitude and language from a
JSON response.
"""
code = resources['status'].get('code')
if code:
# https://docs.what3words.com/api/v2/#errors
exc_msg = "Error returned by What3Words: %s" % resources['status']['message']
if code == 401:
raise exc.GeocoderAuthenticationFailure(exc_msg)
raise exc.GeocoderQueryError(exc_msg)
def parse_resource(resource):
"""
Parse record.
"""
if 'geometry' in resource:
words = resource['words']
position = resource['geometry']
latitude, longitude = position['lat'], position['lng']
if latitude and longitude:
latitude = float(latitude)
longitude = float(longitude)
return Location(words, (latitude, longitude), resource)
else:
raise exc.GeocoderParseError('Error parsing result.')
location = parse_resource(resources)
if exactly_one:
return location
else:
return [location]
def reverse(self, query, lang='en', exactly_one=True,
timeout=DEFAULT_SENTINEL):
"""
Return a `3 words` address by location point. Each point on surface has
a `3 words` address, so there's always a non-empty response.
:param query: The coordinates for which you wish to obtain the 3 word
address.
:type query: :class:`geopy.point.Point`, list or tuple of ``(latitude,
longitude)``, or string as ``"%(latitude)s, %(longitude)s"``.
:param str lang: two character language codes as supported by the
API (https://docs.what3words.com/api/v2/#lang).
:param bool exactly_one: Return one result or a list of results, if
available. Due to the address scheme there is always exactly one
result for each `3 words` address, so this parameter is rather
useless for this geocoder.
.. versionchanged:: 1.14.0
``exactly_one=False`` now returns a list of a single location.
This option wasn't respected before.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder's initialization.
:rtype: :class:`geopy.location.Location` or a list of them, if
``exactly_one=False``.
"""
lang = lang.lower()
params = {
'coords': self._coerce_point_to_string(query),
'lang': lang.lower(),
'key': self.api_key,
}
url = "?".join((self.reverse_api, urlencode(params)))
logger.debug("%s.reverse: %s", self.__class__.__name__, url)
return self._parse_reverse_json(
self._call_geocoder(url, timeout=timeout),
exactly_one=exactly_one
)
def _parse_reverse_json(self, resources, exactly_one=True):
"""
Parses a location from a single-result reverse API call.
"""
return self._parse_json(resources, exactly_one)
| phborba/dsgtoolsop | auxiliar/geopy/geocoders/what3words.py | Python | gpl-2.0 | 8,452 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.autoplot.pngwalk;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.das2.util.LoggerManager;
/**
* first from http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html
* resize taken from http://www.componenthouse.com/article-20
* @author jbf
*/
public class ImageResize {
public static final Logger logger= LoggerManager.getLogger("autoplot.pngwalk");
/**
* convenient typical use.
* @param img image to resize.
* @param thumbSize corner-to-corner size, preserving aspect ratio.
* @return buffered image that is thumbSize across.
*/
public static BufferedImage getScaledInstance( BufferedImage img, int thumbSize ) {
int w0= img.getWidth();
int h0= img.getHeight();
int thumbH, thumbW;
double aspect = 1. * w0 / h0;
thumbH = (int) (Math.sqrt(Math.pow(thumbSize, 2) / (aspect * aspect + 1.)));
thumbW = (int) (thumbH * aspect);
return getScaledInstance( img, thumbW, thumbH, RenderingHints.VALUE_INTERPOLATION_BILINEAR, true );
}
/**
* Convenience method that returns a scaled instance of the
* provided {@code BufferedImage}.
*
* @param img the original image to be scaled
* @param targetWidth the desired width of the scaled instance,
* in pixels
* @param targetHeight the desired height of the scaled instance,
* in pixels
* @param hint one of the rendering hints that corresponds to
* {@code RenderingHints.KEY_INTERPOLATION} (e.g.
* {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
* {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
* {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
* @param higherQuality if true, this method will use a multi-step
* scaling technique that provides higher quality than the usual
* one-step technique (only useful in downscaling cases, where
* {@code targetWidth} or {@code targetHeight} is
* smaller than the original dimensions, and generally only when
* the {@code BILINEAR} hint is specified)
* @return a scaled version of the original {@code BufferedImage}
*/
public static BufferedImage getScaledInstance(BufferedImage img,
int targetWidth,
int targetHeight,
Object hint,
boolean higherQuality)
{
int type = (img.getTransparency() == Transparency.OPAQUE) ?
BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage ret = (BufferedImage)img;
int w, h;
if (higherQuality) {
// Use multi-step technique: start with original size, then
// scale down in multiple passes with drawImage()
// until the target size is reached
w = img.getWidth();
h = img.getHeight();
} else {
// Use one-step technique: scale directly from original
// size to target size with a single drawImage() call
w = targetWidth;
h = targetHeight;
}
int count= 0;
do {
if (higherQuality && w > targetWidth) {
w /= 2;
if (w < targetWidth) {
w = targetWidth;
}
}
if (higherQuality && h > targetHeight) {
h /= 2;
if (h < targetHeight) {
h = targetHeight;
}
}
BufferedImage tmp = new BufferedImage(w, h, type);
Graphics2D g2 = tmp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint );
g2.drawImage(ret, 0, 0, w, h, null);
g2.dispose();
ret = tmp;
count++; // I noticed a case where it hung in this loop.
} while ( count<50 && ( w != targetWidth || h != targetHeight) );
if ( count==50 ) {
logger.log( Level.WARNING, "ran out of iterations in imageResize" );
}
return ret;
}
}
| autoplot/app | Autoplot/src/org/autoplot/pngwalk/ImageResize.java | Java | gpl-2.0 | 4,487 |
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 5 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2004 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 3.0 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at the following url: |
// | http://www.php.net/license/3_0.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Stig Bakken <ssb@php.net> |
// | Tomas V.V.Cox <cox@idecnet.com> |
// | |
// +----------------------------------------------------------------------+
//
// $Id: peclcmd.php,v 1.1 2005/02/21 05:30:56 cellog Exp $
/**
* @nodep Gtk
*/
if ('/home/renato/tmp/usr/share/php' != '@'.'include_path'.'@') {
ini_set('include_path', '/home/renato/tmp/usr/share/php');
$raw = false;
} else {
// this is a raw, uninstalled pear, either a cvs checkout, or php distro
$raw = true;
}
define('PEAR_RUNTYPE', 'pecl');
require_once 'pearcmd.php';
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* indent-tabs-mode: nil
* mode: php
* End:
*/
// vim600:syn=php
?>
| telabotanica/tapirlink | lib/pear/peclcmd.php | PHP | gpl-2.0 | 1,830 |
using Server.Items;
namespace Server.Mobiles
{
[CorpseName( "a lava serpent corpse" )]
[TypeAlias( "Server.Mobiles.Lavaserpant" )]
public class LavaSerpent : BaseCreature
{
[Constructable]
public LavaSerpent() : base( AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4 )
{
Name = "a lava serpent";
Body = 90;
BaseSoundID = 219;
SetStr( 386, 415 );
SetDex( 56, 80 );
SetInt( 66, 85 );
SetHits( 232, 249 );
SetMana( 0 );
SetDamage( 10, 22 );
SetDamageType( ResistanceType.Physical, 20 );
SetDamageType( ResistanceType.Fire, 80 );
SetResistance( ResistanceType.Physical, 35, 45 );
SetResistance( ResistanceType.Fire, 70, 80 );
SetResistance( ResistanceType.Poison, 30, 40 );
SetResistance( ResistanceType.Energy, 10, 20 );
SetSkill( SkillName.MagicResist, 25.3, 70.0 );
SetSkill( SkillName.Tactics, 65.1, 70.0 );
SetSkill( SkillName.Wrestling, 60.1, 80.0 );
Fame = 4500;
Karma = -4500;
VirtualArmor = 40;
PackItem( new SulfurousAsh( 3 ) );
PackItem( new Bone() );
// TODO: body parts, armour
}
public override void GenerateLoot()
{
AddLoot( LootPack.Average );
}
public override bool DeathAdderCharmable{ get{ return true; } }
public override bool HasBreath{ get{ return true; } } // fire breath enabled
public override int Meat{ get{ return 4; } }
public override int Hides{ get{ return 15; } }
public override HideType HideType{ get{ return HideType.Spined; } }
public LavaSerpent(Serial serial) : base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int) 0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
if ( BaseSoundID == -1 )
BaseSoundID = 219;
}
}
} | felladrin/last-wish | Scripts/Mobiles/Animals/Reptiles/LavaSerpent.cs | C# | gpl-2.0 | 1,925 |
package gov.noaa.pmel.eps2;
import java.awt.*;
/**
* <code>EPSConstants</code>
* Various symbolic constants used by EPS
*
* @author oz
* @version 1.0
*/
public interface EPSConstants {
public static int MISSINGVALUE = -99;
public static char COLON_DELIMITER = ':';
public static char TAB_DELIMITER = '\t';
public static char COMMA_DELIMITER = ',';
public static String SCOLON_DELIMITER = ":";
public static String STAB_DELIMITER = "\t";
public static String SCOMMA_DELIMITER = ",";
public static String SHYPHEN_DELIMITER = "-";
public static String SSPACE_DELIMITER = " ";
public static String SPERIOD_DELIMITER = ".";
public static String SSLASH_DELIMITER = "/";
public static String SBACKSLASH_DELIMITER = "\\";
public static String SEQUAL_DELIMITER = "=";
/**
* 8 bit integer
*/
public static int EPBYTE = 0;
/**
* Sring data
*/
public static int EPCHAR = 1;
/**
* 16 bit integer
*/
public static int EPSHORT = 2;
/**
* 32 bit integer
*/
public static int EPINT = 3;
/**
* 32 bit floating point
*/
public static int EPREAL = 4;
/**
* 64 bit floating point
*/
public static int EPDOUBLE = 5;
public static int MAX_NC_DIMS = 100;
public static int EPNONEAXIS = -1;
public static int EPSPACE = 0;
public static int EPTIME = 1;
public static int EPXAXIS = 2;
public static int EPYAXIS = 3;
public static int EPZAXIS = 4;
public static int EPTAXIS = 5;
public static int EPINTT = 6;
public static int EPREALT = 7;
public static int EPTDUMMY = 8;
public static int EPXDUMMY = 9;
public static int EPYDUMMY = 10;
public static int EPZDUMMY = 11;
public static int CANONICALTIME = 12;
public static int PROFILEPTRS = 1;
public static int TSPTRS = 2;
public static int SIMPLEPTRS = 3;
public static int POASECTION = 4;
public static int WOCESECTION = 5;
public static int SD2SECTION = 6;
public static int SD3SECTION = 7;
public static int SSSECTION = 8;
public static int XMLPTRS = 9;
public static int ARGOPTRS = 10;
public static int GTSPPPTRS = 11;
/**
* Sort criteria<br>
*/
public static int X_ASC = 1;
public static int X_DSC = 2;
public static int Y_ASC = 3;
public static int Y_DSC = 4;
public static int Z_ASC = 5;
public static int Z_DSC = 6;
public static int T_ASC = 7;
public static int T_DSC = 8;
public static boolean NC_NOWRITE = true;
public static boolean NC_WRITE = false;
public static int NC_UNSPECIFIED = 0;/* private */
public static int NC_BYTE = 1;
public static int NC_CHAR = 2;
public static int NC_SHORT = 3;
public static int NC_LONG = 4;
public static int NC_FLOAT = 5;
public static int NC_DOUBLE = 6;
public static int NC_BITFIELD = 7;
public static int NC_STRING = 8;
public static int NC_IARRAY = 9;
public static int NC_DIMENSION = 10;
public static int NC_VARIABLE = 11;
public static int NC_ATTRIBUTE = 12;
public static long GREGORIAN = (15+31*(10+12*1582));
public static long JULGREG = 299161;
/**
* "CRUISE" CTD attribute<br>
* Cruise number
*/
public static String EPCRUISE = "CRUISE";
/**
* "CAST" CTD attribute<br>
* cast number
*/
public static String EPCAST = "CAST";
/**
* "INST_TYPE" required EPIC attribute
* instrument type
*/
public static String EPINSTTYPE = "INST_TYPE";
/**
* "CREATION_DATE"
* file creation date
*/
public static String EPCRDATE = "CREATION_DATE";
/**
* "BOTTLE" CTD attribute<br>
* Bottle data flag (=1 if bottle)
*/
public static String EPBOTTLE = "BOTTLE";
/**
*
*/
public static String EPCASTNUM = "CAST_NUMBER";
/**
* "DATA_TYPE" required EPIC attribute<br>
* legal values include "CTD", "TIME", "TRACK",
* and "GRID"
*/
public static String EPDATATYPE = "DATA_TYPE";
/**
* "DATA_SUBTYPE" required EPIC attribute
*/
public static String EPSUBTYPE = "DATA_SUBTYPE";
/**
* "EXPERIMENT" Time Series attribute<br>
* experiment name
* legal values include "CTD" and "BOTTLE"
*/
public static String EPEXPERIMENT = "EXPERIMENT";
/**
* "PROJECT" Time Series attribute <br>
* Project name
*/
public static String EPPROJECT = "PROJECT";
/**
* "MOORING" Time Series attribute<br>
* Mooring identification
*/
public static String EPMOORING = "MOORING";
/**
* "DELTA_T" Time Series attribute<br>
* series delta-t description
*/
public static String EPDELTAT = "DELTA_T";
/**
* "COMPOSITE" Time Series attribute<br>
*/
public static String EPCOMPOSITE = "COMPOSITE";
/**
* "POS_CONST" Time Series attribute<br>
* consistent position flag (=1 not consistent)
*/
public static String EPPOSCONST = "POS_CONST";
/**
* "DEPTH_CONST" Time Series attribute<br>
* consistent depth flag (=1 not consistent)
*/
public static String EPDEPTHCONST = "DEPTH_CONST";
/**
* "DATA_ORIGIN" required EPIC attribute
*/
public static String EPDATAORIGIN = "DATA_ORIGIN";
/**
* "DESCRIPT" Time Series attribute<br>
* text description field
*/
public static String EPDESCRIPT = "DESCRIPT";
/**
* "DATA_CMNT" Time Series attribute<br>
* data comment
*/
public static String EPDATACMNT = "DATA_CMNT";
/**
* "COORD_SYSTEM" required EPIC attribute<br>
* value of "GEOGRAPHICAL" for classic EPIC data
*/
public static String EPCOORDSYS = "COORD_SYSTEM";
/**
* "WATER_MASS" CTD and Time Series attribute <br>
* Water Mass flag <br>
* <p align="left">The WATER MASS attribute is used
* by EPIC contouring programs to decide the default
* contouring level. Refering to following table for valid
* Water Mass flags:</p>
* <table border="1">
*<tr>
* <td>FLAG</td>
* <td>Default contouring level used for water mass at region</td>
*</tr>
*<tr>
* <td>
* <div align="center">"B"</div>
* </td>
* <td>
* <div align="center">Bering Sea</div>
* </td>
*</tr>
*<tr>
* <td>
* <div align="center">"G"</div>
* </td>
* <td>
* <div align="center">Gulf of Alaska</div>
* </td>
*</tr>
*<tr>
* <td>
* <div align="center">"S" </div>
* </td>
* <td>
* <div align="center">Shelikof </div>
* </td>
*</tr>
*<tr>
* <td>
* <div align="center">"V"</div>
* </td>
* <td>
* <div align="center">Vents </div>
* </td>
*</tr>
*<tr>
* <td>
* <div align="center">"P"</div>
* </td>
* <td>
* <div align="center">Puget Sound</div>
* </td>
*</tr>
*<tr>
* <td>
* <div align="center">"E"</div>
* </td>
* <td>
* <div align="center">Equatorial</div>
* </td>
*</tr>
*<tr>
* <td>
* <div align="center">" " </div>
* </td>
* <td>
* <div align="center">Equatorial</div>
* </td>
*</tr>
* </table>
*
*/
public static String EPWATERMASS = "WATER_MASS";
/**
* "DRIFTER" Time Series attribute<br>
* drifter flag (=1 if drifter)
*/
public static String EPDRIFTER = "DRIFTER";
/**
* "WEATHER" CTD attribute<br>
* Weather code (0-9)
*/
public static String EPWEATHER = "WEATHER";
/**
* "SEA_STATE" CTD attribute<br>
* Sea state code (0-9)
*/
public static String EPSEASTATE = "SEA_STATE";
/**
* "BAROMETER" CTD attribute<br>
* Atmospheric pressure in millibars
*/
public static String EPBAROMETER = "BAROMETER";
/**
* "WIND_DIR" CTD attribute<br>
* Wind direction in degrees from north
*/
public static String EPWINDDIR = "WIND_DIR";
/**
* "WIND_SPEED" CTD attribute<br>
* Wind speed in knots
*/
public static String EPWINDSPEED = "WIND_SPEED";
/**
* "VISIBILITY" CTD attribute<br>
* Visibility code (0-9)
*/
public static String EPVISIBILITY = "VISIBILITY";
/**
* "CLOUD_TYPE" CTD attribute<br>
* Cloud type code (0-9, X)
*/
public static String EPCLOUDTYPE = "CLOUD_TYPE";
/**
* "CLOUD_AMOUNT" CTD attribute<br>
* Cloud amount code (0-9)
*/
public static String EPCLOUDAMOUNT = "CLOUD_AMOUNT";
/**
* "AIR_TEMP" CTD attribute<br>
* Dry air temperature
*/
public static String EPAIRTEMP = "AIR_TEMP";
/**
* "WET_BULB" CTD attribute<br>
* Web bulb temperature
*/
public static String EPWETBULB = "WET_BULB";
/**
* "WATER_DEPTH" CTD and Time Series attribute<br>
* Water depth to nearest meter
*/
public static String EPWATERDEPTH = "WATER_DEPTH";
/**
* "VAR_DESC" Time Series attribute<br>
* text field describing variables
*/
public static String EPVARDESC = "VAR_DESC";
/**
* "FILL_FLAG" Time Series attribute<br>
* data fill flag (=1 if data has fill values)
*/
public static String EPFILLFLAG = "FILL_FLAG";
/**
* "VAR_FILL" Time Series attribute<br>
* character string
*/
public static String EPVARFILL = "VAR_FILL";
/**
* "PROG_CMNT1" latest program comment
*/
public static String EPPROGCMNT1 = "PROG_CMNT1";
/**
* "PROG_CMNT2" next program comment
*/
public static String EPPROGCMNT2 = "PROG_CMNT2";
/**
* "PROG_CMNT3" next program comment
*/
public static String EPPROGCMNT3 = "PROG_CMNT3";
/**
* "PROG_CMNT4" oldest program comment
*/
public static String EPPROGCMNT4 = "PROG_CMNT4";
/**
* "LAT_PC" optional Time Series attribute<br>
* piece measurement latitude
*/
public static String EPLATPC = "LAT_PC";
/**
* "LONG_PC" optional Time Series attribute<br>
* piece measurement longitude
*/
public static String EPLONGPC = "LONG_PC";
/**
* "START_PC" optional Time Series attribute<br>
* piece start time and date
*/
public static String EPSTARTPC = "START_PC";
/**
* "END_PC" optional Time Series attribute<br>
* piece stop time and date
*/
public static String EPENDPC = "END_PC";
/**
* "INST_DEPTH_PC" optional Time Series attribute<br>
* piece measurement depth (m)
*/
public static String EPINSTDEPTHPC = "INST_DEPTH_PC";
/**
* "INDENT_PC" optional Time Series attribute<br>
* piece identification
*/
public static String EPIDENTPC = "IDENT_PC";
/**
* "IMAGE" card image from classic EPIC data file
*/
public static String EPIMAGE = "IMAGE";
/**
* Evenly spaced data values in the axis
*/
public static String EPEVEN = "EVEN";
/**
* Unevenly spaced data values in the axis
*/
public static String EPUNEVEN = "UNEVEN";
/**
* Evenly spaced data values in the axis
*/
public static String EPEVEN_INT = "EVENI";
/**
* Evenly spaced data values in the axis
*/
public static String EPEVEN_REAL = "EVENR";
/**
* Unevenly spaced data values in the axis
*/
public static String EPUNEVEN_INT = "UNEVENI";
/**
* Unevenly spaced data values in the axis
*/
public static String EPUNEVEN_REAL = "UNEVENR";
/**
* File open for read only
*/
public static int EPREAD = 0;
/**
* File open for create
*/
public static int EPCREATE = 1;
/**
* File open for edit (append or overwrite)
*/
public static int EPEDIT = 2;
/**
* Synonyms for the x axis
*/
public static String[] xname = {"x",
"longitude",
null};
/**
* Synonyms for the y axis
*/
public static String[] yname = {"y",
"latitude",
null};
/**
* Synonyms for the z axis
*/
public static String[] zname = {"z",
"depth",
"elevation",
null};
/**
* Synonyms for the y axis units
*/
public static String[] yunit = {"degree_north",
"degrees_north",
"degreeN",
"degrees_N",
"degreesN",
null};
/**
* Synonyms for the x axis units
*/
public static String[] xunit = {"degree_east",
"degrees_east",
"degree_E",
"degreeE",
"degrees_E",
"degreesE",
null};
/**
* Synonyms for the z axis units
*/
public static String[] zunit = {"z",
"depth",
"elevation",
"dbar",
"mbar",
"Pa",
null};
/**
* Conversions for time in various units to seconds
*/
public static TimeToSecond[] time_units = {
new TimeToSecond("year", 3.1536e+7, false),
new TimeToSecond("yr" , 3.1536e+7, false),
new TimeToSecond("a" , 3.1536e+7, true),
new TimeToSecond("day", 8.64e+04, false),
new TimeToSecond("d", 8.64e+04, true),
new TimeToSecond("hour", 3.6e+03, false),
new TimeToSecond("hr", 3.6e+03, false),
new TimeToSecond("h", 3.6e+03, true),
new TimeToSecond("minute", 60, false),
new TimeToSecond("min", 60, false),
new TimeToSecond("second", 1, false),
new TimeToSecond("sec", 1, false),
new TimeToSecond("s", 1, true),
new TimeToSecond("msec", 1e-3, false),
new TimeToSecond("msecs", 1e-3, false),
new TimeToSecond("millisecond", 1e-3, false),
new TimeToSecond("millisec", 1e-3, false),
new TimeToSecond("millis", 1e-3, true),
new TimeToSecond("shake", 1e-8, false),
new TimeToSecond("sidereal_day",8.616409e4, false),
new TimeToSecond("sidereal_minute",5.983617e1,false),
new TimeToSecond("sidereal_second",0.9972696, false),
new TimeToSecond("sidereal_year",3.155815e7, false),
new TimeToSecond("tropical_year",3.155693e7, false),
new TimeToSecond("eon", 3.1536e+16, false),
new TimeToSecond("fortnight", 1.2096e+06, false),
new TimeToSecond("0", 0, false)
};
static String[] LongMonths = {
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
};
static String[] LongWeekDays = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
static int[] max_day = {31,28,31,30,31,30,31,31,30,31,30,31};
static String[] dummyName = {"tdummy", "zdummy", "ydummy", "xdummy"};
public static int PTRFILEFORMAT = 0;
public static int JOAFORMAT = 1;
public static int POAFORMAT = 2;
public static int SSFORMAT = 3;
public static int SD2FORMAT = 4;
public static int SD3FORMAT = 5;
public static int WOCEHYDFORMAT = 6;
public static int WOCECTDFORMAT = 7;
public static int NETCDFFORMAT = 8;
public static int ZIPSECTIONFILEFORMAT = 9;
public static int NETCDFXBTFORMAT = 10;
public static int DODSNETCDFFORMAT = 11;
public static int JOPIFORMAT = 12;
public static int XMLPTRFILEFORMAT = 13;
public static int GZIPTARSECTIONFILEFORMAT = 14;
public static int GZIPFILEFORMAT = 15;
public static int ARGOINVENTORYFORMAT = 16;
public static int GTSPPINVENTORYFORMAT = 17;
public static int ARGONODCNETCDFFORMAT = 18;
public static int XYZFORMAT = 19;
public static int TEXTFORMAT = 20;
public static int NQDBFORMAT = 21;
public static int WODCSVFORMAT = 22;
public static int ARGOGDACNETCDFFORMAT = 23;
public static int UNKNOWNFORMAT = 99;
public static int MATCHES = 0;
public static int STARTSWITH = 1;
public static int CONTAINS = 2;
public static int ALL_OBS = 1;
}
| OceanAtlas/JOA | gov/noaa/pmel/eps2/EPSConstants.java | Java | gpl-2.0 | 15,827 |
<?php if(have_posts()) : ?>
<div class="imagethumbs"><?php ioya_the_images( $posts, apply_filters( 'ioya_image_count', 8 ), apply_filters( 'ioya_image_size', array(44, 44) ) ); ?></div>
<?php while (have_posts()) : the_post(); ?>
<div class="post">
<small><?php the_date(); ?></small>
<h3><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
<?php the_excerpt(); ?>
</div>
<?php endwhile; ?>
<?php else : ?>
<div class="post">
<p><?php _e('Sorry, we didn\'t find any posts for this month.', 'ioya'); ?></p>
</div>
<?php endif; ?>
| jarednova/Passport | wp-content/plugins/in-over-your-archives/ioya_month.php | PHP | gpl-2.0 | 643 |
<?php
/**
* Core Design Web Gallery plugin for Joomla! 2.5
* @author Daniel Rataj, <info@greatjoomla.com>
* @package Joomla
* @subpackage Content
* @category Plugin
* @version 2.5.x.2.0.5
* @copyright Copyright (C) 2007 - 2012 Great Joomla!, http://www.greatjoomla.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL 3
*
* This file is part of Great Joomla! extension.
* This extension is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This extension is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
$path = '';
if (isset($_GET['path'])) $path = (string )$_GET['path'];
if (extension_loaded('zlib') && !ini_get('zlib.output_compression')) @ob_start('ob_gzhandler');
header("Content-type: application/x-javascript");
header('Cache-Control: must-revalidate');
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 86400) . ' GMT');
echo "var GB_ROOT_DIR = '$path'";
?> | fatwayne/heart-bridge-joomla | plugins/content/cdwebgallery/engine/greybox/app/application.js.php | PHP | gpl-2.0 | 1,422 |
/* $Id: PDMAsyncCompletion.cpp $ */
/** @file
* PDM Async I/O - Transport data asynchronous in R3 using EMT.
*/
/*
* Copyright (C) 2006-2011 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#define LOG_GROUP LOG_GROUP_PDM_ASYNC_COMPLETION
#include "PDMInternal.h"
#include <VBox/vmm/pdm.h>
#include <VBox/vmm/mm.h>
#ifdef VBOX_WITH_REM
# include <VBox/vmm/rem.h>
#endif
#include <VBox/vmm/vm.h>
#include <VBox/vmm/uvm.h>
#include <VBox/err.h>
#include <VBox/log.h>
#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/thread.h>
#include <iprt/mem.h>
#include <iprt/critsect.h>
#include <iprt/tcp.h>
#include <iprt/path.h>
#include <iprt/string.h>
#include <VBox/vmm/pdmasynccompletion.h>
#include "PDMAsyncCompletionInternal.h"
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
/**
* Async I/O type.
*/
typedef enum PDMASYNCCOMPLETIONTEMPLATETYPE
{
/** Device . */
PDMASYNCCOMPLETIONTEMPLATETYPE_DEV = 1,
/** Driver consumer. */
PDMASYNCCOMPLETIONTEMPLATETYPE_DRV,
/** Internal consumer. */
PDMASYNCCOMPLETIONTEMPLATETYPE_INTERNAL,
/** Usb consumer. */
PDMASYNCCOMPLETIONTEMPLATETYPE_USB
} PDMASYNCTEMPLATETYPE;
/**
* PDM Async I/O template.
*/
typedef struct PDMASYNCCOMPLETIONTEMPLATE
{
/** Pointer to the next template in the list. */
R3PTRTYPE(PPDMASYNCCOMPLETIONTEMPLATE) pNext;
/** Pointer to the previous template in the list. */
R3PTRTYPE(PPDMASYNCCOMPLETIONTEMPLATE) pPrev;
/** Type specific data. */
union
{
/** PDMASYNCCOMPLETIONTEMPLATETYPE_DEV */
struct
{
/** Pointer to consumer function. */
R3PTRTYPE(PFNPDMASYNCCOMPLETEDEV) pfnCompleted;
/** Pointer to the device instance owning the template. */
R3PTRTYPE(PPDMDEVINS) pDevIns;
} Dev;
/** PDMASYNCCOMPLETIONTEMPLATETYPE_DRV */
struct
{
/** Pointer to consumer function. */
R3PTRTYPE(PFNPDMASYNCCOMPLETEDRV) pfnCompleted;
/** Pointer to the driver instance owning the template. */
R3PTRTYPE(PPDMDRVINS) pDrvIns;
/** User argument given during template creation.
* This is only here to make things much easier
* for DrVVD. */
void *pvTemplateUser;
} Drv;
/** PDMASYNCCOMPLETIONTEMPLATETYPE_INTERNAL */
struct
{
/** Pointer to consumer function. */
R3PTRTYPE(PFNPDMASYNCCOMPLETEINT) pfnCompleted;
/** Pointer to user data. */
R3PTRTYPE(void *) pvUser;
} Int;
/** PDMASYNCCOMPLETIONTEMPLATETYPE_USB */
struct
{
/** Pointer to consumer function. */
R3PTRTYPE(PFNPDMASYNCCOMPLETEUSB) pfnCompleted;
/** Pointer to the usb instance owning the template. */
R3PTRTYPE(PPDMUSBINS) pUsbIns;
} Usb;
} u;
/** Template type. */
PDMASYNCCOMPLETIONTEMPLATETYPE enmType;
/** Pointer to the VM. */
R3PTRTYPE(PVM) pVM;
/** Use count of the template. */
volatile uint32_t cUsed;
} PDMASYNCCOMPLETIONTEMPLATE;
/**
* Bandwidth control manager instance data
*/
typedef struct PDMACBWMGR
{
/** Pointer to the next manager in the list. */
struct PDMACBWMGR *pNext;
/** Pointer to the shared UVM structure. */
PPDMASYNCCOMPLETIONEPCLASS pEpClass;
/** Identifier of the manager. */
char *pszId;
/** Maximum number of bytes the endpoints are allowed to transfer (Max is 4GB/s currently) */
volatile uint32_t cbTransferPerSecMax;
/** Number of bytes we start with */
volatile uint32_t cbTransferPerSecStart;
/** Step after each update */
volatile uint32_t cbTransferPerSecStep;
/** Number of bytes we are allowed to transfer till the next update.
* Reset by the refresh timer. */
volatile uint32_t cbTransferAllowed;
/** Timestamp of the last update */
volatile uint64_t tsUpdatedLast;
/** Reference counter - How many endpoints are associated with this manager. */
volatile uint32_t cRefs;
} PDMACBWMGR;
/** Pointer to a bandwidth control manager pointer. */
typedef PPDMACBWMGR *PPPDMACBWMGR;
/*******************************************************************************
* Internal Functions *
*******************************************************************************/
static void pdmR3AsyncCompletionPutTask(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, PPDMASYNCCOMPLETIONTASK pTask);
/**
* Internal worker for the creation apis
*
* @returns VBox status.
* @param pVM Pointer to the VM.
* @param ppTemplate Where to store the template handle.
*/
static int pdmR3AsyncCompletionTemplateCreate(PVM pVM, PPPDMASYNCCOMPLETIONTEMPLATE ppTemplate,
PDMASYNCCOMPLETIONTEMPLATETYPE enmType)
{
PUVM pUVM = pVM->pUVM;
AssertPtrReturn(ppTemplate, VERR_INVALID_POINTER);
PPDMASYNCCOMPLETIONTEMPLATE pTemplate;
int rc = MMR3HeapAllocZEx(pVM, MM_TAG_PDM_ASYNC_COMPLETION, sizeof(PDMASYNCCOMPLETIONTEMPLATE), (void **)&pTemplate);
if (RT_FAILURE(rc))
return rc;
/*
* Initialize fields.
*/
pTemplate->pVM = pVM;
pTemplate->cUsed = 0;
pTemplate->enmType = enmType;
/*
* Add template to the global VM template list.
*/
RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
pTemplate->pNext = pUVM->pdm.s.pAsyncCompletionTemplates;
if (pUVM->pdm.s.pAsyncCompletionTemplates)
pUVM->pdm.s.pAsyncCompletionTemplates->pPrev = pTemplate;
pUVM->pdm.s.pAsyncCompletionTemplates = pTemplate;
RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
*ppTemplate = pTemplate;
return VINF_SUCCESS;
}
/**
* Creates a async completion template for a device instance.
*
* The template is used when creating new completion tasks.
*
* @returns VBox status code.
* @param pVM Pointer to the VM.
* @param pDevIns The device instance.
* @param ppTemplate Where to store the template pointer on success.
* @param pfnCompleted The completion callback routine.
* @param pszDesc Description.
*/
VMMR3DECL(int) PDMR3AsyncCompletionTemplateCreateDevice(PVM pVM, PPDMDEVINS pDevIns, PPPDMASYNCCOMPLETIONTEMPLATE ppTemplate, PFNPDMASYNCCOMPLETEDEV pfnCompleted, const char *pszDesc)
{
LogFlow(("%s: pDevIns=%p ppTemplate=%p pfnCompleted=%p pszDesc=%s\n",
__FUNCTION__, pDevIns, ppTemplate, pfnCompleted, pszDesc));
/*
* Validate input.
*/
VM_ASSERT_EMT(pVM);
AssertPtrReturn(pfnCompleted, VERR_INVALID_POINTER);
AssertPtrReturn(ppTemplate, VERR_INVALID_POINTER);
/*
* Create the template.
*/
PPDMASYNCCOMPLETIONTEMPLATE pTemplate;
int rc = pdmR3AsyncCompletionTemplateCreate(pVM, &pTemplate, PDMASYNCCOMPLETIONTEMPLATETYPE_DEV);
if (RT_SUCCESS(rc))
{
pTemplate->u.Dev.pDevIns = pDevIns;
pTemplate->u.Dev.pfnCompleted = pfnCompleted;
*ppTemplate = pTemplate;
Log(("PDM: Created device template %p: pfnCompleted=%p pDevIns=%p\n",
pTemplate, pfnCompleted, pDevIns));
}
return rc;
}
/**
* Creates a async completion template for a driver instance.
*
* The template is used when creating new completion tasks.
*
* @returns VBox status code.
* @param pVM Pointer to the VM.
* @param pDrvIns The driver instance.
* @param ppTemplate Where to store the template pointer on success.
* @param pfnCompleted The completion callback routine.
* @param pvTemplateUser Template user argument
* @param pszDesc Description.
*/
VMMR3DECL(int) PDMR3AsyncCompletionTemplateCreateDriver(PVM pVM, PPDMDRVINS pDrvIns, PPPDMASYNCCOMPLETIONTEMPLATE ppTemplate, PFNPDMASYNCCOMPLETEDRV pfnCompleted, void *pvTemplateUser, const char *pszDesc)
{
LogFlow(("%s: pDrvIns=%p ppTemplate=%p pfnCompleted=%p pszDesc=%s\n",
__FUNCTION__, pDrvIns, ppTemplate, pfnCompleted, pszDesc));
/*
* Validate input.
*/
AssertPtrReturn(pfnCompleted, VERR_INVALID_POINTER);
AssertPtrReturn(ppTemplate, VERR_INVALID_POINTER);
/*
* Create the template.
*/
PPDMASYNCCOMPLETIONTEMPLATE pTemplate;
int rc = pdmR3AsyncCompletionTemplateCreate(pVM, &pTemplate, PDMASYNCCOMPLETIONTEMPLATETYPE_DRV);
if (RT_SUCCESS(rc))
{
pTemplate->u.Drv.pDrvIns = pDrvIns;
pTemplate->u.Drv.pfnCompleted = pfnCompleted;
pTemplate->u.Drv.pvTemplateUser = pvTemplateUser;
*ppTemplate = pTemplate;
Log(("PDM: Created driver template %p: pfnCompleted=%p pDrvIns=%p\n",
pTemplate, pfnCompleted, pDrvIns));
}
return rc;
}
/**
* Creates a async completion template for a USB device instance.
*
* The template is used when creating new completion tasks.
*
* @returns VBox status code.
* @param pVM Pointer to the VM.
* @param pUsbIns The USB device instance.
* @param ppTemplate Where to store the template pointer on success.
* @param pfnCompleted The completion callback routine.
* @param pszDesc Description.
*/
VMMR3DECL(int) PDMR3AsyncCompletionTemplateCreateUsb(PVM pVM, PPDMUSBINS pUsbIns, PPPDMASYNCCOMPLETIONTEMPLATE ppTemplate, PFNPDMASYNCCOMPLETEUSB pfnCompleted, const char *pszDesc)
{
LogFlow(("%s: pUsbIns=%p ppTemplate=%p pfnCompleted=%p pszDesc=%s\n",
__FUNCTION__, pUsbIns, ppTemplate, pfnCompleted, pszDesc));
/*
* Validate input.
*/
VM_ASSERT_EMT(pVM);
AssertPtrReturn(pfnCompleted, VERR_INVALID_POINTER);
AssertPtrReturn(ppTemplate, VERR_INVALID_POINTER);
/*
* Create the template.
*/
PPDMASYNCCOMPLETIONTEMPLATE pTemplate;
int rc = pdmR3AsyncCompletionTemplateCreate(pVM, &pTemplate, PDMASYNCCOMPLETIONTEMPLATETYPE_USB);
if (RT_SUCCESS(rc))
{
pTemplate->u.Usb.pUsbIns = pUsbIns;
pTemplate->u.Usb.pfnCompleted = pfnCompleted;
*ppTemplate = pTemplate;
Log(("PDM: Created usb template %p: pfnCompleted=%p pDevIns=%p\n",
pTemplate, pfnCompleted, pUsbIns));
}
return rc;
}
/**
* Creates a async completion template for internally by the VMM.
*
* The template is used when creating new completion tasks.
*
* @returns VBox status code.
* @param pVM Pointer to the VM.
* @param ppTemplate Where to store the template pointer on success.
* @param pfnCompleted The completion callback routine.
* @param pvUser2 The 2nd user argument for the callback.
* @param pszDesc Description.
*/
VMMR3DECL(int) PDMR3AsyncCompletionTemplateCreateInternal(PVM pVM, PPPDMASYNCCOMPLETIONTEMPLATE ppTemplate, PFNPDMASYNCCOMPLETEINT pfnCompleted, void *pvUser2, const char *pszDesc)
{
LogFlow(("%s: ppTemplate=%p pfnCompleted=%p pvUser2=%p pszDesc=%s\n",
__FUNCTION__, ppTemplate, pfnCompleted, pvUser2, pszDesc));
/*
* Validate input.
*/
VM_ASSERT_EMT(pVM);
AssertPtrReturn(pfnCompleted, VERR_INVALID_POINTER);
AssertPtrReturn(ppTemplate, VERR_INVALID_POINTER);
/*
* Create the template.
*/
PPDMASYNCCOMPLETIONTEMPLATE pTemplate;
int rc = pdmR3AsyncCompletionTemplateCreate(pVM, &pTemplate, PDMASYNCCOMPLETIONTEMPLATETYPE_INTERNAL);
if (RT_SUCCESS(rc))
{
pTemplate->u.Int.pvUser = pvUser2;
pTemplate->u.Int.pfnCompleted = pfnCompleted;
*ppTemplate = pTemplate;
Log(("PDM: Created internal template %p: pfnCompleted=%p pvUser2=%p\n",
pTemplate, pfnCompleted, pvUser2));
}
return rc;
}
/**
* Destroys the specified async completion template.
*
* @returns VBox status codes:
* @retval VINF_SUCCESS on success.
* @retval VERR_PDM_ASYNC_TEMPLATE_BUSY if the template is still in use.
*
* @param pTemplate The template in question.
*/
VMMR3DECL(int) PDMR3AsyncCompletionTemplateDestroy(PPDMASYNCCOMPLETIONTEMPLATE pTemplate)
{
LogFlow(("%s: pTemplate=%p\n", __FUNCTION__, pTemplate));
if (!pTemplate)
{
AssertMsgFailed(("pTemplate is NULL!\n"));
return VERR_INVALID_PARAMETER;
}
/*
* Check if the template is still used.
*/
if (pTemplate->cUsed > 0)
{
AssertMsgFailed(("Template is still in use\n"));
return VERR_PDM_ASYNC_TEMPLATE_BUSY;
}
/*
* Unlink the template from the list.
*/
PUVM pUVM = pTemplate->pVM->pUVM;
RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
PPDMASYNCCOMPLETIONTEMPLATE pPrev = pTemplate->pPrev;
PPDMASYNCCOMPLETIONTEMPLATE pNext = pTemplate->pNext;
if (pPrev)
pPrev->pNext = pNext;
else
pUVM->pdm.s.pAsyncCompletionTemplates = pNext;
if (pNext)
pNext->pPrev = pPrev;
RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
/*
* Free the template.
*/
MMR3HeapFree(pTemplate);
return VINF_SUCCESS;
}
/**
* Destroys all the specified async completion templates for the given device instance.
*
* @returns VBox status codes:
* @retval VINF_SUCCESS on success.
* @retval VERR_PDM_ASYNC_TEMPLATE_BUSY if one or more of the templates are still in use.
*
* @param pVM Pointer to the VM.
* @param pDevIns The device instance.
*/
VMMR3DECL(int) PDMR3AsyncCompletionTemplateDestroyDevice(PVM pVM, PPDMDEVINS pDevIns)
{
LogFlow(("%s: pDevIns=%p\n", __FUNCTION__, pDevIns));
/*
* Validate input.
*/
if (!pDevIns)
return VERR_INVALID_PARAMETER;
VM_ASSERT_EMT(pVM);
/*
* Unlink it.
*/
PUVM pUVM = pVM->pUVM;
RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
PPDMASYNCCOMPLETIONTEMPLATE pTemplate = pUVM->pdm.s.pAsyncCompletionTemplates;
while (pTemplate)
{
if ( pTemplate->enmType == PDMASYNCCOMPLETIONTEMPLATETYPE_DEV
&& pTemplate->u.Dev.pDevIns == pDevIns)
{
PPDMASYNCCOMPLETIONTEMPLATE pTemplateDestroy = pTemplate;
pTemplate = pTemplate->pNext;
int rc = PDMR3AsyncCompletionTemplateDestroy(pTemplateDestroy);
if (RT_FAILURE(rc))
{
RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
return rc;
}
}
else
pTemplate = pTemplate->pNext;
}
RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
return VINF_SUCCESS;
}
/**
* Destroys all the specified async completion templates for the given driver instance.
*
* @returns VBox status codes:
* @retval VINF_SUCCESS on success.
* @retval VERR_PDM_ASYNC_TEMPLATE_BUSY if one or more of the templates are still in use.
*
* @param pVM Pointer to the VM.
* @param pDrvIns The driver instance.
*/
VMMR3DECL(int) PDMR3AsyncCompletionTemplateDestroyDriver(PVM pVM, PPDMDRVINS pDrvIns)
{
LogFlow(("%s: pDevIns=%p\n", __FUNCTION__, pDrvIns));
/*
* Validate input.
*/
if (!pDrvIns)
return VERR_INVALID_PARAMETER;
VM_ASSERT_EMT(pVM);
/*
* Unlink it.
*/
PUVM pUVM = pVM->pUVM;
RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
PPDMASYNCCOMPLETIONTEMPLATE pTemplate = pUVM->pdm.s.pAsyncCompletionTemplates;
while (pTemplate)
{
if ( pTemplate->enmType == PDMASYNCCOMPLETIONTEMPLATETYPE_DRV
&& pTemplate->u.Drv.pDrvIns == pDrvIns)
{
PPDMASYNCCOMPLETIONTEMPLATE pTemplateDestroy = pTemplate;
pTemplate = pTemplate->pNext;
int rc = PDMR3AsyncCompletionTemplateDestroy(pTemplateDestroy);
if (RT_FAILURE(rc))
{
RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
return rc;
}
}
else
pTemplate = pTemplate->pNext;
}
RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
return VINF_SUCCESS;
}
/**
* Destroys all the specified async completion templates for the given USB device instance.
*
* @returns VBox status codes:
* @retval VINF_SUCCESS on success.
* @retval VERR_PDM_ASYNC_TEMPLATE_BUSY if one or more of the templates are still in use.
*
* @param pVM Pointer to the VM.
* @param pUsbIns The USB device instance.
*/
VMMR3DECL(int) PDMR3AsyncCompletionTemplateDestroyUsb(PVM pVM, PPDMUSBINS pUsbIns)
{
LogFlow(("%s: pUsbIns=%p\n", __FUNCTION__, pUsbIns));
/*
* Validate input.
*/
if (!pUsbIns)
return VERR_INVALID_PARAMETER;
VM_ASSERT_EMT(pVM);
/*
* Unlink it.
*/
PUVM pUVM = pVM->pUVM;
RTCritSectEnter(&pUVM->pdm.s.ListCritSect);
PPDMASYNCCOMPLETIONTEMPLATE pTemplate = pUVM->pdm.s.pAsyncCompletionTemplates;
while (pTemplate)
{
if ( pTemplate->enmType == PDMASYNCCOMPLETIONTEMPLATETYPE_USB
&& pTemplate->u.Usb.pUsbIns == pUsbIns)
{
PPDMASYNCCOMPLETIONTEMPLATE pTemplateDestroy = pTemplate;
pTemplate = pTemplate->pNext;
int rc = PDMR3AsyncCompletionTemplateDestroy(pTemplateDestroy);
if (RT_FAILURE(rc))
{
RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
return rc;
}
}
else
pTemplate = pTemplate->pNext;
}
RTCritSectLeave(&pUVM->pdm.s.ListCritSect);
return VINF_SUCCESS;
}
static PPDMACBWMGR pdmacBwMgrFindById(PPDMASYNCCOMPLETIONEPCLASS pEpClass, const char *pcszId)
{
PPDMACBWMGR pBwMgr = NULL;
if (RT_VALID_PTR(pcszId))
{
int rc = RTCritSectEnter(&pEpClass->CritSect); AssertRC(rc);
pBwMgr = pEpClass->pBwMgrsHead;
while ( pBwMgr
&& RTStrCmp(pBwMgr->pszId, pcszId))
pBwMgr = pBwMgr->pNext;
rc = RTCritSectLeave(&pEpClass->CritSect); AssertRC(rc);
}
return pBwMgr;
}
static void pdmacBwMgrLink(PPDMACBWMGR pBwMgr)
{
PPDMASYNCCOMPLETIONEPCLASS pEpClass = pBwMgr->pEpClass;
int rc = RTCritSectEnter(&pEpClass->CritSect); AssertRC(rc);
pBwMgr->pNext = pEpClass->pBwMgrsHead;
pEpClass->pBwMgrsHead = pBwMgr;
rc = RTCritSectLeave(&pEpClass->CritSect); AssertRC(rc);
}
#ifdef SOME_UNUSED_FUNCTION
static void pdmacBwMgrUnlink(PPDMACBWMGR pBwMgr)
{
PPDMASYNCCOMPLETIONEPCLASS pEpClass = pBwMgr->pEpClass;
int rc = RTCritSectEnter(&pEpClass->CritSect); AssertRC(rc);
if (pBwMgr == pEpClass->pBwMgrsHead)
pEpClass->pBwMgrsHead = pBwMgr->pNext;
else
{
PPDMACBWMGR pPrev = pEpClass->pBwMgrsHead;
while ( pPrev
&& pPrev->pNext != pBwMgr)
pPrev = pPrev->pNext;
AssertPtr(pPrev);
pPrev->pNext = pBwMgr->pNext;
}
rc = RTCritSectLeave(&pEpClass->CritSect); AssertRC(rc);
}
#endif /* SOME_UNUSED_FUNCTION */
static int pdmacAsyncCompletionBwMgrCreate(PPDMASYNCCOMPLETIONEPCLASS pEpClass, const char *pcszBwMgr, uint32_t cbTransferPerSecMax,
uint32_t cbTransferPerSecStart, uint32_t cbTransferPerSecStep)
{
LogFlowFunc(("pEpClass=%#p pcszBwMgr=%#p{%s} cbTransferPerSecMax=%u cbTransferPerSecStart=%u cbTransferPerSecStep=%u\n",
pEpClass, pcszBwMgr, cbTransferPerSecMax, cbTransferPerSecStart, cbTransferPerSecStep));
AssertPtrReturn(pEpClass, VERR_INVALID_POINTER);
AssertPtrReturn(pcszBwMgr, VERR_INVALID_POINTER);
AssertReturn(*pcszBwMgr != '\0', VERR_INVALID_PARAMETER);
int rc;
PPDMACBWMGR pBwMgr = pdmacBwMgrFindById(pEpClass, pcszBwMgr);
if (!pBwMgr)
{
rc = MMR3HeapAllocZEx(pEpClass->pVM, MM_TAG_PDM_ASYNC_COMPLETION,
sizeof(PDMACBWMGR),
(void **)&pBwMgr);
if (RT_SUCCESS(rc))
{
pBwMgr->pszId = RTStrDup(pcszBwMgr);
if (pBwMgr->pszId)
{
pBwMgr->pEpClass = pEpClass;
pBwMgr->cRefs = 0;
/* Init I/O flow control. */
pBwMgr->cbTransferPerSecMax = cbTransferPerSecMax;
pBwMgr->cbTransferPerSecStart = cbTransferPerSecStart;
pBwMgr->cbTransferPerSecStep = cbTransferPerSecStep;
pBwMgr->cbTransferAllowed = pBwMgr->cbTransferPerSecStart;
pBwMgr->tsUpdatedLast = RTTimeSystemNanoTS();
pdmacBwMgrLink(pBwMgr);
rc = VINF_SUCCESS;
}
else
{
rc = VERR_NO_MEMORY;
MMR3HeapFree(pBwMgr);
}
}
}
else
rc = VERR_ALREADY_EXISTS;
LogFlowFunc(("returns rc=%Rrc\n", rc));
return rc;
}
DECLINLINE(void) pdmacBwMgrRef(PPDMACBWMGR pBwMgr)
{
ASMAtomicIncU32(&pBwMgr->cRefs);
}
DECLINLINE(void) pdmacBwMgrUnref(PPDMACBWMGR pBwMgr)
{
Assert(pBwMgr->cRefs > 0);
ASMAtomicDecU32(&pBwMgr->cRefs);
}
bool pdmacEpIsTransferAllowed(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, uint32_t cbTransfer, RTMSINTERVAL *pmsWhenNext)
{
bool fAllowed = true;
PPDMACBWMGR pBwMgr = ASMAtomicReadPtrT(&pEndpoint->pBwMgr, PPDMACBWMGR);
LogFlowFunc(("pEndpoint=%p pBwMgr=%p cbTransfer=%u\n", pEndpoint, pBwMgr, cbTransfer));
if (pBwMgr)
{
uint32_t cbOld = ASMAtomicSubU32(&pBwMgr->cbTransferAllowed, cbTransfer);
if (RT_LIKELY(cbOld >= cbTransfer))
fAllowed = true;
else
{
fAllowed = false;
/* We are out of resources Check if we can update again. */
uint64_t tsNow = RTTimeSystemNanoTS();
uint64_t tsUpdatedLast = ASMAtomicUoReadU64(&pBwMgr->tsUpdatedLast);
if (tsNow - tsUpdatedLast >= (1000*1000*1000))
{
if (ASMAtomicCmpXchgU64(&pBwMgr->tsUpdatedLast, tsNow, tsUpdatedLast))
{
if (pBwMgr->cbTransferPerSecStart < pBwMgr->cbTransferPerSecMax)
{
pBwMgr->cbTransferPerSecStart = RT_MIN(pBwMgr->cbTransferPerSecMax, pBwMgr->cbTransferPerSecStart + pBwMgr->cbTransferPerSecStep);
LogFlow(("AIOMgr: Increasing maximum bandwidth to %u bytes/sec\n", pBwMgr->cbTransferPerSecStart));
}
/* Update */
ASMAtomicWriteU32(&pBwMgr->cbTransferAllowed, pBwMgr->cbTransferPerSecStart - cbTransfer);
fAllowed = true;
LogFlow(("AIOMgr: Refreshed bandwidth\n"));
}
}
else
{
ASMAtomicAddU32(&pBwMgr->cbTransferAllowed, cbTransfer);
*pmsWhenNext = ((1000*1000*1000) - (tsNow - tsUpdatedLast)) / (1000*1000);
}
}
}
LogFlowFunc(("fAllowed=%RTbool\n", fAllowed));
return fAllowed;
}
void pdmR3AsyncCompletionCompleteTask(PPDMASYNCCOMPLETIONTASK pTask, int rc, bool fCallCompletionHandler)
{
LogFlow(("%s: pTask=%#p fCallCompletionHandler=%RTbool\n", __FUNCTION__, pTask, fCallCompletionHandler));
if (fCallCompletionHandler)
{
PPDMASYNCCOMPLETIONTEMPLATE pTemplate = pTask->pEndpoint->pTemplate;
switch (pTemplate->enmType)
{
case PDMASYNCCOMPLETIONTEMPLATETYPE_DEV:
pTemplate->u.Dev.pfnCompleted(pTemplate->u.Dev.pDevIns, pTask->pvUser, rc);
break;
case PDMASYNCCOMPLETIONTEMPLATETYPE_DRV:
pTemplate->u.Drv.pfnCompleted(pTemplate->u.Drv.pDrvIns, pTemplate->u.Drv.pvTemplateUser, pTask->pvUser, rc);
break;
case PDMASYNCCOMPLETIONTEMPLATETYPE_USB:
pTemplate->u.Usb.pfnCompleted(pTemplate->u.Usb.pUsbIns, pTask->pvUser, rc);
break;
case PDMASYNCCOMPLETIONTEMPLATETYPE_INTERNAL:
pTemplate->u.Int.pfnCompleted(pTemplate->pVM, pTask->pvUser, pTemplate->u.Int.pvUser, rc);
break;
default:
AssertMsgFailed(("Unknown template type!\n"));
}
}
pdmR3AsyncCompletionPutTask(pTask->pEndpoint, pTask);
}
/**
* Worker initializing a endpoint class.
*
* @returns VBox status code.
* @param pVM Pointer to the shared VM instance data.
* @param pEpClass Pointer to the endpoint class structure.
* @param pCfgHandle Pointer to the CFGM tree.
*/
int pdmR3AsyncCompletionEpClassInit(PVM pVM, PCPDMASYNCCOMPLETIONEPCLASSOPS pEpClassOps, PCFGMNODE pCfgHandle)
{
/* Validate input. */
AssertPtrReturn(pEpClassOps, VERR_INVALID_POINTER);
AssertReturn(pEpClassOps->u32Version == PDMAC_EPCLASS_OPS_VERSION, VERR_VERSION_MISMATCH);
AssertReturn(pEpClassOps->u32VersionEnd == PDMAC_EPCLASS_OPS_VERSION, VERR_VERSION_MISMATCH);
LogFlowFunc((": pVM=%p pEpClassOps=%p{%s}\n", pVM, pEpClassOps, pEpClassOps->pcszName));
/* Allocate global class data. */
PPDMASYNCCOMPLETIONEPCLASS pEndpointClass = NULL;
int rc = MMR3HeapAllocZEx(pVM, MM_TAG_PDM_ASYNC_COMPLETION,
pEpClassOps->cbEndpointClassGlobal,
(void **)&pEndpointClass);
if (RT_SUCCESS(rc))
{
/* Initialize common data. */
pEndpointClass->pVM = pVM;
pEndpointClass->pEndpointOps = pEpClassOps;
rc = RTCritSectInit(&pEndpointClass->CritSect);
if (RT_SUCCESS(rc))
{
PCFGMNODE pCfgNodeClass = CFGMR3GetChild(pCfgHandle, pEpClassOps->pcszName);
/* Create task cache */
rc = RTMemCacheCreate(&pEndpointClass->hMemCacheTasks, pEpClassOps->cbTask,
0, UINT32_MAX, NULL, NULL, NULL, 0);
if (RT_SUCCESS(rc))
{
/* Call the specific endpoint class initializer. */
rc = pEpClassOps->pfnInitialize(pEndpointClass, pCfgNodeClass);
if (RT_SUCCESS(rc))
{
/* Create all bandwidth groups for resource control. */
PCFGMNODE pCfgBwGrp = CFGMR3GetChild(pCfgNodeClass, "BwGroups");
if (pCfgBwGrp)
{
for (PCFGMNODE pCur = CFGMR3GetFirstChild(pCfgBwGrp); pCur; pCur = CFGMR3GetNextChild(pCur))
{
uint32_t cbMax, cbStart, cbStep;
size_t cchName = CFGMR3GetNameLen(pCur) + 1;
char *pszBwGrpId = (char *)RTMemAllocZ(cchName);
if (!pszBwGrpId)
{
rc = VERR_NO_MEMORY;
break;
}
rc = CFGMR3GetName(pCur, pszBwGrpId, cchName);
AssertRC(rc);
if (RT_SUCCESS(rc))
rc = CFGMR3QueryU32(pCur, "Max", &cbMax);
if (RT_SUCCESS(rc))
rc = CFGMR3QueryU32Def(pCur, "Start", &cbStart, cbMax);
if (RT_SUCCESS(rc))
rc = CFGMR3QueryU32Def(pCur, "Step", &cbStep, 0);
if (RT_SUCCESS(rc))
rc = pdmacAsyncCompletionBwMgrCreate(pEndpointClass, pszBwGrpId, cbMax, cbStart, cbStep);
RTMemFree(pszBwGrpId);
if (RT_FAILURE(rc))
break;
}
}
if (RT_SUCCESS(rc))
{
PUVM pUVM = pVM->pUVM;
AssertMsg(!pUVM->pdm.s.apAsyncCompletionEndpointClass[pEpClassOps->enmClassType],
("Endpoint class was already initialized\n"));
pUVM->pdm.s.apAsyncCompletionEndpointClass[pEpClassOps->enmClassType] = pEndpointClass;
LogFlowFunc((": Initialized endpoint class \"%s\" rc=%Rrc\n", pEpClassOps->pcszName, rc));
return VINF_SUCCESS;
}
}
RTMemCacheDestroy(pEndpointClass->hMemCacheTasks);
}
RTCritSectDelete(&pEndpointClass->CritSect);
}
MMR3HeapFree(pEndpointClass);
}
LogFlowFunc((": Failed to initialize endpoint class rc=%Rrc\n", rc));
return rc;
}
/**
* Worker terminating all endpoint classes.
*
* @returns nothing
* @param pEndpointClass Pointer to the endpoint class to terminate.
*
* @remarks This method ensures that any still open endpoint is closed.
*/
static void pdmR3AsyncCompletionEpClassTerminate(PPDMASYNCCOMPLETIONEPCLASS pEndpointClass)
{
PVM pVM = pEndpointClass->pVM;
/* Close all still open endpoints. */
while (pEndpointClass->pEndpointsHead)
PDMR3AsyncCompletionEpClose(pEndpointClass->pEndpointsHead);
/* Destroy the bandwidth managers. */
PPDMACBWMGR pBwMgr = pEndpointClass->pBwMgrsHead;
while (pBwMgr)
{
PPDMACBWMGR pFree = pBwMgr;
pBwMgr = pBwMgr->pNext;
MMR3HeapFree(pFree);
}
/* Call the termination callback of the class. */
pEndpointClass->pEndpointOps->pfnTerminate(pEndpointClass);
RTMemCacheDestroy(pEndpointClass->hMemCacheTasks);
RTCritSectDelete(&pEndpointClass->CritSect);
/* Free the memory of the class finally and clear the entry in the class array. */
pVM->pUVM->pdm.s.apAsyncCompletionEndpointClass[pEndpointClass->pEndpointOps->enmClassType] = NULL;
MMR3HeapFree(pEndpointClass);
}
/**
* Initialize the async completion manager.
*
* @returns VBox status code
* @param pVM Pointer to the VM.
*/
int pdmR3AsyncCompletionInit(PVM pVM)
{
LogFlowFunc((": pVM=%p\n", pVM));
VM_ASSERT_EMT(pVM);
PCFGMNODE pCfgRoot = CFGMR3GetRoot(pVM);
PCFGMNODE pCfgAsyncCompletion = CFGMR3GetChild(CFGMR3GetChild(pCfgRoot, "PDM"), "AsyncCompletion");
int rc = pdmR3AsyncCompletionEpClassInit(pVM, &g_PDMAsyncCompletionEndpointClassFile, pCfgAsyncCompletion);
LogFlowFunc((": pVM=%p rc=%Rrc\n", pVM, rc));
return rc;
}
/**
* Terminates the async completion manager.
*
* @returns VBox status code
* @param pVM Pointer to the VM.
*/
int pdmR3AsyncCompletionTerm(PVM pVM)
{
LogFlowFunc((": pVM=%p\n", pVM));
PUVM pUVM = pVM->pUVM;
for (size_t i = 0; i < RT_ELEMENTS(pUVM->pdm.s.apAsyncCompletionEndpointClass); i++)
if (pUVM->pdm.s.apAsyncCompletionEndpointClass[i])
pdmR3AsyncCompletionEpClassTerminate(pUVM->pdm.s.apAsyncCompletionEndpointClass[i]);
return VINF_SUCCESS;
}
/**
* Resume worker for the async completion manager.
*
* @returns nothing.
* @param pVM Pointer to the VM.
*/
void pdmR3AsyncCompletionResume(PVM pVM)
{
LogFlowFunc((": pVM=%p\n", pVM));
PUVM pUVM = pVM->pUVM;
/* Log the bandwidth groups and all assigned endpoints. */
for (size_t i = 0; i < RT_ELEMENTS(pUVM->pdm.s.apAsyncCompletionEndpointClass); i++)
if (pUVM->pdm.s.apAsyncCompletionEndpointClass[i])
{
PPDMASYNCCOMPLETIONEPCLASS pEpClass = pUVM->pdm.s.apAsyncCompletionEndpointClass[i];
PPDMACBWMGR pBwMgr = pEpClass->pBwMgrsHead;
PPDMASYNCCOMPLETIONENDPOINT pEp;
if (pBwMgr)
LogRel(("AIOMgr: Bandwidth groups for class '%s'\n", i == PDMASYNCCOMPLETIONEPCLASSTYPE_FILE
? "File" : "<Unknown>"));
while (pBwMgr)
{
LogRel(("AIOMgr: Id: %s\n", pBwMgr->pszId));
LogRel(("AIOMgr: Max: %u B/s\n", pBwMgr->cbTransferPerSecMax));
LogRel(("AIOMgr: Start: %u B/s\n", pBwMgr->cbTransferPerSecStart));
LogRel(("AIOMgr: Step: %u B/s\n", pBwMgr->cbTransferPerSecStep));
LogRel(("AIOMgr: Endpoints:\n"));
pEp = pEpClass->pEndpointsHead;
while (pEp)
{
if (pEp->pBwMgr == pBwMgr)
LogRel(("AIOMgr: %s\n", pEp->pszUri));
pEp = pEp->pNext;
}
pBwMgr = pBwMgr->pNext;
}
/* Print all endpoints without assigned bandwidth groups. */
pEp = pEpClass->pEndpointsHead;
if (pEp)
LogRel(("AIOMgr: Endpoints without assigned bandwidth groups:\n"));
while (pEp)
{
if (!pEp->pBwMgr)
LogRel(("AIOMgr: %s\n", pEp->pszUri));
pEp = pEp->pNext;
}
}
}
/**
* Tries to get a free task from the endpoint or class cache
* allocating the task if it fails.
*
* @returns Pointer to a new and initialized task or NULL
* @param pEndpoint The endpoint the task is for.
* @param pvUser Opaque user data for the task.
*/
static PPDMASYNCCOMPLETIONTASK pdmR3AsyncCompletionGetTask(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, void *pvUser)
{
PPDMASYNCCOMPLETIONEPCLASS pEndpointClass = pEndpoint->pEpClass;
PPDMASYNCCOMPLETIONTASK pTask = (PPDMASYNCCOMPLETIONTASK)RTMemCacheAlloc(pEndpointClass->hMemCacheTasks);
if (RT_LIKELY(pTask))
{
/* Initialize common parts. */
pTask->pvUser = pvUser;
pTask->pEndpoint = pEndpoint;
/* Clear list pointers for safety. */
pTask->pPrev = NULL;
pTask->pNext = NULL;
pTask->tsNsStart = RTTimeNanoTS();
#ifdef VBOX_WITH_STATISTICS
STAM_COUNTER_INC(&pEndpoint->StatIoOpsStarted);
#endif
}
return pTask;
}
/**
* Puts a task in one of the caches.
*
* @returns nothing.
* @param pEndpoint The endpoint the task belongs to.
* @param pTask The task to cache.
*/
static void pdmR3AsyncCompletionPutTask(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, PPDMASYNCCOMPLETIONTASK pTask)
{
PPDMASYNCCOMPLETIONEPCLASS pEndpointClass = pEndpoint->pEpClass;
uint64_t cNsRun = RTTimeNanoTS() - pTask->tsNsStart;
if (RT_UNLIKELY(cNsRun >= RT_NS_10SEC))
LogRel(("AsyncCompletion: Task %#p completed after %llu seconds\n", pTask, cNsRun / RT_NS_1SEC));
#ifdef VBOX_WITH_STATISTICS
PSTAMCOUNTER pStatCounter;
if (cNsRun < RT_NS_1US)
pStatCounter = &pEndpoint->StatTaskRunTimesNs[cNsRun / (RT_NS_1US / 10)];
else if (cNsRun < RT_NS_1MS)
pStatCounter = &pEndpoint->StatTaskRunTimesUs[cNsRun / (RT_NS_1MS / 10)];
else if (cNsRun < RT_NS_1SEC)
pStatCounter = &pEndpoint->StatTaskRunTimesMs[cNsRun / (RT_NS_1SEC / 10)];
else if (cNsRun < RT_NS_1SEC_64*100)
pStatCounter = &pEndpoint->StatTaskRunTimesSec[cNsRun / (RT_NS_1SEC_64*100 / 10)];
else
pStatCounter = &pEndpoint->StatTaskRunOver100Sec;
STAM_COUNTER_INC(pStatCounter);
STAM_COUNTER_INC(&pEndpoint->StatIoOpsCompleted);
pEndpoint->cIoOpsCompleted++;
uint64_t tsMsCur = RTTimeMilliTS();
uint64_t tsInterval = tsMsCur - pEndpoint->tsIntervalStartMs;
if (tsInterval >= 1000)
{
pEndpoint->StatIoOpsPerSec.c = pEndpoint->cIoOpsCompleted / (tsInterval / 1000);
pEndpoint->tsIntervalStartMs = tsMsCur;
pEndpoint->cIoOpsCompleted = 0;
}
#endif /* VBOX_WITH_STATISTICS */
RTMemCacheFree(pEndpointClass->hMemCacheTasks, pTask);
}
static PPDMASYNCCOMPLETIONENDPOINT pdmR3AsyncCompletionFindEndpointWithUri(PPDMASYNCCOMPLETIONEPCLASS pEndpointClass,
const char *pszUri)
{
PPDMASYNCCOMPLETIONENDPOINT pEndpoint = pEndpointClass->pEndpointsHead;
while (pEndpoint)
{
if (!RTStrCmp(pEndpoint->pszUri, pszUri))
return pEndpoint;
pEndpoint = pEndpoint->pNext;
}
return NULL;
}
VMMR3DECL(int) PDMR3AsyncCompletionEpCreateForFile(PPPDMASYNCCOMPLETIONENDPOINT ppEndpoint,
const char *pszFilename, uint32_t fFlags,
PPDMASYNCCOMPLETIONTEMPLATE pTemplate)
{
LogFlowFunc((": ppEndpoint=%p pszFilename=%p{%s} fFlags=%u pTemplate=%p\n",
ppEndpoint, pszFilename, pszFilename, fFlags, pTemplate));
/* Sanity checks. */
AssertPtrReturn(ppEndpoint, VERR_INVALID_POINTER);
AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
AssertPtrReturn(pTemplate, VERR_INVALID_POINTER);
/* Check that the flags are valid. */
AssertReturn(((~(PDMACEP_FILE_FLAGS_READ_ONLY | PDMACEP_FILE_FLAGS_DONT_LOCK | PDMACEP_FILE_FLAGS_HOST_CACHE_ENABLED) & fFlags) == 0),
VERR_INVALID_PARAMETER);
PVM pVM = pTemplate->pVM;
PUVM pUVM = pVM->pUVM;
PPDMASYNCCOMPLETIONEPCLASS pEndpointClass = pUVM->pdm.s.apAsyncCompletionEndpointClass[PDMASYNCCOMPLETIONEPCLASSTYPE_FILE];
PPDMASYNCCOMPLETIONENDPOINT pEndpoint = NULL;
AssertMsg(pEndpointClass, ("File endpoint class was not initialized\n"));
/* Search for a already opened endpoint for this file. */
pEndpoint = pdmR3AsyncCompletionFindEndpointWithUri(pEndpointClass, pszFilename);
if (pEndpoint)
{
/* Endpoint found. */
pEndpoint->cUsers++;
*ppEndpoint = pEndpoint;
return VINF_SUCCESS;
}
/* Create an endpoint. */
int rc = MMR3HeapAllocZEx(pVM, MM_TAG_PDM_ASYNC_COMPLETION,
pEndpointClass->pEndpointOps->cbEndpoint,
(void **)&pEndpoint);
if (RT_SUCCESS(rc))
{
/* Initialize common parts. */
pEndpoint->pNext = NULL;
pEndpoint->pPrev = NULL;
pEndpoint->pEpClass = pEndpointClass;
pEndpoint->pTemplate = pTemplate;
pEndpoint->pszUri = RTStrDup(pszFilename);
pEndpoint->cUsers = 1;
pEndpoint->pBwMgr = NULL;
if ( pEndpoint->pszUri
&& RT_SUCCESS(rc))
{
/* Call the initializer for the endpoint. */
rc = pEndpointClass->pEndpointOps->pfnEpInitialize(pEndpoint, pszFilename, fFlags);
if (RT_SUCCESS(rc))
{
/* Link it into the list of endpoints. */
rc = RTCritSectEnter(&pEndpointClass->CritSect);
AssertMsg(RT_SUCCESS(rc), ("Failed to enter critical section rc=%Rrc\n", rc));
pEndpoint->pNext = pEndpointClass->pEndpointsHead;
if (pEndpointClass->pEndpointsHead)
pEndpointClass->pEndpointsHead->pPrev = pEndpoint;
pEndpointClass->pEndpointsHead = pEndpoint;
pEndpointClass->cEndpoints++;
rc = RTCritSectLeave(&pEndpointClass->CritSect);
AssertMsg(RT_SUCCESS(rc), ("Failed to enter critical section rc=%Rrc\n", rc));
/* Reference the template. */
ASMAtomicIncU32(&pTemplate->cUsed);
#ifdef VBOX_WITH_STATISTICS
/* Init the statistics part */
for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesNs); i++)
{
rc = STAMR3RegisterF(pVM, &pEndpoint->StatTaskRunTimesNs[i], STAMTYPE_COUNTER,
STAMVISIBILITY_USED,
STAMUNIT_OCCURENCES,
"Nanosecond resolution runtime statistics",
"/PDM/AsyncCompletion/File/%s/TaskRun1Ns-%u-%u",
RTPathFilename(pEndpoint->pszUri),
i*100, i*100+100-1);
if (RT_FAILURE(rc))
break;
}
if (RT_SUCCESS(rc))
{
for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesUs); i++)
{
rc = STAMR3RegisterF(pVM, &pEndpoint->StatTaskRunTimesUs[i], STAMTYPE_COUNTER,
STAMVISIBILITY_USED,
STAMUNIT_OCCURENCES,
"Microsecond resolution runtime statistics",
"/PDM/AsyncCompletion/File/%s/TaskRun2MicroSec-%u-%u",
RTPathFilename(pEndpoint->pszUri),
i*100, i*100+100-1);
if (RT_FAILURE(rc))
break;
}
}
if (RT_SUCCESS(rc))
{
for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesMs); i++)
{
rc = STAMR3RegisterF(pVM, &pEndpoint->StatTaskRunTimesMs[i], STAMTYPE_COUNTER,
STAMVISIBILITY_USED,
STAMUNIT_OCCURENCES,
"Milliseconds resolution runtime statistics",
"/PDM/AsyncCompletion/File/%s/TaskRun3Ms-%u-%u",
RTPathFilename(pEndpoint->pszUri),
i*100, i*100+100-1);
if (RT_FAILURE(rc))
break;
}
}
if (RT_SUCCESS(rc))
{
for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesMs); i++)
{
rc = STAMR3RegisterF(pVM, &pEndpoint->StatTaskRunTimesSec[i], STAMTYPE_COUNTER,
STAMVISIBILITY_USED,
STAMUNIT_OCCURENCES,
"Second resolution runtime statistics",
"/PDM/AsyncCompletion/File/%s/TaskRun4Sec-%u-%u",
RTPathFilename(pEndpoint->pszUri),
i*10, i*10+10-1);
if (RT_FAILURE(rc))
break;
}
}
if (RT_SUCCESS(rc))
{
rc = STAMR3RegisterF(pVM, &pEndpoint->StatTaskRunOver100Sec, STAMTYPE_COUNTER,
STAMVISIBILITY_USED,
STAMUNIT_OCCURENCES,
"Tasks which ran more than 100sec",
"/PDM/AsyncCompletion/File/%s/TaskRunSecGreater100Sec",
RTPathFilename(pEndpoint->pszUri));
}
if (RT_SUCCESS(rc))
{
rc = STAMR3RegisterF(pVM, &pEndpoint->StatIoOpsPerSec, STAMTYPE_COUNTER,
STAMVISIBILITY_ALWAYS,
STAMUNIT_OCCURENCES,
"Processed I/O operations per second",
"/PDM/AsyncCompletion/File/%s/IoOpsPerSec",
RTPathFilename(pEndpoint->pszUri));
}
if (RT_SUCCESS(rc))
{
rc = STAMR3RegisterF(pVM, &pEndpoint->StatIoOpsStarted, STAMTYPE_COUNTER,
STAMVISIBILITY_ALWAYS,
STAMUNIT_OCCURENCES,
"Started I/O operations for this endpoint",
"/PDM/AsyncCompletion/File/%s/IoOpsStarted",
RTPathFilename(pEndpoint->pszUri));
}
if (RT_SUCCESS(rc))
{
rc = STAMR3RegisterF(pVM, &pEndpoint->StatIoOpsCompleted, STAMTYPE_COUNTER,
STAMVISIBILITY_ALWAYS,
STAMUNIT_OCCURENCES,
"Completed I/O operations for this endpoint",
"/PDM/AsyncCompletion/File/%s/IoOpsCompleted",
RTPathFilename(pEndpoint->pszUri));
}
/** @todo why bother maintaing rc when it's just ignored /
logged and not returned? */
pEndpoint->tsIntervalStartMs = RTTimeMilliTS();
#endif
*ppEndpoint = pEndpoint;
LogFlowFunc((": Created endpoint for %s: rc=%Rrc\n", pszFilename, rc));
return VINF_SUCCESS;
}
RTStrFree(pEndpoint->pszUri);
}
MMR3HeapFree(pEndpoint);
}
LogFlowFunc((": Creation of endpoint for %s failed: rc=%Rrc\n", pszFilename, rc));
return rc;
}
VMMR3DECL(void) PDMR3AsyncCompletionEpClose(PPDMASYNCCOMPLETIONENDPOINT pEndpoint)
{
LogFlowFunc((": pEndpoint=%p\n", pEndpoint));
/* Sanity checks. */
AssertReturnVoid(VALID_PTR(pEndpoint));
pEndpoint->cUsers--;
/* If the last user closed the endpoint we will free it. */
if (!pEndpoint->cUsers)
{
PPDMASYNCCOMPLETIONEPCLASS pEndpointClass = pEndpoint->pEpClass;
pEndpointClass->pEndpointOps->pfnEpClose(pEndpoint);
/* Drop reference from the template. */
ASMAtomicDecU32(&pEndpoint->pTemplate->cUsed);
/* Unlink the endpoint from the list. */
int rc = RTCritSectEnter(&pEndpointClass->CritSect);
AssertMsg(RT_SUCCESS(rc), ("Failed to enter critical section rc=%Rrc\n", rc));
PPDMASYNCCOMPLETIONENDPOINT pEndpointNext = pEndpoint->pNext;
PPDMASYNCCOMPLETIONENDPOINT pEndpointPrev = pEndpoint->pPrev;
if (pEndpointPrev)
pEndpointPrev->pNext = pEndpointNext;
else
pEndpointClass->pEndpointsHead = pEndpointNext;
if (pEndpointNext)
pEndpointNext->pPrev = pEndpointPrev;
pEndpointClass->cEndpoints--;
rc = RTCritSectLeave(&pEndpointClass->CritSect);
AssertMsg(RT_SUCCESS(rc), ("Failed to enter critical section rc=%Rrc\n", rc));
#ifdef VBOX_WITH_STATISTICS
/* Deregister the statistics part */
PVM pVM = pEndpointClass->pVM;
for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesNs); i++)
STAMR3Deregister(pVM, &pEndpoint->StatTaskRunTimesNs[i]);
for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesUs); i++)
STAMR3Deregister(pVM, &pEndpoint->StatTaskRunTimesUs[i]);
for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesMs); i++)
STAMR3Deregister(pVM, &pEndpoint->StatTaskRunTimesMs[i]);
for (unsigned i = 0; i < RT_ELEMENTS(pEndpoint->StatTaskRunTimesMs); i++)
STAMR3Deregister(pVM, &pEndpoint->StatTaskRunTimesSec[i]);
STAMR3Deregister(pVM, &pEndpoint->StatTaskRunOver100Sec);
STAMR3Deregister(pVM, &pEndpoint->StatIoOpsPerSec);
STAMR3Deregister(pVM, &pEndpoint->StatIoOpsStarted);
STAMR3Deregister(pVM, &pEndpoint->StatIoOpsCompleted);
#endif
RTStrFree(pEndpoint->pszUri);
MMR3HeapFree(pEndpoint);
}
}
VMMR3DECL(int) PDMR3AsyncCompletionEpRead(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, RTFOFF off,
PCRTSGSEG paSegments, unsigned cSegments,
size_t cbRead, void *pvUser,
PPPDMASYNCCOMPLETIONTASK ppTask)
{
AssertPtrReturn(pEndpoint, VERR_INVALID_POINTER);
AssertPtrReturn(paSegments, VERR_INVALID_POINTER);
AssertPtrReturn(ppTask, VERR_INVALID_POINTER);
AssertReturn(cSegments > 0, VERR_INVALID_PARAMETER);
AssertReturn(cbRead > 0, VERR_INVALID_PARAMETER);
AssertReturn(off >= 0, VERR_INVALID_PARAMETER);
PPDMASYNCCOMPLETIONTASK pTask;
pTask = pdmR3AsyncCompletionGetTask(pEndpoint, pvUser);
if (!pTask)
return VERR_NO_MEMORY;
int rc = pEndpoint->pEpClass->pEndpointOps->pfnEpRead(pTask, pEndpoint, off,
paSegments, cSegments, cbRead);
if (RT_SUCCESS(rc))
*ppTask = pTask;
else
pdmR3AsyncCompletionPutTask(pEndpoint, pTask);
return rc;
}
VMMR3DECL(int) PDMR3AsyncCompletionEpWrite(PPDMASYNCCOMPLETIONENDPOINT pEndpoint, RTFOFF off,
PCRTSGSEG paSegments, unsigned cSegments,
size_t cbWrite, void *pvUser,
PPPDMASYNCCOMPLETIONTASK ppTask)
{
AssertPtrReturn(pEndpoint, VERR_INVALID_POINTER);
AssertPtrReturn(paSegments, VERR_INVALID_POINTER);
AssertPtrReturn(ppTask, VERR_INVALID_POINTER);
AssertReturn(cSegments > 0, VERR_INVALID_PARAMETER);
AssertReturn(cbWrite > 0, VERR_INVALID_PARAMETER);
AssertReturn(off >= 0, VERR_INVALID_PARAMETER);
PPDMASYNCCOMPLETIONTASK pTask;
pTask = pdmR3AsyncCompletionGetTask(pEndpoint, pvUser);
if (!pTask)
return VERR_NO_MEMORY;
int rc = pEndpoint->pEpClass->pEndpointOps->pfnEpWrite(pTask, pEndpoint, off,
paSegments, cSegments, cbWrite);
if (RT_SUCCESS(rc))
{
*ppTask = pTask;
}
else
pdmR3AsyncCompletionPutTask(pEndpoint, pTask);
return rc;
}
VMMR3DECL(int) PDMR3AsyncCompletionEpFlush(PPDMASYNCCOMPLETIONENDPOINT pEndpoint,
void *pvUser,
PPPDMASYNCCOMPLETIONTASK ppTask)
{
AssertPtrReturn(pEndpoint, VERR_INVALID_POINTER);
AssertPtrReturn(ppTask, VERR_INVALID_POINTER);
PPDMASYNCCOMPLETIONTASK pTask;
pTask = pdmR3AsyncCompletionGetTask(pEndpoint, pvUser);
if (!pTask)
return VERR_NO_MEMORY;
int rc = pEndpoint->pEpClass->pEndpointOps->pfnEpFlush(pTask, pEndpoint);
if (RT_SUCCESS(rc))
*ppTask = pTask;
else
pdmR3AsyncCompletionPutTask(pEndpoint, pTask);
return rc;
}
VMMR3DECL(int) PDMR3AsyncCompletionEpGetSize(PPDMASYNCCOMPLETIONENDPOINT pEndpoint,
uint64_t *pcbSize)
{
AssertPtrReturn(pEndpoint, VERR_INVALID_POINTER);
AssertPtrReturn(pcbSize, VERR_INVALID_POINTER);
if (pEndpoint->pEpClass->pEndpointOps->pfnEpGetSize)
return pEndpoint->pEpClass->pEndpointOps->pfnEpGetSize(pEndpoint, pcbSize);
return VERR_NOT_SUPPORTED;
}
VMMR3DECL(int) PDMR3AsyncCompletionEpSetSize(PPDMASYNCCOMPLETIONENDPOINT pEndpoint,
uint64_t cbSize)
{
AssertPtrReturn(pEndpoint, VERR_INVALID_POINTER);
if (pEndpoint->pEpClass->pEndpointOps->pfnEpSetSize)
return pEndpoint->pEpClass->pEndpointOps->pfnEpSetSize(pEndpoint, cbSize);
return VERR_NOT_SUPPORTED;
}
VMMR3DECL(int) PDMR3AsyncCompletionEpSetBwMgr(PPDMASYNCCOMPLETIONENDPOINT pEndpoint,
const char *pcszBwMgr)
{
AssertPtrReturn(pEndpoint, VERR_INVALID_POINTER);
PPDMACBWMGR pBwMgrOld = NULL;
PPDMACBWMGR pBwMgrNew = NULL;
int rc = VINF_SUCCESS;
if (pcszBwMgr)
{
pBwMgrNew = pdmacBwMgrFindById(pEndpoint->pEpClass, pcszBwMgr);
if (pBwMgrNew)
pdmacBwMgrRef(pBwMgrNew);
else
rc = VERR_NOT_FOUND;
}
if (RT_SUCCESS(rc))
{
pBwMgrOld = ASMAtomicXchgPtrT(&pEndpoint->pBwMgr, pBwMgrNew, PPDMACBWMGR);
if (pBwMgrOld)
pdmacBwMgrUnref(pBwMgrOld);
}
return rc;
}
VMMR3DECL(int) PDMR3AsyncCompletionTaskCancel(PPDMASYNCCOMPLETIONTASK pTask)
{
NOREF(pTask);
return VERR_NOT_IMPLEMENTED;
}
VMMR3DECL(int) PDMR3AsyncCompletionBwMgrSetMaxForFile(PVM pVM, const char *pcszBwMgr, uint32_t cbMaxNew)
{
AssertPtrReturn(pVM, VERR_INVALID_POINTER);
AssertPtrReturn(pcszBwMgr, VERR_INVALID_POINTER);
int rc = VINF_SUCCESS;
PPDMASYNCCOMPLETIONEPCLASS pEpClass = pVM->pUVM->pdm.s.apAsyncCompletionEndpointClass[PDMASYNCCOMPLETIONEPCLASSTYPE_FILE];
PPDMACBWMGR pBwMgr = pdmacBwMgrFindById(pEpClass, pcszBwMgr);
if (pBwMgr)
{
/*
* Set the new value for the start and max value to let the manager pick up
* the new limit immediately.
*/
ASMAtomicWriteU32(&pBwMgr->cbTransferPerSecMax, cbMaxNew);
ASMAtomicWriteU32(&pBwMgr->cbTransferPerSecStart, cbMaxNew);
}
else
rc = VERR_NOT_FOUND;
return rc;
}
| VirtualMonitor/VirtualMonitor | src/VBox/VMM/VMMR3/PDMAsyncCompletion.cpp | C++ | gpl-2.0 | 54,355 |
namespace :project_state do
resources :summary, only: [:index]
resources :users, only: [:show]
resource :user, only: [:show]
resources :state, only: [:show]
resources :project_state_reports, only: [:index, :show, :update]
resources :bank_holidays, only: [:index]
get 'configure', action: :edit
post 'configure', action: :edit
end
| crukci-bioinformatics/process_tracker_plugin | config/routes.rb | Ruby | gpl-2.0 | 347 |
/*============================================================================*/
/*! \file reader_xtc.hpp
* \author Tiago LOBATO GIMENES (tlgimenes@gmail.com)
* \date 2015-03-30 18:49
*
* \brief .xtc file reader
*
* This file contains the implementation of a class for reading .xtc files
* with a trajectory list
* */
/*============================================================================*/
///////////////////////////////////////////////////////////////////////////////
#ifndef READER_XTC_HPP
#define READER_XTC_HPP
///////////////////////////////////////////////////////////////////////////////
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <boost/filesystem.hpp>
#include "error.hpp"
#include "xdrfile/xdrfile.h"
#include "xdrfile/xdrfile_xtc.h"
///////////////////////////////////////////////////////////////////////////////
/*! \brief Maximun file name lenght */
#define MAX_FILE_NAME_LENGTH 128
///////////////////////////////////////////////////////////////////////////////
namespace bfs = boost::filesystem;
///////////////////////////////////////////////////////////////////////////////
/*! \brief Class for reading trajlist and .xtc files */
class reader_xtc
{
public:
/*! \brief Reads all trajectories specified in the trajlist file.
*
* A trajlist file can contains the relative paths to the .xtc files or name of
* files that contains relative paths to the .xtc files. The absolute
* path is always done in the following way : path = home/trajlist
* */
static inline void read_list(const std::string& home, const std::string& trajlist,
std::vector<float>& data, int& n_atoms);
protected:
/*! \brief Reads a trajectory file.
*
* It can be *.xtc or any other file defined in _supported_ext vector
* and appends the new trajectories in the data vector
* */
static inline void read_trajfile(const std::string& trajfile, std::vector<float>&
data, int& n_atoms, int& n_samples);
/*! \brief finds *.xtc files from trajlist
*
* Given a trajlist path, this function will recursively try to find
* the (*.xtc) files and insert it on the framefile_list. The complete
* path for the file must be given by home/trajlist
* */
static inline void get_framefile_list(std::vector<std::string>& framefile_list,
const std::string& home, const std::string& trajlist);
/*! \brief Checks if the extension of file "file_name" is supported or not
* by this class
*
* \return true if file extension is supported, false otherwise
* */
static inline bool is_ext_supported(const std::string& file_name);
private:
static std::vector<std::string> _supported_ext; /*! list of supported extensions */
};
///////////////////////////////////////////////////////////////////////////////
std::vector<std::string> reader_xtc::_supported_ext = {".xtc"};
///////////////////////////////////////////////////////////////////////////////
inline void reader_xtc::read_list(const std::string& home, const std::string& trajlist_path,
std::vector<float>& data, int& n_atoms)
{
std::vector<std::string> trajlist;
int n_samples = 0;
// Checks if file exists
if(!bfs::is_regular_file(home+trajlist_path)) FATAL_ERROR(home+trajlist_path+": File not found :(");
reader_xtc::get_framefile_list(trajlist, home, trajlist_path);
data.clear(); // clears data
// Number of atoms in the first file is number of atoms in all the files
if(trajlist.size() <= 0) FATAL_ERROR("File list empty :(");
read_xtc_natoms((char*)trajlist[0].c_str(), &n_atoms);
// Foreach file in trajlist
for(std::string trajfile : trajlist)
{
DBG_MESSAGE("Reading file: " + trajfile + " ... "); // Debug Message
reader_xtc::read_trajfile(trajfile, data, n_atoms, n_samples);
DBG_MESSAGE(std::to_string(n_samples) + " frames found\n"); // Debug Message
}
}
///////////////////////////////////////////////////////////////////////////////
inline bool reader_xtc::is_ext_supported(const std::string& str)
{
for(std::string l : reader_xtc::_supported_ext)
{
if(!str.compare(str.size()-4, 4, l))
return true;
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
inline void reader_xtc::get_framefile_list(std::vector<std::string>& trajlist,
const std::string& home, const std::string& trajlinks_path)
{
std::stringstream trajlinks;
std::string sub_traj;
// Recursion base, when file is a complete path
if(reader_xtc::is_ext_supported(trajlinks_path))
trajlist.push_back(home + trajlinks_path);
// when file is a link to a file
else {
// Gets contents of the file
trajlinks << std::ifstream(home + trajlinks_path, std::ios_base::in).rdbuf();
trajlinks >> sub_traj;
while(trajlinks && !trajlinks.eof() && sub_traj.size() > 0) // Foreach link in the file
{
if(bfs::is_regular_file(home+sub_traj)) // if file is openable and is a link to other files
reader_xtc::get_framefile_list(trajlist, home, sub_traj);
else if(bfs::is_regular_file(home+sub_traj+".xtc")) // if file without xtc extension
trajlist.push_back(home+sub_traj+".xtc");
else // default file name
trajlist.push_back(home+sub_traj+"/frame0.xtc");
trajlinks >> sub_traj; // gets new file/link
}
}
}
///////////////////////////////////////////////////////////////////////////////
inline void reader_xtc::read_trajfile(const std::string& trajfile,
std::vector<float> &data, int& n_atoms, int& n_samples)
{
int step;
float time, prec;
matrix box;
rvec* tmp = new rvec[n_atoms];
n_samples = 0;
// Opens trajfile
XDRFILE *xdr_file = xdrfile_open(trajfile.c_str(), "r"); // opens file
// Reads each frame
while (exdrOK == read_xtc(xdr_file, n_atoms, &step, &time, box, tmp, &prec)) {
for(int i=0; i < n_atoms; i++) {
data.push_back(tmp[i][0]);
data.push_back(tmp[i][1]);
data.push_back(tmp[i][2]);
}
n_samples++;
}
// Closes trajfile
xdrfile_close(xdr_file);
// Deletes allocated memory
delete []tmp;
}
///////////////////////////////////////////////////////////////////////////////
#endif /* !READER_XTC_HPP */
///////////////////////////////////////////////////////////////////////////////
| tlgimenes/CUDADClusterer | utils/reader_xtc.hpp | C++ | gpl-2.0 | 6,763 |
/*
* Copyright 2009 TauNova (http://taunova.com). All rights reserved.
*
* This file is subject to the terms and conditions defined in
* file 'LICENSE.txt', which is part of this source code package.
*/
package com.taunova.ui.light.component;
import java.awt.Graphics;
/**
* Description
*
* @version 1.0, 12/07/09
* @author Renat Gilmanov
* @author Viktor Zakalyuzhnyy
*/
public class LightLabel extends AbstractTextComponent {
public LightLabel(String text) {
super(text);
}
@Override
public void paint(Graphics g) {
g.setColor(background);
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
g.setColor(textColor);
g.drawString(text, bounds.x+10, bounds.y+15);
}
} | RenatGilmanov/tau-ui | src/java/com/taunova/ui/light/component/LightLabel.java | Java | gpl-2.0 | 791 |
<?php
namespace Drupal\Tests\conditional_fields\FunctionalJavascript;
use Drupal\language\Entity\ContentLanguageSettings;
use Drupal\Tests\conditional_fields\FunctionalJavascript\TestCases\ConditionalFieldValueInterface;
/**
* Test Conditional Fields Language Select Plugin.
*
* @group conditional_fields
*/
class ConditionalFieldLanguageSelectTest extends ConditionalFieldTestBase implements ConditionalFieldValueInterface {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'conditional_fields',
'language',
'node',
'options',
];
/**
* {@inheritdoc}
*/
protected $screenshotPath = 'sites/simpletest/conditional_fields/language_select/';
/**
* The field name used in the test.
*
* @var string
*/
protected $fieldName = 'langcode';
/**
* Jquery selector of field in a document.
*
* @var string
*/
protected $fieldSelector;
/**
* The field to use in this test.
*
* @var \Drupal\field\Entity\FieldConfig
*/
protected $field;
/**
* The default language code.
*
* @var string
*/
protected $defaultLanguage;
/**
* An array with Not specified and Not applicable language codes.
*
* @var array
*/
protected $langcodes = ['und', 'zxx'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->fieldSelector = "[name=\"{$this->fieldName}[0][value]\"]";
// Get the default language which will trigger the dependency.
$this->defaultLanguage = \Drupal::languageManager()->getCurrentLanguage()->getId();
// Enable language selector on node creation page.
ContentLanguageSettings::loadByEntityTypeBundle('node', 'article')
->setLanguageAlterable(TRUE)
->setDefaultLangcode($this->defaultLanguage)
->save();
}
/**
* {@inheritdoc}
*/
public function testVisibleValueWidget() {
$this->baseTestSteps();
// Visit a ConditionalFields configuration page for Content bundles.
$this->createCondition('body', $this->fieldName, 'visible', 'value');
$this->createScreenshot($this->screenshotPath . '01-language-select-add-filed-conditions.png');
// Set up conditions.
$data = [
'condition' => 'value',
'values_set' => CONDITIONAL_FIELDS_DEPENDENCY_VALUES_WIDGET,
$this->fieldName . '[0][value]' => $this->defaultLanguage,
'grouping' => 'AND',
'state' => 'visible',
'effect' => 'show',
];
$this->submitForm( $data, 'Save settings');
$this->createScreenshot($this->screenshotPath . '02-language-select-post-add-list-options-filed-conditions.png');
// Check if that configuration is saved.
$this->drupalGet('admin/structure/types/manage/article/conditionals');
$this->createScreenshot($this->screenshotPath . '03-language-select-submit-list-options-filed-conditions.png');
$this->assertSession()->pageTextContains('body ' . $this->fieldName . ' visible value');
// Visit Article Add form to check that conditions are applied.
$this->drupalGet('node/add/article');
// Check that the field Body is visible.
$this->createScreenshot($this->screenshotPath . '04-language-select-body-visible-when-controlled-field-has-default-value.png');
$this->waitUntilVisible('.field--name-body', 50, '01. Article Body field is not visible');
// Change a select value set that should not show the body.
$this->changeField($this->fieldSelector, $this->langcodes[0]);
$this->createScreenshot($this->screenshotPath . '05-language-select-body-invisible-when-controlled-field-has-wrong-value.png');
$this->waitUntilHidden('.field--name-body', 50, '02. Article Body field is visible');
// Change a select value set to show the body.
$this->changeField($this->fieldSelector, $this->defaultLanguage);
$this->createScreenshot($this->screenshotPath . '06-language-select-body-visible-when-controlled-field-has-value.png');
$this->waitUntilVisible('.field--name-body', 50, '03. Article Body field is not visible');
// Change a select value set to hide the body again.
$this->changeField($this->fieldSelector, $this->langcodes[1]);
$this->createScreenshot($this->screenshotPath . '07-language-select-body-invisible-when-controlled-field-has-wrong-value-again.png');
$this->waitUntilHidden('.field--name-body', 50, '04. Article Body field is visible');
}
/**
* {@inheritdoc}
*/
public function testVisibleValueRegExp() {
$this->baseTestSteps();
// Visit a ConditionalFields configuration page for Content bundles.
$this->createCondition('body', $this->fieldName, 'visible', 'value');
$this->createScreenshot($this->screenshotPath . '01-language-select-add-filed-conditions.png');
// Set up conditions.
$data = [
'condition' => 'value',
'values_set' => CONDITIONAL_FIELDS_DEPENDENCY_VALUES_REGEX,
"regex" => '^'. $this->langcodes[0] . '$',
'grouping' => 'AND',
'state' => 'visible',
'effect' => 'show',
];
$this->submitForm( $data, 'Save settings');
$this->createScreenshot($this->screenshotPath . '02-language-select-post-add-list-options-filed-conditions.png');
// Check if that configuration is saved.
$this->drupalGet('admin/structure/types/manage/article/conditionals');
$this->createScreenshot($this->screenshotPath . '03-language-select-submit-list-options-filed-conditions.png');
$this->assertSession()->pageTextContains('body ' . $this->fieldName . ' visible value');
// Visit Article Add form to check that conditions are applied.
$this->drupalGet('node/add/article');
// Check that the field Body is visible.
$this->createScreenshot($this->screenshotPath . '04-language-select-body-visible-when-controlled-field-has-default-value.png');
$this->waitUntilHidden('.field--name-body', 50, '01. Article Body field is visible');
// Change a select value set that should not show the body.
$this->changeField($this->fieldSelector, $this->langcodes[0]);
$this->createScreenshot($this->screenshotPath . '05-language-select-body-invisible-when-controlled-field-has-wrong-value.png');
$this->waitUntilVisible('.field--name-body', 50, '02. Article Body field is not visible');
// Change a select value set to show the body.
$this->changeField($this->fieldSelector, $this->defaultLanguage);
$this->createScreenshot($this->screenshotPath . '06-language-select-body-visible-when-controlled-field-has-value.png');
$this->waitUntilHidden('.field--name-body', 50, '03. Article Body field is visible');
// Change a select value set to hide the body again.
$this->changeField($this->fieldSelector, $this->langcodes[1]);
$this->createScreenshot($this->screenshotPath . '07-language-select-body-invisible-when-controlled-field-has-wrong-value-again.png');
$this->waitUntilHidden('.field--name-body', 50, '04. Article Body field is visible');
}
/**
* {@inheritdoc}
*/
public function testVisibleValueAnd() {
$this->baseTestSteps();
// Visit a ConditionalFields configuration page for Content bundles.
$this->createCondition('body', $this->fieldName, 'visible', 'value');
$this->createScreenshot($this->screenshotPath . '01-language-select-add-filed-conditions.png');
// Set up conditions.
$data = [
'condition' => 'value',
'values_set' => CONDITIONAL_FIELDS_DEPENDENCY_VALUES_AND,
"values" => implode( "\r\n", $this->langcodes ),
'grouping' => 'AND',
'state' => 'visible',
'effect' => 'show',
];
$this->submitForm( $data, 'Save settings');
$this->createScreenshot($this->screenshotPath . '02-language-select-post-add-list-options-filed-conditions.png');
// Check if that configuration is saved.
$this->drupalGet('admin/structure/types/manage/article/conditionals');
$this->createScreenshot($this->screenshotPath . '03-language-select-submit-list-options-filed-conditions.png');
$this->assertSession()->pageTextContains('body ' . $this->fieldName . ' visible value');
// Visit Article Add form to check that conditions are applied.
$this->drupalGet('node/add/article');
// Check that the field Body is visible.
$this->createScreenshot($this->screenshotPath . '04-language-select-body-visible-when-controlled-field-has-default-value.png');
$this->waitUntilHidden('.field--name-body', 50, '01. Article Body field is visible');
// Change a select value set that should not show the body.
$this->changeField($this->fieldSelector, $this->langcodes[0]);
$this->createScreenshot($this->screenshotPath . '05-language-select-body-invisible-when-controlled-field-has-wrong-value.png');
$this->waitUntilHidden('.field--name-body', 50, '02. Article Body field is visible');
// Change a select value set to show the body.
$this->changeField($this->fieldSelector, $this->defaultLanguage);
$this->createScreenshot($this->screenshotPath . '06-language-select-body-visible-when-controlled-field-has-value.png');
$this->waitUntilHidden('.field--name-body', 50, '03. Article Body field is visible');
// Change a select value set to hide the body again.
$this->changeField($this->fieldSelector, $this->langcodes[1]);
$this->createScreenshot($this->screenshotPath . '07-language-select-body-invisible-when-controlled-field-has-wrong-value-again.png');
$this->waitUntilHidden('.field--name-body', 50, '04. Article Body field is visible');
}
/**
* {@inheritdoc}
*/
public function testVisibleValueOr() {
$this->baseTestSteps();
// Visit a ConditionalFields configuration page for Content bundles.
$this->createCondition('body', $this->fieldName, 'visible', 'value');
$this->createScreenshot($this->screenshotPath . '01-language-select-add-filed-conditions.png');
// Set up conditions.
$data = [
'condition' => 'value',
'values_set' => CONDITIONAL_FIELDS_DEPENDENCY_VALUES_OR,
"values" => implode( "\r\n", $this->langcodes ),
'grouping' => 'AND',
'state' => 'visible',
'effect' => 'show',
];
$this->submitForm( $data, 'Save settings');
$this->createScreenshot($this->screenshotPath . '02-language-select-post-add-list-options-filed-conditions.png');
// Check if that configuration is saved.
$this->drupalGet('admin/structure/types/manage/article/conditionals');
$this->createScreenshot($this->screenshotPath . '03-language-select-submit-list-options-filed-conditions.png');
$this->assertSession()->pageTextContains('body ' . $this->fieldName . ' visible value');
// Visit Article Add form to check that conditions are applied.
$this->drupalGet('node/add/article');
// Check that the field Body is visible.
$this->createScreenshot($this->screenshotPath . '04-language-select-body-visible-when-controlled-field-has-default-value.png');
$this->waitUntilHidden('.field--name-body', 50, '01. Article Body field is visible');
// Change a select value set that should not show the body.
$this->changeField($this->fieldSelector, $this->langcodes[0]);
$this->createScreenshot($this->screenshotPath . '05-language-select-body-invisible-when-controlled-field-has-wrong-value.png');
$this->waitUntilVisible('.field--name-body', 50, '02. Article Body field is not visible');
// Change a select value set to show the body.
$this->changeField($this->fieldSelector, $this->defaultLanguage);
$this->createScreenshot($this->screenshotPath . '06-language-select-body-visible-when-controlled-field-has-value.png');
$this->waitUntilHidden('.field--name-body', 50, '03. Article Body field is visible');
// Change a select value set to hide the body again.
$this->changeField($this->fieldSelector, $this->langcodes[1]);
$this->createScreenshot($this->screenshotPath . '07-language-select-body-invisible-when-controlled-field-has-wrong-value-again.png');
$this->waitUntilVisible('.field--name-body', 50, '04. Article Body field is not visible');
}
/**
* {@inheritdoc}
*/
public function testVisibleValueNot() {
$this->baseTestSteps();
// Visit a ConditionalFields configuration page for Content bundles.
$this->createCondition('body', $this->fieldName, 'visible', 'value');
$this->createScreenshot($this->screenshotPath . '01-language-select-add-filed-conditions.png');
// Set up conditions.
$data = [
'condition' => 'value',
'values_set' => CONDITIONAL_FIELDS_DEPENDENCY_VALUES_NOT,
"values" => implode( "\r\n", $this->langcodes ),
'grouping' => 'AND',
'state' => 'visible',
'effect' => 'show',
];
$this->submitForm( $data, 'Save settings');
$this->createScreenshot($this->screenshotPath . '02-language-select-post-add-list-options-filed-conditions.png');
// Check if that configuration is saved.
$this->drupalGet('admin/structure/types/manage/article/conditionals');
$this->createScreenshot($this->screenshotPath . '03-language-select-submit-list-options-filed-conditions.png');
$this->assertSession()->pageTextContains('body ' . $this->fieldName . ' visible value');
// Visit Article Add form to check that conditions are applied.
$this->drupalGet('node/add/article');
// Check that the field Body is visible.
$this->createScreenshot($this->screenshotPath . '04-language-select-body-visible-when-controlled-field-has-default-value.png');
$this->waitUntilVisible('.field--name-body', 50, '01. Article Body field is not visible');
// Change a select value set that should not show the body.
$this->changeField($this->fieldSelector, $this->langcodes[0]);
$this->createScreenshot($this->screenshotPath . '05-language-select-body-invisible-when-controlled-field-has-wrong-value.png');
$this->waitUntilHidden('.field--name-body', 50, '02. Article Body field is visible');
// Change a select value set to show the body.
$this->changeField($this->fieldSelector, $this->defaultLanguage);
$this->createScreenshot($this->screenshotPath . '06-language-select-body-visible-when-controlled-field-has-value.png');
$this->waitUntilVisible('.field--name-body', 50, '03. Article Body field is not visible');
// Change a select value set to hide the body again.
$this->changeField($this->fieldSelector, $this->langcodes[1]);
$this->createScreenshot($this->screenshotPath . '07-language-select-body-invisible-when-controlled-field-has-wrong-value-again.png');
$this->waitUntilHidden('.field--name-body', 50, '04. Article Body field is visible');
}
/**
* {@inheritdoc}
*/
public function testVisibleValueXor() {
$this->baseTestSteps();
// Visit a ConditionalFields configuration page for Content bundles.
$this->createCondition('body', $this->fieldName, 'visible', 'value');
$this->createScreenshot($this->screenshotPath . '01-language-select-add-filed-conditions.png');
// Set up conditions.
$data = [
'condition' => 'value',
'values_set' => CONDITIONAL_FIELDS_DEPENDENCY_VALUES_XOR,
"values" => implode( "\r\n", $this->langcodes ),
'grouping' => 'AND',
'state' => 'visible',
'effect' => 'show',
];
$this->submitForm( $data, 'Save settings');
$this->createScreenshot($this->screenshotPath . '02-language-select-post-add-list-options-filed-conditions.png');
// Check if that configuration is saved.
$this->drupalGet('admin/structure/types/manage/article/conditionals');
$this->createScreenshot($this->screenshotPath . '03-language-select-submit-list-options-filed-conditions.png');
$this->assertSession()->pageTextContains('body ' . $this->fieldName . ' visible value');
// Visit Article Add form to check that conditions are applied.
$this->drupalGet('node/add/article');
// Check that the field Body is visible.
$this->createScreenshot($this->screenshotPath . '04-language-select-body-visible-when-controlled-field-has-default-value.png');
$this->waitUntilHidden('.field--name-body', 50, '01. Article Body field is visible');
// Change a select value set that should not show the body.
$this->changeField($this->fieldSelector, $this->langcodes[0]);
$this->createScreenshot($this->screenshotPath . '05-language-select-body-invisible-when-controlled-field-has-wrong-value.png');
$this->waitUntilVisible('.field--name-body', 50, '02. Article Body field is not visible');
// Change a select value set to show the body.
$this->changeField($this->fieldSelector, $this->defaultLanguage);
$this->createScreenshot($this->screenshotPath . '06-language-select-body-visible-when-controlled-field-has-value.png');
$this->waitUntilHidden('.field--name-body', 50, '03. Article Body field is visible');
// Change a select value set to hide the body again.
$this->changeField($this->fieldSelector, $this->langcodes[1]);
$this->createScreenshot($this->screenshotPath . '07-language-select-body-invisible-when-controlled-field-has-wrong-value-again.png');
$this->waitUntilVisible('.field--name-body', 50, '04. Article Body field is not visible');
}
}
| enslyon/ensl | modules/conditional_fields/tests/src/FunctionalJavascript/ConditionalFieldLanguageSelectTest.php | PHP | gpl-2.0 | 17,212 |
/*
Copyright (C) 2008 - 2016 by Mark de Wever <koraq@xs4all.nl>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
#ifndef GUI_WIDGETS_TEXT_BOX_HPP_INCLUDED
#define GUI_WIDGETS_TEXT_BOX_HPP_INCLUDED
#include "gui/widgets/text.hpp"
namespace gui2
{
// ------------ WIDGET -----------{
/**
* Class for text input history.
*
* The history of text items can be stored in the preferences. This class
* handles that. Every item needs an id by which the history is loaded and
* saved.
*/
class ttext_history
{
public:
/**
* Gets history that matches id.
*
* @param id The id of the history to look for.
* @param enabled The enabled state of the history.
*
* @returns The history object.
*/
static ttext_history get_history(const std::string& id, const bool enabled);
ttext_history() : history_(0), pos_(0), enabled_(false)
{
}
/**
* Push string into the history.
*
* If the string is empty or the same as the last item in the history this
* function is a nop.
*
* @param text The text to push in the history.
*/
void push(const std::string& text);
/**
* One step up in the history.
*
* Pushes text to the history if at the end.
*
* @param text The text to push in the history.
*
* @returns The current value of the history.
*/
std::string up(const std::string& text = "");
/**
* One step down in the history.
*
* Pushes text to the history if at the end.
*
* @param text The text to push in the history.
*
* @returns The current value of the history.
*/
std::string down(const std::string& text = "");
/**
* Gets the current history value.
*
* @returns If enabled return the current history
* position, otherwise an empty string is
* returned.
*/
std::string get_value() const;
/***** ***** ***** setters / getters for members ***** ****** *****/
void set_enabled(bool enabled = true)
{
enabled_ = enabled;
}
bool get_enabled() const
{
return enabled_;
}
private:
ttext_history(std::vector<std::string>* history, const bool enabled)
: history_(history), pos_(history->size()), enabled_(enabled)
{
}
/** The items in the history. */
std::vector<std::string>* history_;
/** The current position in the history. */
unsigned pos_;
/** Is the history enabled. */
bool enabled_;
};
/** Class for a single line text area. */
class ttext_box : public ttext_
{
public:
ttext_box();
/** Saves the text in the widget to the history. */
void save_to_history()
{
history_.push(get_value());
}
/***** ***** ***** setters / getters for members ***** ****** *****/
void set_history(const std::string& id)
{
history_ = ttext_history::get_history(id, true);
}
void set_max_input_length(const size_t length)
{
max_input_length_ = length;
}
void clear()
{
set_value("");
}
protected:
/***** ***** ***** ***** layout functions ***** ***** ***** *****/
/** See @ref twidget::place. */
virtual void place(const tpoint& origin, const tpoint& size) override;
/***** ***** ***** ***** Inherited ***** ***** ***** *****/
/** See @ref tcontrol::update_canvas. */
virtual void update_canvas() override;
/** Inherited from ttext_. */
void goto_end_of_line(const bool select = false) override
{
goto_end_of_data(select);
}
/** Inherited from ttext_. */
void goto_start_of_line(const bool select = false) override
{
goto_start_of_data(select);
}
/** Inherited from ttext_. */
void delete_char(const bool before_cursor) override;
/** Inherited from ttext_. */
void delete_selection() override;
void handle_mouse_selection(tpoint mouse, const bool start_selection);
private:
/** The history text for this widget. */
ttext_history history_;
/** The maximum length of the text input. */
size_t max_input_length_;
/**
* The x offset in the widget where the text starts.
*
* This value is needed to translate a location in the widget to a location
* in the text.
*/
unsigned text_x_offset_;
/**
* The y offset in the widget where the text starts.
*
* Needed to determine whether a click is on the text.
*/
unsigned text_y_offset_;
/**
* The height of the text itself.
*
* Needed to determine whether a click is on the text.
*/
unsigned text_height_;
/** Updates text_x_offset_ and text_y_offset_. */
void update_offsets();
/** Is the mouse in dragging mode, this affects selection in mouse move */
bool dragging_;
/**
* Inherited from ttext_.
*
* Unmodified Unhandled.
* Control Ignored.
* Shift Ignored.
* Alt Ignored.
*/
void handle_key_up_arrow(SDL_Keymod /*modifier*/, bool& /*handled*/) override
{
}
/**
* Inherited from ttext_.
*
* Unmodified Unhandled.
* Control Ignored.
* Shift Ignored.
* Alt Ignored.
*/
void handle_key_down_arrow(SDL_Keymod /*modifier*/, bool& /*handled*/) override
{
}
/**
* Goes one item up in the history.
*
* @returns True if there's a history, false otherwise.
*/
bool history_up();
/**
* Goes one item down in the history.
*
* @returns True if there's a history, false otherwise.
*/
bool history_down();
/** Inherited from ttext_. */
void handle_key_default(bool& handled,
SDL_Keycode key,
SDL_Keymod modifier,
const utf8::string& unicode) override;
/** Inherited from ttext_. */
void handle_key_clear_line(SDL_Keymod modifier, bool& handled) override;
/** See @ref tcontrol::get_control_type. */
virtual const std::string& get_control_type() const override;
/** Inherited from tcontrol. */
void load_config_extra() override;
/***** ***** ***** signal handlers ***** ****** *****/
void signal_handler_mouse_motion(const event::tevent event,
bool& handled,
const tpoint& coordinate);
void signal_handler_left_button_down(const event::tevent event,
bool& handled);
void signal_handler_left_button_up(const event::tevent event,
bool& handled);
void signal_handler_left_button_double_click(const event::tevent event,
bool& handled);
};
// }---------- DEFINITION ---------{
struct ttext_box_definition : public tcontrol_definition
{
explicit ttext_box_definition(const config& cfg);
struct tresolution : public tresolution_definition_
{
explicit tresolution(const config& cfg);
tformula<unsigned> text_x_offset;
tformula<unsigned> text_y_offset;
};
};
// }---------- BUILDER -----------{
namespace implementation
{
struct tbuilder_text_box : public tbuilder_control
{
public:
explicit tbuilder_text_box(const config& cfg);
using tbuilder_control::build;
twidget* build() const;
std::string history;
size_t max_input_length;
};
} // namespace implementation
// }------------ END --------------
} // namespace gui2
#endif
| aquileia/wesnoth | src/gui/widgets/text_box.hpp | C++ | gpl-2.0 | 7,540 |
<?php
include('includes/session.inc');
$Title = _('Tax Status Maintenance');
include('includes/header.inc');
include('includes/SQL_CommonFunctions.inc');
if (isset($_GET['TaxStatusID'])) {
$TaxStatusID = strtoupper($_GET['TaxStatusID']);
} elseif (isset($_POST['TaxStatusID'])) {
$TaxStatusID = strtoupper($_POST['TaxStatusID']);
} else {
unset($TaxStatusID);
}
//initialise no input errors assumed initially before we test
$InputError = 0;
/* actions to take once the user has clicked the submit button
ie the page has called itself with some user input */
//first off validate inputs sensible
if ($InputError != 1 and (isset($_POST['update']) or isset($_POST['insert']))) {
if (isset($_POST['update'])) {
$SQL = "UPDATE prltaxstatus SET taxstatusdescription='" . $_POST['TaxStatusDescription'] . "',
personalexemption='" . $_POST['PersonalExemption'] . "',
additionalexemption='" . $_POST['AdditionalExemption'] . "',
totalexemption='" . $_POST['TotalExemption'] . "'
WHERE taxstatusid = '" . $TaxStatusID . "'";
$ErrMsg = _('The tax status could not be updated because');
$DbgMsg = _('The SQL that was used to update the tax status but failed was');
$Result = DB_query($SQL, $ErrMsg, $DbgMsg);
prnMsg(_('The tax status master record for') . ' ' . $TaxStatusID . ' ' . _('has been updated'), 'success');
} elseif (isset($_POST['insert'])) { //its a new tax status
$SQL = "INSERT INTO prltaxstatus (taxstatusid,
taxstatusdescription,
personalexemption,
additionalexemption,
totalexemption
) VALUES ('" . $_POST['TaxStatusID'] . "',
'" . $_POST['TaxStatusDescription'] . "',
'" . $_POST['PersonalExemption'] . "',
'" . $_POST['AdditionalExemption'] . "',
'" . $_POST['TotalExemption'] . "'
)";
$ErrMsg = _('The tax status') . ' ' . $_POST['TaxStatusDescription'] . ' ' . _('could not be added because');
$DbgMsg = _('The SQL that was used to insert the tax status but failed was');
$Result = DB_query($SQL, $ErrMsg, $DbgMsg);
prnMsg(_('A new tax status for') . ' ' . $_POST['TaxStatusDescription'] . ' ' . _('has been added to the database'), 'success');
}
unset($TaxStatusID);
unset($_POST['TaxStatusDescription']);
unset($_POST['PersonalExemption']);
unset($_POST['AdditionalExemption']);
unset($_POST['TotalExemption']);
} elseif ($InputError > 0) {
prnMsg(_('Validation failed') . _('no updates or deletes took place'), 'warn');
}
if (isset($_POST['delete']) AND $_POST['delete'] != '') {
//the link to delete a selected record was clicked instead of the submit button
$CancelDelete = 0;
// PREVENT DELETES IF DEPENDENT RECORDS IN 'SuppTrans' , PurchOrders, SupplierContacts
if ($CancelDelete == 0) {
$SQL = "DELETE FROM prltaxstatus WHERE taxstatusid='$TaxStatusID'";
$Result = DB_query($SQL);
prnMsg(_('Tax status record for') . ' ' . $TaxStatusID . ' ' . _('has been deleted'), 'success');
unset($TaxStatusID);
unset($_SESSION['TaxStatusID']);
} //end if Delete tax status
} //end of (isset($_POST['submit']))
//SupplierID exists - either passed when calling the form or from the form itself
echo '<form method="post" class="noPrint" action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '">';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
echo '<p class="page_title_text noPrint" >
<img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/money_add.png" title="' . $Title . '" alt="" />' . ' ' . $Title . '
</p>';
$SQL = "SELECT taxstatusid,
taxstatusdescription,
personalexemption,
additionalexemption,
totalexemption
FROM prltaxstatus";
$Result = DB_query($SQL);
if (DB_num_rows($Result)) {
echo '<table class="selection">
<tr>
<th>' . _('Status ID') . '<th>
<th>' . _('Description') . '<th>
<th>' . _('Personal Excemption') . '<th>
<th>' . _('Additional Excemption') . '<th>
<th>' . _('Total Excemption') . '<th>
</tr>';
while ($MyRow = DB_fetch_array($Result)) {
echo '<tr>
<td>' . $MyRow['taxstatusid'] . '<td>
<td>' . $MyRow['taxstatusdescription'] . '<td>
<td class="number">' . locale_number_format($MyRow['personalexemption'], $_SESSION['CompanyRecord']['decimalplaces']) . '<td>
<td class="number">' . locale_number_format($MyRow['additionalexemption'], $_SESSION['CompanyRecord']['decimalplaces']) . '<td>
<td class="number">' . locale_number_format($MyRow['totalexemption'], $_SESSION['CompanyRecord']['decimalplaces']) . '<td>
<td><a href="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '?TaxStatusID=' . $MyRow['taxstatusid'] . '">' . _('Edit') . '</a></td>
</tr>';
}
echo '</table>';
}
if (isset($TaxStatusID)) {
$SQL = "SELECT taxstatusid,
taxstatusdescription,
personalexemption,
additionalexemption,
totalexemption
FROM prltaxstatus
WHERE taxstatusid = '" . $TaxStatusID . "'";
$Result = DB_query($SQL);
$MyRow = DB_fetch_array($Result);
$_POST['TaxStatusDescription'] = $MyRow['taxstatusdescription'];
$_POST['PersonalExemption'] = $MyRow['personalexemption'];
$_POST['AdditionalExemption'] = $MyRow['additionalexemption'];
$_POST['TotalExemption'] = $MyRow['totalexemption'];
echo '<table class="selection">';
echo '<input type="hidden" name="TaxStatusID" value="' . $TaxStatusID . '" />';
echo '<tr>
<td>' . _('Tax Status ID') . ':</td>
<td>' . $TaxStatusID . '</td>
</tr>';
} else {
// its a new status being added
echo '<table class="selection">';
echo '<tr>
<td>' . _('Tax Status ID') . ':</td>
<td><input type="text" name="TaxStatusID" value="" size="12" maxlength="10" /></td>
</tr>';
$_POST['TaxStatusDescription'] = '';
$_POST['PersonalExemption'] = 0;
$_POST['AdditionalExemption'] = 0;
$_POST['TotalExemption'] = 0;
}
echo '<tr>
<td>' . _('Tax Status Description') . ':</td>
<td><input type="text" name="TaxStatusDescription" value="' . $_POST['TaxStatusDescription'] . '" size="42" maxlength="40" //></td>
</tr>';
echo '<tr>
<td>' . _('Personal Exemption') . ':</td>
<td><input type="text" class="number" name="PersonalExemption" value="' . $_POST['PersonalExemption'] . '" size="13" maxlength="12" /></td>
</tr>';
echo '<tr>
<td>' . _('Additional Exemption') . ':</td>
<td><input type="text" class="number" name="AdditionalExemption" size="13" maxlength="12" value="' . $_POST['AdditionalExemption'] . '" /></td>
</tr>';
echo '<tr>
<td>' . _('Total Exemption') . ':</td>
<td><input type="text" class="number" name="TotalExemption" size="13" maxlength="12" value="' . $_POST['TotalExemption'] . '" /></td>
</tr>';
if (!isset($TaxStatusID)) {
echo '</table>
<div class="centre">
<input type="submit" name="insert" value="' . _('Add These New Tax Status Details') . '" />
</div>
</form>';
} else {
echo '</table>
<div class="centre">
<input type="submit" name="update" value="' . _('Update Tax Status') . '" />
</div>';
echo '<div class="centre">
<input type="Submit" name="delete" value="' . _('Delete Employee') . '" onclick="return confirm("' . _('Are you sure you wish to delete this tax status?') . '");" />
</div>
</form>';
}
include('includes/footer.inc');
?> | fahadhatib/KwaMoja | prlTaxStatus.php | PHP | gpl-2.0 | 7,520 |
package ModelLayer;
import java.util.ArrayList;
/**
* Write a description of class Product here.
*
* @author (Jacob Pedersen & Ronnie Knudsen)
* @version (04-12-2014) dd-mm-yyyy
*/
public class Product
{
// instance variables
private ArrayList<ProductItem> items;
private int id;
private String barcode;
private String productName;
private String description;
private double minimumPrice; //Absolute minimum price, that the product may be sold for.
private double salesPrice; //Actual price the product should be sold for.
private double supplierPrice; //The price the product costed to buy from the supplier
private double discountPrice; //if there's a discount, the sales price will be defined here while the discount lasts. When not null, this will be the given sales price.
private int quantity; //The ammount of items
private String location; //location the products items is located in the warehouse.
/**
* Constructor for objects of class Product
*
* @param id the products unique id.
* @param barcode the products barcode.
* @param productName The products name.
* @param description product description.
* @param minimumPrice minimum price that the product may be sold for.
* @param salesPrice Actual price the product should be sold for.
* @param supplierPrice The price the product costed to buy from the supplier.
* @param discountPrice if there's a discount, the sales price will be defined here while the discount lasts. When not 0, this will be the given sales price.
*/
public Product(int id, String barcode, String productName, String description, double minimumPrice, double salesPrice, double supplierPrice)
{
items = new ArrayList<ProductItem>();
this.id = id;
this.barcode = barcode;
this.productName = productName;
this.description = description;
this.minimumPrice = minimumPrice;
this.salesPrice = salesPrice;
this.supplierPrice = supplierPrice;
this.quantity = 0;
this.location = "Undefined";
}
/**
* Adds an item to the container with availbale items for this product.
*
* @param productItem A parameter
*/
public void addItem(ProductItem productItem)
{
items.add(productItem);
quantity++;
}
/**
* If an item is avalible, the first on the list is returned.
*
* @return is an item of the given itemtype.
*/
public ProductItem getItem()
{
if(items.size() > 0)
{
return items.get(0);
}
return null;
}
/**
* Returns the item with the given SerialNumber if it exists.
*
* @param SerialNumber The items serialnumber.
* @Return The item with the given serialnumber if it exists. Else it returns null.
*/
public ProductItem getItemBySerial(String serialNumber)
{
//Find item with given serialNumber.
return null;
}
/**
* returns true if remove is available.
*
* @true if remove is available, else false
*/
public boolean removeItem()
{
if(getAvailable() == true)
{
items.remove(0);
quantity--;
return true;
}
return false;
}
/**
* @return true if there's items available for the product and false if not.
*/
public boolean getAvailable()
{
if(quantity > 0)
{
return true;
}
return false;
}
/**
* Get the products id.
* @return Get the products id.
*/
public int getId()
{
return id;
}
/**
* Get the products barcode.
* @return The products Barcode.
*/
public String getBarcode()
{
return barcode;
}
/**
* Get the products name.
* @return The products name.
*/
public String getProductName()
{
return productName;
}
/**
* Get the products description.
* @return The products description.
*/
public String getDescription()
{
return description;
}
/**
* Get the products minimum price.
* @return The products minimum price.
*/
public double getMinimumPrice()
{
return minimumPrice;
}
/**
* Get the products sales price.
* @return The products sales price.
*/
public double getSalesPrice()
{
return salesPrice;
}
/**
* Get the products discount price.
* @return The products discount price.
*/
public double getDiscountPrice()
{
return discountPrice;
}
/**
* Get the products supplier price.
* @return The products supplier price.
*/
public double getSupplierPrice()
{
return supplierPrice;
}
/**
* Get the products quantity of available items.
* @return The products quantity.
*/
public int getQuantity()
{
return quantity;
}
/**
* Get the products location in the warehouse.
* @return The products location in the warehouse.
*/
public String getLocation()
{
return location;
}
/**
* @param barcode the barcode to set
*/
public void setBarcode(String barcode) {
this.barcode = barcode;
}
/**
* @param productName the productName to set
*/
public void setProductName(String productName) {
this.productName = productName;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @param minimumPrice the minimumPrice to set
*/
public void setMinimumPrice(double minimumPrice) {
this.minimumPrice = minimumPrice;
}
/**
* @param salesPrice the salesPrice to set
*/
public void setSalesPrice(double salesPrice) {
this.salesPrice = salesPrice;
}
/**
* @param supplierPrice the supplierPrice to set
*/
public void setSupplierPrice(double supplierPrice) {
this.supplierPrice = supplierPrice;
}
/**
* @param discountPrice the discountPrice to set
*/
public void setDiscountPrice(double discountPrice) {
this.discountPrice = discountPrice;
}
/**
* @param quantity the quantity to set
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
/**
* @param location the location to set
*/
public void setLocation(String location) {
this.location = location;
}
}
| dmab0914-Gruppe-2/Vestbjerg-Byggecenter | src/ModelLayer/Product.java | Java | gpl-2.0 | 6,578 |
#include <iostream>
#include "assembler.h"
using namespace std;
// Simple constructor.
Assembler::Assembler(istream &in, ostream &out)
{
currentAddress = 0;
for (int i = 0; i < MAXLABEL; i++)
labelTable[i] = 0;
insource = ∈
outsource = &out;
}
// Default destructor.
Assembler::~Assembler()
{ }
// The first pass of the assmebler. This just builds the labelTable.
// Don't translate just yet.
void Assembler::firstPass()
{
// Start at address 0 (not 1 as I had previously thought)
currentAddress = 0;
string nextop;
(*insource) >> nextop;
// Loop until we find the ENDPROG operation.
for (;;) {
// Record the current address in the label table.
if (nextop == "DEFADDR") {
int index;
(*insource) >> index;
labelTable[index] = currentAddress;
(*insource) >> nextop;
}
// Record the associated value in the label table.
else if (nextop == "DEFARG") {
int index, value;
(*insource) >> index >> value;
labelTable[index] = value;
(*insource) >> nextop;
}
// Stop when we find ENDPROG.
else if (nextop == "ENDPROG")
return;
else if (nextop == "ARROW" || nextop == "ASSIGN" || nextop == "BAR" ||
nextop == "CONSTANT" || nextop == "FI" || nextop == "READ" ||
nextop == "WRITE") {
// Skip one machine words.
(*insource) >> nextop;
(*insource) >> nextop;
currentAddress += 2;
}
else if (nextop == "CALL" || nextop == "INDEX" || nextop == "PROC" ||
nextop == "PROG" || nextop == "VARIABLE") {
// Skip two machine words.
(*insource) >> nextop;
(*insource) >> nextop;
(*insource) >> nextop;
currentAddress += 3;
}
else {
// just get the next machine word.
(*insource) >> nextop;
currentAddress++;
}
}
}
// The second pass of the assembler. Here we actually translate operations
// to their opcodes.
void Assembler::secondPass()
{
string nextop;
(*insource) >> nextop;
// Loop until ENDPROG.
for (;;) {
if (nextop == "ADD") {
(*outsource) << 0 << endl;;
currentAddress++;
}
else if (nextop == "AND") {
(*outsource) << 1 << endl;;
currentAddress++;
}
else if (nextop == "ARROW") {
(*outsource) << 2 << endl;;
int temp;
(*insource) >> temp;
// Output the absolute jump address.
(*outsource) << labelTable[temp] << endl;
currentAddress += 2;
}
else if (nextop == "ASSIGN") {
(*outsource) << 3 << endl;
int temp;
(*insource) >> temp;
(*outsource) << temp << endl;
currentAddress += 2;
}
else if (nextop == "BAR") {
(*outsource) << 4 << endl;
int temp;
(*insource) >> temp;
(*outsource) << labelTable[temp] << endl;
currentAddress += 2;
}
else if (nextop == "CALL") {
(*outsource) << 5 << endl;
int temp;
(*insource) >> temp;
(*outsource) << temp << endl;
(*insource) >> temp;
(*outsource) << labelTable[temp] << endl;
currentAddress += 3;
}
else if (nextop == "CONSTANT") {
(*outsource) << 6 << endl;
int temp;
(*insource) >> temp;
(*outsource) << temp << endl;
currentAddress += 2;
}
else if (nextop == "DIVIDE") {
(*outsource) << 7 << endl;
currentAddress++;
}
else if (nextop == "ENDPROC") {
(*outsource) << 8 << endl;
currentAddress++;
}
else if (nextop == "ENDPROG") {
(*outsource) << 9 << endl;
break;
}
else if (nextop == "EQUAL") {
(*outsource) << 10 << endl;
currentAddress++;
}
else if (nextop == "FI") {
(*outsource) << 11 << endl;
int temp;
(*insource) >> temp;
(*outsource) << temp << endl;
currentAddress += 2;
}
else if (nextop == "GREATER") {
(*outsource) << 12 << endl;
currentAddress++;
}
else if (nextop == "INDEX") {
(*outsource) << 13 << endl;
int temp;
(*insource) >> temp;
(*outsource) << temp << endl;
(*insource) >> temp;
(*outsource) << temp << endl;
currentAddress += 3;
}
else if (nextop == "LESS") {
(*outsource) << 14 << endl;
currentAddress++;
}
else if (nextop == "MINUS") {
(*outsource) << 15 << endl;
currentAddress++;
}
else if (nextop == "MODULO") {
(*outsource) << 16 << endl;
currentAddress++;
}
else if (nextop == "MULTIPLY") {
(*outsource) << 17 << endl;
currentAddress++;
}
else if (nextop == "NOT") {
(*outsource) << 18 << endl;
currentAddress++;
}
else if (nextop == "OR") {
(*outsource) << 19 << endl;
currentAddress++;
}
else if (nextop == "PROC") {
(*outsource) << 20 << endl;
int temp;
(*insource) >> temp;
(*outsource) << labelTable[temp] << endl;
(*insource) >> temp;
(*outsource) << labelTable[temp] << endl;
currentAddress += 3;
}
else if (nextop == "PROG") {
(*outsource) << 21 << endl;
int temp;
(*insource) >> temp;
(*outsource) << labelTable[temp] << endl;
(*insource) >> temp;
(*outsource) << labelTable[temp] << endl;
currentAddress += 3;
}
else if (nextop == "READ") {
(*outsource) << 22 << endl;
int temp;
(*insource) >> temp;
(*outsource) << temp << endl;
currentAddress += 2;
}
else if (nextop == "SUBTRACT") {
(*outsource) << 23 << endl;
currentAddress++;
}
else if (nextop == "VALUE") {
(*outsource) << 24 << endl;
currentAddress++;
}
else if (nextop == "VARIABLE") {
(*outsource) << 25 << endl;
int temp;
(*insource) >> temp;
(*outsource) << temp << endl;
(*insource) >> temp;
(*outsource) << temp << endl;
currentAddress += 3;
}
else if (nextop == "WRITE") {
(*outsource) << 26 << endl;
int temp;
(*insource) >> temp;
(*outsource) << temp << endl;
currentAddress += 2;
}
else if (nextop == "DEFADDR") {
int temp;
(*insource) >> temp;
}
else if (nextop == "DEFARG") {
int temp1, temp2;
(*insource) >> temp1 >> temp2;
}
else {
// We should never see this message.
cerr << "Assembler encountered an unknown operator: `"
<< nextop << "'. Bailing...\n";
exit(2);
}
(*insource) >> nextop;
}
}
| versionzero/plc | src/assembler.cc | C++ | gpl-2.0 | 6,134 |
<?php
/**
* @package Joomla.Platform
* @subpackage Database
*
* @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* MySQLi import driver.
*
* @since 11.1
*/
class JDatabaseImporterMysqli extends JDatabaseImporter
{
/**
* Checks if all data and options are in order prior to exporting.
*
* @return JDatabaseImporterMysqli Method supports chaining.
*
* @since 11.1
* @throws Exception if an error is encountered.
*/
public function check()
{
// Check if the db connector has been set.
if (!($this->db instanceof JDatabaseDriverMysqli))
{
throw new Exception('JPLATFORM_ERROR_DATABASE_CONNECTOR_WRONG_TYPE');
}
// Check if the tables have been specified.
if (empty($this->from))
{
throw new Exception('JPLATFORM_ERROR_NO_TABLES_SPECIFIED');
}
return $this;
}
/**
* Get the SQL syntax to add a table.
*
* @param SimpleXMLElement $table The table information.
*
* @return string
*
* @since 11.1
* @throws RuntimeException
*/
protected function xmlToCreate(SimpleXMLElement $table)
{
$existingTables = $this->db->getTableList();
$tableName = (string) $table['name'];
if (in_array($tableName, $existingTables))
{
throw new RuntimeException('The table you are trying to create already exists');
}
$createTableStatement = 'CREATE TABLE ' . $this->db->quoteName($tableName) . ' (';
foreach ($table->xpath('field') as $field)
{
$createTableStatement .= $this->getColumnSQL($field) . ', ';
}
$newLookup = $this->getKeyLookup($table->xpath('key'));
// Loop through each key in the new structure.
foreach ($newLookup as $key)
{
$createTableStatement .= $this->getKeySQL($key) . ', ';
}
// Remove the comma after the last key
$createTableStatement = rtrim($createTableStatement, ', ');
$createTableStatement .= ')';
return $createTableStatement;
}
/**
* Get the SQL syntax to add a column.
*
* @param string $table The table name.
* @param SimpleXMLElement $field The XML field definition.
*
* @return string
*
* @since 11.1
*/
protected function getAddColumnSql($table, SimpleXMLElement $field)
{
return 'ALTER TABLE ' . $this->db->quoteName($table) . ' ADD COLUMN ' . $this->getColumnSql($field);
}
/**
* Get the SQL syntax to add a key.
*
* @param string $table The table name.
* @param array $keys An array of the fields pertaining to this key.
*
* @return string
*
* @since 11.1
*/
protected function getAddKeySql($table, $keys)
{
return 'ALTER TABLE ' . $this->db->quoteName($table) . ' ADD ' . $this->getKeySql($keys);
}
/**
* Get alters for table if there is a difference.
*
* @param SimpleXMLElement $structure The XML structure pf the table.
*
* @return array
*
* @since 11.1
*/
protected function getAlterTableSql(SimpleXMLElement $structure)
{
$table = $this->getRealTableName($structure['name']);
$oldFields = $this->db->getTableColumns($table);
$oldKeys = $this->db->getTableKeys($table);
$alters = array();
// Get the fields and keys from the XML that we are aiming for.
$newFields = $structure->xpath('field');
$newKeys = $structure->xpath('key');
// Loop through each field in the new structure.
foreach ($newFields as $field)
{
$fName = (string) $field['Field'];
if (isset($oldFields[$fName]))
{
// The field exists, check it's the same.
$column = $oldFields[$fName];
// Test whether there is a change.
$change = ((string) $field['Type'] != $column->Type) || ((string) $field['Null'] != $column->Null)
|| ((string) $field['Default'] != $column->Default) || ((string) $field['Extra'] != $column->Extra);
if ($change)
{
$alters[] = $this->getChangeColumnSql($table, $field);
}
// Unset this field so that what we have left are fields that need to be removed.
unset($oldFields[$fName]);
}
else
{
// The field is new.
$alters[] = $this->getAddColumnSql($table, $field);
}
}
// Any columns left are orphans
foreach ($oldFields as $name => $column)
{
// Delete the column.
$alters[] = $this->getDropColumnSql($table, $name);
}
// Get the lookups for the old and new keys.
$oldLookup = $this->getKeyLookup($oldKeys);
$newLookup = $this->getKeyLookup($newKeys);
// Loop through each key in the new structure.
foreach ($newLookup as $name => $keys)
{
// Check if there are keys on this field in the existing table.
if (isset($oldLookup[$name]))
{
$same = true;
$newCount = count($newLookup[$name]);
$oldCount = count($oldLookup[$name]);
// There is a key on this field in the old and new tables. Are they the same?
if ($newCount == $oldCount)
{
// Need to loop through each key and do a fine grained check.
for ($i = 0; $i < $newCount; $i++)
{
$same = (((string) $newLookup[$name][$i]['Non_unique'] == $oldLookup[$name][$i]->Non_unique)
&& ((string) $newLookup[$name][$i]['Column_name'] == $oldLookup[$name][$i]->Column_name)
&& ((string) $newLookup[$name][$i]['Seq_in_index'] == $oldLookup[$name][$i]->Seq_in_index)
&& ((string) $newLookup[$name][$i]['Collation'] == $oldLookup[$name][$i]->Collation)
&& ((string) $newLookup[$name][$i]['Index_type'] == $oldLookup[$name][$i]->Index_type));
/*
Debug.
echo '<pre>';
echo '<br>Non_unique: '.
((string) $newLookup[$name][$i]['Non_unique'] == $oldLookup[$name][$i]->Non_unique ? 'Pass' : 'Fail').' '.
(string) $newLookup[$name][$i]['Non_unique'].' vs '.$oldLookup[$name][$i]->Non_unique;
echo '<br>Column_name: '.
((string) $newLookup[$name][$i]['Column_name'] == $oldLookup[$name][$i]->Column_name ? 'Pass' : 'Fail').' '.
(string) $newLookup[$name][$i]['Column_name'].' vs '.$oldLookup[$name][$i]->Column_name;
echo '<br>Seq_in_index: '.
((string) $newLookup[$name][$i]['Seq_in_index'] == $oldLookup[$name][$i]->Seq_in_index ? 'Pass' : 'Fail').' '.
(string) $newLookup[$name][$i]['Seq_in_index'].' vs '.$oldLookup[$name][$i]->Seq_in_index;
echo '<br>Collation: '.
((string) $newLookup[$name][$i]['Collation'] == $oldLookup[$name][$i]->Collation ? 'Pass' : 'Fail').' '.
(string) $newLookup[$name][$i]['Collation'].' vs '.$oldLookup[$name][$i]->Collation;
echo '<br>Index_type: '.
((string) $newLookup[$name][$i]['Index_type'] == $oldLookup[$name][$i]->Index_type ? 'Pass' : 'Fail').' '.
(string) $newLookup[$name][$i]['Index_type'].' vs '.$oldLookup[$name][$i]->Index_type;
echo '<br>Same = '.($same ? 'true' : 'false');
echo '</pre>';
*/
if (!$same)
{
// Break out of the loop. No need to check further.
break;
}
}
}
else
{
// Count is different, just drop and add.
$same = false;
}
if (!$same)
{
$alters[] = $this->getDropKeySql($table, $name);
$alters[] = $this->getAddKeySql($table, $keys);
}
// Unset this field so that what we have left are fields that need to be removed.
unset($oldLookup[$name]);
}
else
{
// This is a new key.
$alters[] = $this->getAddKeySql($table, $keys);
}
}
// Any keys left are orphans.
foreach ($oldLookup as $name => $keys)
{
if (strtoupper($name) == 'PRIMARY')
{
$alters[] = $this->getDropPrimaryKeySql($table);
}
else
{
$alters[] = $this->getDropKeySql($table, $name);
}
}
return $alters;
}
/**
* Get the syntax to alter a column.
*
* @param string $table The name of the database table to alter.
* @param SimpleXMLElement $field The XML definition for the field.
*
* @return string
*
* @since 11.1
*/
protected function getChangeColumnSql($table, SimpleXMLElement $field)
{
return 'ALTER TABLE ' . $this->db->quoteName($table) . ' CHANGE COLUMN ' . $this->db->quoteName((string) $field['Field']) . ' '
. $this->getColumnSql($field);
}
/**
* Get the SQL syntax for a single column that would be included in a table create or alter statement.
*
* @param SimpleXMLElement $field The XML field definition.
*
* @return string
*
* @since 11.1
*/
protected function getColumnSql(SimpleXMLElement $field)
{
// TODO Incorporate into parent class and use $this.
$blobs = array('text', 'smalltext', 'mediumtext', 'largetext');
$fName = (string) $field['Field'];
$fType = (string) $field['Type'];
$fNull = (string) $field['Null'];
$fDefault = isset($field['Default']) ? (string) $field['Default'] : null;
$fExtra = (string) $field['Extra'];
$query = $this->db->quoteName($fName) . ' ' . $fType;
if ($fNull == 'NO')
{
if (in_array($fType, $blobs) || $fDefault === null)
{
$query .= ' NOT NULL';
}
else
{
// TODO Don't quote numeric values.
$query .= ' NOT NULL DEFAULT ' . $this->db->quote($fDefault);
}
}
else
{
if ($fDefault === null)
{
$query .= ' DEFAULT NULL';
}
else
{
// TODO Don't quote numeric values.
$query .= ' DEFAULT ' . $this->db->quote($fDefault);
}
}
if ($fExtra)
{
$query .= ' ' . strtoupper($fExtra);
}
return $query;
}
/**
* Get the SQL syntax to drop a key.
*
* @param string $table The table name.
* @param string $name The name of the key to drop.
*
* @return string
*
* @since 11.1
*/
protected function getDropKeySql($table, $name)
{
return 'ALTER TABLE ' . $this->db->quoteName($table) . ' DROP KEY ' . $this->db->quoteName($name);
}
/**
* Get the SQL syntax to drop a key.
*
* @param string $table The table name.
*
* @return string
*
* @since 11.1
*/
protected function getDropPrimaryKeySql($table)
{
return 'ALTER TABLE ' . $this->db->quoteName($table) . ' DROP PRIMARY KEY';
}
/**
* Get the details list of keys for a table.
*
* @param array $keys An array of objects that comprise the keys for the table.
*
* @return array The lookup array. array({key name} => array(object, ...))
*
* @since 11.1
* @throws Exception
*/
protected function getKeyLookup($keys)
{
// First pass, create a lookup of the keys.
$lookup = array();
foreach ($keys as $key)
{
if ($key instanceof SimpleXMLElement)
{
$kName = (string) $key['Key_name'];
}
else
{
$kName = $key->Key_name;
}
if (empty($lookup[$kName]))
{
$lookup[$kName] = array();
}
$lookup[$kName][] = $key;
}
return $lookup;
}
/**
* Get the SQL syntax for a key.
*
* @param array $columns An array of SimpleXMLElement objects comprising the key.
*
* @return string
*
* @since 11.1
*/
protected function getKeySql($columns)
{
// TODO Error checking on array and element types.
$kNonUnique = (string) $columns[0]['Non_unique'];
$kName = (string) $columns[0]['Key_name'];
$kColumn = (string) $columns[0]['Column_name'];
$prefix = '';
if ($kName == 'PRIMARY')
{
$prefix = 'PRIMARY ';
}
elseif ($kNonUnique == 0)
{
$prefix = 'UNIQUE ';
}
$nColumns = count($columns);
$kColumns = array();
if ($nColumns == 1)
{
$kColumns[] = $this->db->quoteName($kColumn);
}
else
{
foreach ($columns as $column)
{
$kColumns[] = (string) $column['Column_name'];
}
}
$query = $prefix . 'KEY ' . ($kName != 'PRIMARY' ? $this->db->quoteName($kName) : '') . ' (' . implode(',', $kColumns) . ')';
return $query;
}
}
| ylahav/joomla-cms | libraries/joomla/database/importer/mysqli.php | PHP | gpl-2.0 | 11,690 |
// cmdline_extract_cache_subset.cc
//
// Copyright (C) 2008-2010 Daniel Burrows
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; see the file COPYING. If not, write to
// the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
// Local includes:
#include "cmdline_extract_cache_subset.h"
#include "cmdline_util.h"
#include "terminal.h"
#include "text_progress.h"
#include <aptitude.h>
#include <generic/apt/apt.h>
#include <generic/apt/dump_packages.h>
#include <generic/apt/matching/match.h>
#include <generic/apt/matching/parse.h>
#include <generic/apt/matching/pattern.h>
#include <generic/util/util.h>
// System includes:
#include <apt-pkg/error.h>
#include <apt-pkg/progress.h>
#include <stdio.h>
#include <memory>
using aptitude::cmdline::create_terminal;
using aptitude::cmdline::make_text_progress;
using aptitude::cmdline::terminal_io;
namespace aptitude
{
namespace cmdline
{
int extract_cache_subset(int argc, char *argv[])
{
if(argc < 2)
{
fprintf(stderr, _("extract-cache-entries: at least one argument is required (the directory\nto which to write files).\n"));
return -1;
}
const std::shared_ptr<terminal_io> term = create_terminal();
std::string out_dir = argv[1];
std::shared_ptr<OpProgress> progress = make_text_progress(false, term, term, term);
apt_init(progress.get(), true);
if(_error->PendingError())
{
_error->DumpErrors();
return -1;
}
bool ok = true;
std::set<pkgCache::PkgIterator> packages;
if(argc == 2)
{
for(pkgCache::PkgIterator pIt = (*apt_cache_file)->PkgBegin();
!pIt.end(); ++pIt)
packages.insert(pIt);
}
else
{
for(int i = 2; i < argc; ++i)
{
std::string arg(argv[i]);
if(!aptitude::matching::is_pattern(arg))
{
pkgCache::PkgIterator pIt = (*apt_cache_file)->FindPkg(arg);
if(pIt.end())
{
std::cerr << ssprintf(_("No such package \"%s\""), arg.c_str())
<< std::endl;
ok = false;
}
else
packages.insert(pIt);
}
else
{
using namespace aptitude::matching;
using cwidget::util::ref_ptr;
ref_ptr<pattern> p = parse(arg);
if(p.valid())
{
_error->DumpErrors();
}
else
{
std::vector<std::pair<pkgCache::PkgIterator, ref_ptr<structural_match> > > matches;
ref_ptr<search_cache> search_info(search_cache::create());
search(p, search_info,
matches,
*apt_cache_file,
*apt_package_records);
for(std::vector<std::pair<pkgCache::PkgIterator, ref_ptr<structural_match> > >::const_iterator
it = matches.begin(); it != matches.end(); ++it)
packages.insert(it->first);
}
}
}
}
if(!ok)
return 2;
if(packages.size() == 0)
{
printf(_("No packages were selected by the given search pattern; nothing to do.\n"));
return 0;
}
aptitude::apt::make_truncated_state_copy(out_dir, packages);
bool copy_ok = !_error->PendingError();
_error->DumpErrors();
return copy_ok ? 0 : 1;
}
}
}
| iamduyu/aptitude | src/cmdline/cmdline_extract_cache_subset.cc | C++ | gpl-2.0 | 3,749 |
class CreateMaterials < ActiveRecord::Migration
def change
create_table :materials do |t|
t.string :name
t.decimal :price_per_m2
t.timestamps null: false
end
end
end
| ProjNaRok1516/ruby-www | db/migrate/20160105130157_create_materials.rb | Ruby | gpl-2.0 | 197 |
// Aseprite
// Copyright (C) 2001-2016 David Capello
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "app/util/freetype_utils.h"
#include "base/unique_ptr.h"
#include "doc/blend_funcs.h"
#include "doc/blend_internals.h"
#include "doc/color.h"
#include "doc/image.h"
#include "doc/primitives.h"
#include "ft/face.h"
#include "ft/lib.h"
#include <stdexcept>
namespace app {
doc::Image* render_text(const std::string& fontfile, int fontsize,
const std::string& text,
doc::color_t color,
bool antialias)
{
base::UniquePtr<doc::Image> image(nullptr);
ft::Lib ft;
ft::Face face(ft.open(fontfile));
if (face.isValid()) {
// Set font size
face.setSize(fontsize);
face.setAntialias(antialias);
// Calculate text size
gfx::Rect bounds = face.calcTextBounds(text);
// Render the image and copy it to the clipboard
if (!bounds.isEmpty()) {
image.reset(doc::Image::create(doc::IMAGE_RGB, bounds.w, bounds.h));
doc::clear_image(image, 0);
face.forEachGlyph(
text,
[&bounds, &image, color, antialias](const ft::Glyph& glyph) {
int t, yimg = - bounds.y + int(glyph.y);
for (int v=0; v<int(glyph.bitmap->rows); ++v, ++yimg) {
const uint8_t* p = glyph.bitmap->buffer + v*glyph.bitmap->pitch;
int ximg = - bounds.x + int(glyph.x);
int bit = 0;
for (int u=0; u<int(glyph.bitmap->width); ++u, ++ximg) {
int alpha;
if (antialias) {
alpha = *(p++);
}
else {
alpha = ((*p) & (1 << (7 - (bit++))) ? 255: 0);
if (bit == 8) {
bit = 0;
++p;
}
}
int output_alpha = MUL_UN8(doc::rgba_geta(color), alpha, t);
if (output_alpha) {
doc::color_t output_color =
doc::rgba(doc::rgba_getr(color),
doc::rgba_getg(color),
doc::rgba_getb(color),
output_alpha);
doc::put_pixel(
image, ximg, yimg,
doc::rgba_blender_normal(
doc::get_pixel(image, ximg, yimg),
output_color));
}
}
}
});
}
else {
throw std::runtime_error("There is no text");
}
}
else {
throw std::runtime_error("Error loading font face");
}
return (image ? image.release(): nullptr);
}
} // namespace app
| tony/aseprite | src/app/util/freetype_utils.cpp | C++ | gpl-2.0 | 2,836 |
/********************************************************************************
* *
* GNORASI - The Knowlegde-Based Remote Sensing Engine *
* *
* Language: C++ *
* *
* Copyright (c) ALTEC SA - All rights reserved. *
* Copyright (c) ALTEC SA - All rights reserved. *
* Copyright (c) ALTEC SA - All rights reserved. *
* *
* This file is part of the GNORASI software package. GNORASI is free *
* software: you can redistribute it and/or modify it under the terms *
* of the GNU General Public License version 2 as published by the *
* Free Software Foundation. *
* *
* GNORASI is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* in the file "LICENSE.txt" along with this program. *
* If not, see <http://www.gnu.org/licenses/>. *
* *
********************************************************************************/
#include "otbgeodesicactivecontourlevelsetimagefilterprocessor.h"
#include "voreen/core/voreenapplication.h"
namespace voreen {
const std::string OTBGeodesicActiveContourLevelSetImageFilterProcessor::loggerCat_("voreen.OTBGeodesicActiveContourLevelSetImageFilterProcessor");
OTBGeodesicActiveContourLevelSetImageFilterProcessor::OTBGeodesicActiveContourLevelSetImageFilterProcessor()
:OTBImageFilterProcessor(),
seedX_("seedX", "Seed Point X: ", 0, 0, 2000),
seedY_("seedY", "Seed Point Y: ", 0, 0, 2000),
initialDistance_("initialDistance", "Initial Distance: ", 5.0f, 0.0f, 1000.0f),
sigma_("sigma", "Sigma: ", 1.0f, 0.0f, 100.0f),
sigmoidAlpha_("sigmoidAlpha", "Sigmoid Alpha:", 5.f, -100.0f, 255.0f),
sigmoidBeta_("sigmoidBeta", "Sigmoid Beta:", 10.0f, -100.0f, 255.0f),
propagationScaling_("propagationScaling", "Propagation Scaling: ", 10.0, 0.0f, 100.0f),
inPort_(Port::INPORT, "OTBImage.Inport",0),
outPort_(Port::OUTPORT, "OTBImage.Outport",0),
testOutPort1_(Port::OUTPORT, "OTBImage.Smoothing",0),
testOutPort2_(Port::OUTPORT, "OTBImage.GradientMagnitude",0),
testOutPort3_(Port::OUTPORT, "OTBImage.Sigmoid",0),
testOutPort4_(Port::OUTPORT, "OTBImage.FastMarching",0)
{
addProperty(enableSwitch_);
addProperty(seedX_);
addProperty(seedY_);
addProperty(initialDistance_);
addProperty(sigma_);
addProperty(sigmoidAlpha_);
addProperty(sigmoidBeta_);
addProperty(propagationScaling_);
addPort(inPort_);
addPort(testOutPort1_);
addPort(testOutPort2_);
addPort(testOutPort3_);
addPort(testOutPort4_);
addPort(outPort_);
smoothing = SmoothingFilterType::New();
gradientMagnitude = GradientFilterType::New();
sigmoid = SigmoidFilterType::New();
fastMarching = FastMarchingFilterType::New();
seeds = NodeContainer::New();
geodesicActiveContour = GeodesicActiveContourFilterType::New();
thresholder = ThresholdingFilterType::New();
portToCharCaster = PortToCharCastingFilterType::New();
charToInternalCaster = CharToInternalCastingFilterType::New();
charToPortCaster = CharToPortCastingFilterType::New();
internToPortCaster1 = InternalToPortCastingFilterType::New();
}
Processor* OTBGeodesicActiveContourLevelSetImageFilterProcessor::create() const {
return new OTBGeodesicActiveContourLevelSetImageFilterProcessor();
}
OTBGeodesicActiveContourLevelSetImageFilterProcessor::~OTBGeodesicActiveContourLevelSetImageFilterProcessor() {
}
void OTBGeodesicActiveContourLevelSetImageFilterProcessor::initialize() throw (tgt::Exception) {
Processor::initialize();
}
void OTBGeodesicActiveContourLevelSetImageFilterProcessor::deinitialize() throw (tgt::Exception) {
Processor::deinitialize();
}
std::string OTBGeodesicActiveContourLevelSetImageFilterProcessor::getProcessorInfo() const {
return "Geodesic Active Contour Level Set Image Filter Processor";
}
void OTBGeodesicActiveContourLevelSetImageFilterProcessor::process() {
//LINFO("Geodesic Active Contour Level SetImage Filter Enabled!");
//check bypass switch
if (!enableSwitch_.get()) {
bypass(&inPort_, &outPort_);
return;
}
try
{
//Curvature Anisotropic Diffusion
smoothing->SetInput(inPort_.getData());
smoothing->SetTimeStep(0.125);
smoothing->SetNumberOfIterations(5);
smoothing->SetConductanceParameter(9.0);
//testOutport1.Smoothing
testOutPort1_.setData(smoothing->GetOutput());
//Gradient Magnitude
gradientMagnitude->SetInput(smoothing->GetOutput());
double sigma = sigma_.get();
gradientMagnitude->SetSigma(sigma);
//testOutport2.GradientMagnitude
testOutPort2_.setData(gradientMagnitude->GetOutput());
//Sigmoid
portToCharCaster->SetInput(gradientMagnitude->GetOutput());
sigmoid->SetInput(portToCharCaster->GetOutput());
sigmoid->SetOutputMinimum(0);
sigmoid->SetOutputMaximum(255);
double alpha = sigmoidAlpha_.get();
double beta = sigmoidBeta_.get();
sigmoid->SetAlpha(alpha);
sigmoid->SetBeta(beta);
sigmoid->Update();
charToInternalCaster->SetInput(sigmoid->GetOutput());
//testOutport3.Sigmoid
charToPortCaster->SetInput(sigmoid->GetOutput());
testOutPort3_.setData(charToPortCaster->GetOutput());
//Geodesic Active Contour
geodesicActiveContour->SetFeatureImage(charToInternalCaster->GetOutput());
double propagationScaling = propagationScaling_.get();
geodesicActiveContour->SetPropagationScaling(propagationScaling);
geodesicActiveContour->SetCurvatureScaling(1.0);
geodesicActiveContour->SetAdvectionScaling(1.0);
geodesicActiveContour->SetMaximumRMSError(0.02);
geodesicActiveContour->SetNumberOfIterations(800);
//Fast Marching
seedPosition[0] = seedX_.get();
seedPosition[1] = seedY_.get();
double initialDistance = initialDistance_.get();
NodeType node;
double seedValue = -initialDistance;
node.SetValue(seedValue);
node.SetIndex(seedPosition);
seeds->Initialize();
seeds->InsertElement(0,node);
fastMarching->SetTrialPoints(seeds);
fastMarching->SetSpeedConstant(1.0);
fastMarching->SetOutputSize(inPort_.getData()->GetBufferedRegion().GetSize());
fastMarching->Update();
//testOutport3.FastMarching
testOutPort4_.setData(fastMarching->GetOutput());
//Fast Matching -> Geodesic Active Contour
geodesicActiveContour->SetInput(fastMarching->GetOutput());
geodesicActiveContour->Update();
//Thresholder
internToPortCaster1->SetInput(geodesicActiveContour->GetOutput());
thresholder->SetInput(internToPortCaster1->GetOutput());
thresholder->SetLowerThreshold(-1000.0);
thresholder->SetUpperThreshold(0.0);
thresholder->SetOutsideValue(0);
thresholder->SetInsideValue(255);
thresholder->Update();
//outPort
outPort_.setData(thresholder->GetOutput());
LINFO("Geodesic Active Contour Level SetImage Filter Connected!");
}
catch (int e)
{
LERROR("Error in Geodesic Active Contour Level SetImage Filter!");
return;
}
}
} // namespace
| gnorasi/gnorasi | Gnorasi/modules/otb/processors/Segmentation/otbgeodesicactivecontourlevelsetimagefilterprocessor.cpp | C++ | gpl-2.0 | 8,476 |
<?php
/**
* @file
* Contains \Drupal\Console\Utils\Create\UserData.
*/
namespace Drupal\Console\Utils\Create;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Datetime\DateFormatterInterface;
/**
* Class Users
*
* @package Drupal\Console\Utils\Create
*/
class UserData extends Base
{
/**
* Create and returns an array of new Users.
*
* @param $roles
* @param $limit
* @param $password
* @param $timeRange
*
* @return array
*/
public function create(
$roles,
$limit,
$password,
$timeRange
) {
$siteRoles = $this->drupalApi->getRoles();
$users = [];
for ($i=0; $i<$limit; $i++) {
$username = $this->getRandom()->word(mt_rand(6, 12));
$user = $this->entityTypeManager->getStorage('user')->create(
[
'name' => $username,
'mail' => $username . '@example.com',
'pass' => $password?:$this->getRandom()->word(mt_rand(8, 16)),
'status' => mt_rand(0, 1),
'roles' => $roles[array_rand($roles)],
'created' => REQUEST_TIME - mt_rand(0, $timeRange),
]
);
try {
$user->save();
$userRoles = [];
foreach ($user->getRoles() as $userRole) {
$userRoles[] = $siteRoles[$userRole];
}
$users['success'][] = [
'user-id' => $user->id(),
'username' => $user->getUsername(),
'roles' => implode(', ', $userRoles),
'created' => $this->dateFormatter->format(
$user->getCreatedTime(),
'custom',
'Y-m-d h:i:s'
)
];
} catch (\Exception $error) {
$users['error'][] = [
'vid' => $user->id(),
'name' => $user->get('name'),
'error' => $error->getMessage()
];
}
}
return $users;
}
}
| cburschka/drupal-console | src/Utils/Create/UserData.php | PHP | gpl-2.0 | 2,268 |
package com.code.taskmanager;
import java.util.List;
import com.code.taskmanager.bean.AppInfo;
import com.code.taskmanager.db.dao.WhiteListDao;
import com.code.taskmanager.utils.ApplicationUtils;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.format.Formatter;
import android.widget.Toast;
public class ClearActivity extends Activity {
private boolean openWhiteList;
private List<AppInfo> runningApplication;
private ActivityManager activityManager;
private WhiteListDao whiteListDao;
private int count = 0;
private long mem = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
whiteListDao = new WhiteListDao(this);
openWhiteList = sp.getBoolean("OpenWhiteList", false);
runningApplication = ApplicationUtils.getRunningApplication(this);
clear();
finish();
}
private void clear() {
if (openWhiteList) {
for (AppInfo info : runningApplication) {
if (!whiteListDao.find(info.packagename)) {
activityManager.killBackgroundProcesses(info.packagename);
mem += info.mem;
count++;
}
}
} else {
for (AppInfo info : runningApplication) {
activityManager.killBackgroundProcesses(info.packagename);
mem += info.mem;
count++;
}
}
Toast.makeText(
this,
"Çå³ýÁË" + count + "¸öÈÎÎñ" + ",¹²ÊÍ·ÅÁË"
+ Formatter.formatFileSize(this, mem) + "µÄÄÚ´æ",
Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
whiteListDao.close();
}
}
| silvernoo/KillTask | src/com/code/taskmanager/ClearActivity.java | Java | gpl-2.0 | 1,759 |
/*
* Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package sun.nio.cs.ext;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
public class JIS_X_0208_Solaris_Decoder extends DoubleByteDecoder
{
public JIS_X_0208_Solaris_Decoder(Charset cs) {
super(cs,
index1,
index2,
0x21,
0x7E);
}
private final static String innerIndex0=
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u2460\u2461"+
"\u2462\u2463\u2464\u2465\u2466\u2467\u2468\u2469"+
"\u246A\u246B\u246C\u246D\u246E\u246F\u2470\u2471"+
"\u2472\u2473\u2160\u2161\u2162\u2163\u2164\u2165"+
"\u2166\u2167\u2168\u2169\uFFFD\u3349\u3314\u3322"+
"\u334D\u3318\u3327\u3303\u3336\u3351\u3357\u330D"+
"\u3326\u3323\u332B\u334A\u333B\u339C\u339D\u339E"+
"\u338E\u338F\u33C4\u33A1\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\u337B\u301D\u301F\u2116"+
"\u33CD\u2121\u32A4\u32A5\u32A6\u32A7\u32A8\u3231"+
"\u3232\u3239\u337E\u337D\u337C\u2252\u2261\u222B"+
"\u222E\u2211\u221A\u22A5\u2220\u221F\u22BF\u2235"+
"\u2229\u222A\uFFFD\uFFFD\u7E8A\u891C\u9348\u9288"+
"\u84DC\u4FC9\u70BB\u6631\u68C8\u92F9\u66FB\u5F45"+
"\u4E28\u4EE1\u4EFC\u4F00\u4F03\u4F39\u4F56\u4F92"+
"\u4F8A\u4F9A\u4F94\u4FCD\u5040\u5022\u4FFF\u501E"+
"\u5046\u5070\u5042\u5094\u50F4\u50D8\u514A\u5164"+
"\u519D\u51BE\u51EC\u5215\u529C\u52A6\u52C0\u52DB"+
"\u5300\u5307\u5324\u5372\u5393\u53B2\u53DD\uFA0E"+
"\u549C\u548A\u54A9\u54FF\u5586\u5759\u5765\u57AC"+
"\u57C8\u57C7\uFA0F\uFA10\u589E\u58B2\u590B\u5953"+
"\u595B\u595D\u5963\u59A4\u59BA\u5B56\u5BC0\u752F"+
"\u5BD8\u5BEC\u5C1E\u5CA6\u5CBA\u5CF5\u5D27\u5D53"+
"\uFA11\u5D42\u5D6D\u5DB8\u5DB9\u5DD0\u5F21\u5F34"+
"\u5F67\u5FB7\u5FDE\u605D\u6085\u608A\u60DE\u60D5"+
"\u6120\u60F2\u6111\u6137\u6130\u6198\u6213\u62A6"+
"\u63F5\u6460\u649D\u64CE\u654E\u6600\u6615\u663B"+
"\u6609\u662E\u661E\u6624\u6665\u6657\u6659\uFA12"+
"\u6673\u6699\u66A0\u66B2\u66BF\u66FA\u670E\uF929"+
"\u6766\u67BB\u6852\u67C0\u6801\u6844\u68CF\uFA13"+
"\u6968\uFA14\u6998\u69E2\u6A30\u6A6B\u6A46\u6A73"+
"\u6A7E\u6AE2\u6AE4\u6BD6\u6C3F\u6C5C\u6C86\u6C6F"+
"\u6CDA\u6D04\u6D87\u6D6F\u6D96\u6DAC\u6DCF\u6DF8"+
"\u6DF2\u6DFC\u6E39\u6E5C\u6E27\u6E3C\u6EBF\u6F88"+
"\u6FB5\u6FF5\u7005\u7007\u7028\u7085\u70AB\u710F"+
"\u7104\u715C\u7146\u7147\uFA15\u71C1\u71FE\u72B1"+
"\u72BE\u7324\uFA16\u7377\u73BD\u73C9\u73D6\u73E3"+
"\u73D2\u7407\u73F5\u7426\u742A\u7429\u742E\u7462"+
"\u7489\u749F\u7501\u756F\u7682\u769C\u769E\u769B"+
"\u76A6\uFA17\u7746\u52AF\u7821\u784E\u7864\u787A"+
"\u7930\uFA18\uFA19\uFA1A\u7994\uFA1B\u799B\u7AD1"+
"\u7AE7\uFA1C\u7AEB\u7B9E\uFA1D\u7D48\u7D5C\u7DB7"+
"\u7DA0\u7DD6\u7E52\u7F47\u7FA1\uFA1E\u8301\u8362"+
"\u837F\u83C7\u83F6\u8448\u84B4\u8553\u8559\u856B"+
"\uFA1F\u85B0\uFA20\uFA21\u8807\u88F5\u8A12\u8A37"+
"\u8A79\u8AA7\u8ABE\u8ADF\uFA22\u8AF6\u8B53\u8B7F"+
"\u8CF0\u8CF4\u8D12\u8D76\uFA23\u8ECF\uFA24\uFA25"+
"\u9067\u90DE\uFA26\u9115\u9127\u91DA\u91D7\u91DE"+
"\u91ED\u91EE\u91E4\u91E5\u9206\u9210\u920A\u923A"+
"\u9240\u923C\u924E\u9259\u9251\u9239\u9267\u92A7"+
"\u9277\u9278\u92E7\u92D7\u92D9\u92D0\uFA27\u92D5"+
"\u92E0\u92D3\u9325\u9321\u92FB\uFA28\u931E\u92FF"+
"\u931D\u9302\u9370\u9357\u93A4\u93C6\u93DE\u93F8"+
"\u9431\u9445\u9448\u9592\uF9DC\uFA29\u969D\u96AF"+
"\u9733\u973B\u9743\u974D\u974F\u9751\u9755\u9857"+
"\u9865\uFA2A\uFA2B\u9927\uFA2C\u999E\u9A4E\u9AD9"+
"\u9ADC\u9B75\u9B72\u9B8F\u9BB1\u9BBB\u9C00\u9D70"+
"\u9D6B\uFA2D\u9E19\u9ED1\uFFFD\uFFFD\u2170\u2171"+
"\u2172\u2173\u2174\u2175\u2176\u2177\u2178\u2179"+
"\u3052\u00A6\uFF07\uFF02\u2170\u2171\u2172\u2173"+
"\u2174\u2175\u2176\u2177\u2178\u2179\u2160\u2161"+
"\u2162\u2163\u2164\u2165\u2166\u2167\u2168\u2169"+
"\u3052\u00A6\uFF07\uFF02\u3231\u2116\u2121\u306E"+
"\u7E8A\u891C\u9348\u9288\u84DC\u4FC9\u70BB\u6631"+
"\u68C8\u92F9\u66FB\u5F45\u4E28\u4EE1\u4EFC\u4F00"+
"\u4F03\u4F39\u4F56\u4F92\u4F8A\u4F9A\u4F94\u4FCD"+
"\u5040\u5022\u4FFF\u501E\u5046\u5070\u5042\u5094"+
"\u50F4\u50D8\u514A\u5164\u519D\u51BE\u51EC\u5215"+
"\u529C\u52A6\u52C0\u52DB\u5300\u5307\u5324\u5372"+
"\u5393\u53B2\u53DD\uFA0E\u549C\u548A\u54A9\u54FF"+
"\u5586\u5759\u5765\u57AC\u57C8\u57C7\uFA0F\uFA10"+
"\u589E\u58B2\u590B\u5953\u595B\u595D\u5963\u59A4"+
"\u59BA\u5B56\u5BC0\u752F\u5BD8\u5BEC\u5C1E\u5CA6"+
"\u5CBA\u5CF5\u5D27\u5D53\uFA11\u5D42\u5D6D\u5DB8"+
"\u5DB9\u5DD0\u5F21\u5F34\u5F67\u5FB7\u5FDE\u605D"+
"\u6085\u608A\u60DE\u60D5\u6120\u60F2\u6111\u6137"+
"\u6130\u6198\u6213\u62A6\u63F5\u6460\u649D\u64CE"+
"\u654E\u6600\u6615\u663B\u6609\u662E\u661E\u6624"+
"\u6665\u6657\u6659\uFA12\u6673\u6699\u66A0\u66B2"+
"\u66BF\u66FA\u670E\uF929\u6766\u67BB\u6852\u67C0"+
"\u6801\u6844\u68CF\uFA13\u6968\uFA14\u6998\u69E2"+
"\u6A30\u6A6B\u6A46\u6A73\u6A7E\u6AE2\u6AE4\u6BD6"+
"\u6C3F\u6C5C\u6C86\u6C6F\u6CDA\u6D04\u6D87\u6D6F"+
"\u6D96\u6DAC\u6DCF\u6DF8\u6DF2\u6DFC\u6E39\u6E5C"+
"\u6E27\u6E3C\u6EBF\u6F88\u6FB5\u6FF5\u7005\u7007"+
"\u7028\u7085\u70AB\u710F\u7104\u715C\u7146\u7147"+
"\uFA15\u71C1\u71FE\u72B1\u72BE\u7324\uFA16\u7377"+
"\u73BD\u73C9\u73D6\u73E3\u73D2\u7407\u73F5\u7426"+
"\u742A\u7429\u742E\u7462\u7489\u749F\u7501\u756F"+
"\u7682\u769C\u769E\u769B\u76A6\uFA17\u7746\u52AF"+
"\u7821\u784E\u7864\u787A\u7930\uFA18\uFA19\uFA1A"+
"\u7994\uFA1B\u799B\u7AD1\u7AE7\uFA1C\u7AEB\u7B9E"+
"\uFA1D\u7D48\u7D5C\u7DB7\u7DA0\u7DD6\u7E52\u7F47"+
"\u7FA1\uFA1E\u8301\u8362\u837F\u83C7\u83F6\u8448"+
"\u84B4\u8553\u8559\u856B\uFA1F\u85B0\uFA20\uFA21"+
"\u8807\u88F5\u8A12\u8A37\u8A79\u8AA7\u8ABE\u8ADF"+
"\uFA22\u8AF6\u8B53\u8B7F\u8CF0\u8CF4\u8D12\u8D76"+
"\uFA23\u8ECF\uFA24\uFA25\u9067\u90DE\uFA26\u9115"+
"\u9127\u91DA\u91D7\u91DE\u91ED\u91EE\u91E4\u91E5"+
"\u9206\u9210\u920A\u923A\u9240\u923C\u924E\u9259"+
"\u9251\u9239\u9267\u92A7\u9277\u9278\u92E7\u92D7"+
"\u92D9\u92D0\uFA27\u92D5\u92E0\u92D3\u9325\u9321"+
"\u92FB\uFA28\u931E\u92FF\u931D\u9302\u9370\u9357"+
"\u93A4\u93C6\u93DE\u93F8\u9431\u9445\u9448\u9592"+
"\uF9DC\uFA29\u969D\u96AF\u9733\u973B\u9743\u974D"+
"\u974F\u9751\u9755\u9857\u9865\uFA2A\uFA2B\u9927"+
"\uFA2C\u999E\u9A4E\u9AD9\u9ADC\u9B75\u9B72\u9B8F"+
"\u9BB1\u9BBB\u9C00\u9D70\u9D6B\uFA2D\u9E19\u9ED1"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD"+
"\uFFFD\uFFFD";
private static final short index1[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 4, 5, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 6, 7, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
private final static String index2[] = {
innerIndex0
};
protected char convSingleByte(int b) {
return REPLACE_CHAR;
}
/**
* These accessors are temporarily supplied while sun.io
* converters co-exist with the sun.nio.cs.{ext} charset coders
* These facilitate sharing of conversion tables between the
* two co-existing implementations. When sun.io converters
* are made extinct these will be unncessary and should be removed
*/
public static short[] getIndex1() {
return index1;
}
public static String[] getIndex2() {
return index2;
}
}
| neelance/jre4ruby | jre4ruby/src/share/sun/nio/cs/ext/JIS_X_0208_Solaris_Decoder.java | Java | gpl-2.0 | 10,929 |
<?php
declare(strict_types=1);
namespace Netgen\Bundle\EzFormsBundle\Tests\Form\FieldTypeHandler;
use eZ\Publish\Core\FieldType\Url\Value as UrlValue;
use eZ\Publish\Core\Repository\Values\ContentType\FieldDefinition;
use Netgen\Bundle\EzFormsBundle\Form\FieldTypeHandler;
use Netgen\Bundle\EzFormsBundle\Form\FieldTypeHandler\Url;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\FormBuilder;
final class UrlTest extends TestCase
{
public function testAssertInstanceOfFieldTypeHandler(): void
{
$url = new Url();
self::assertInstanceOf(FieldTypeHandler::class, $url);
}
public function testConvertFieldValueToForm(): void
{
$url = new Url();
$timeValue = new UrlValue('link', 'text');
$returnedValue = $url->convertFieldValueToForm($timeValue);
self::assertSame(['url' => 'link', 'text' => 'text'], $returnedValue);
}
public function testConvertFieldValueFromForm(): void
{
$url = new Url();
$timeValue = new UrlValue('link', 'text');
$returnedValue = $url->convertFieldValueFromForm(['url' => 'link', 'text' => 'text']);
self::assertSame($timeValue->link, $returnedValue->link);
self::assertSame($timeValue->text, $returnedValue->text);
}
public function testConvertFieldValueFromFormWhenDataIsNotArray(): void
{
$url = new Url();
$timeValue = new UrlValue(null, null);
$returnedValue = $url->convertFieldValueFromForm('some string');
self::assertSame($timeValue->link, $returnedValue->link);
self::assertSame($timeValue->text, $returnedValue->text);
}
public function testBuildFieldCreateForm(): void
{
$formBuilder = $this->getMockBuilder(FormBuilder::class)
->disableOriginalConstructor()
->onlyMethods(['add'])
->getMock();
$formBuilder->expects(self::once())
->method('add');
$fieldDefinition = new FieldDefinition(
[
'id' => 'id',
'identifier' => 'identifier',
'isRequired' => true,
'descriptions' => ['fre-FR' => 'fre-FR'],
'names' => ['fre-FR' => 'fre-FR'],
]
);
$languageCode = 'eng-GB';
$url = new Url();
$url->buildFieldCreateForm($formBuilder, $fieldDefinition, $languageCode);
}
}
| netgen/NetgenEzFormsBundle | tests/Form/FieldTypeHandler/UrlTest.php | PHP | gpl-2.0 | 2,421 |
<?php
/* core/themes/classy/templates/navigation/links.html.twig */
class __TwigTemplate_ece02f0c3df7b0086cd0ca8465f38308d76b527e9ac8a6b1025d4d084d54ae92 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$tags = array("if" => 34, "for" => 43);
$filters = array();
$functions = array();
try {
$this->env->getExtension('Twig_Extension_Sandbox')->checkSecurity(
array('if', 'for'),
array(),
array()
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setSourceContext($this->getSourceContext());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
// line 34
if (($context["links"] ?? null)) {
// line 35
if (($context["heading"] ?? null)) {
// line 36
if ($this->getAttribute(($context["heading"] ?? null), "level", array())) {
// line 37
echo "<";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute(($context["heading"] ?? null), "level", array()), "html", null, true));
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute(($context["heading"] ?? null), "attributes", array()), "html", null, true));
echo ">";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute(($context["heading"] ?? null), "text", array()), "html", null, true));
echo "</";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute(($context["heading"] ?? null), "level", array()), "html", null, true));
echo ">";
} else {
// line 39
echo "<h2";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute(($context["heading"] ?? null), "attributes", array()), "html", null, true));
echo ">";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute(($context["heading"] ?? null), "text", array()), "html", null, true));
echo "</h2>";
}
}
// line 42
echo "<ul";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, ($context["attributes"] ?? null), "html", null, true));
echo ">";
// line 43
$context['_parent'] = $context;
$context['_seq'] = twig_ensure_traversable(($context["links"] ?? null));
foreach ($context['_seq'] as $context["_key"] => $context["item"]) {
// line 44
echo "<li";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($context["item"], "attributes", array()), "html", null, true));
echo ">";
// line 45
if ($this->getAttribute($context["item"], "link", array())) {
// line 46
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($context["item"], "link", array()), "html", null, true));
} elseif ($this->getAttribute( // line 47
$context["item"], "text_attributes", array())) {
// line 48
echo "<span";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($context["item"], "text_attributes", array()), "html", null, true));
echo ">";
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($context["item"], "text", array()), "html", null, true));
echo "</span>";
} else {
// line 50
echo $this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed($this->env->getExtension('Drupal\Core\Template\TwigExtension')->escapeFilter($this->env, $this->getAttribute($context["item"], "text", array()), "html", null, true));
}
// line 52
echo "</li>";
}
$_parent = $context['_parent'];
unset($context['_seq'], $context['_iterated'], $context['_key'], $context['item'], $context['_parent'], $context['loop']);
$context = array_intersect_key($context, $_parent) + $_parent;
// line 54
echo "</ul>";
}
}
public function getTemplateName()
{
return "core/themes/classy/templates/navigation/links.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 101 => 54, 95 => 52, 92 => 50, 85 => 48, 83 => 47, 81 => 46, 79 => 45, 75 => 44, 71 => 43, 67 => 42, 59 => 39, 49 => 37, 47 => 36, 45 => 35, 43 => 34,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("", "core/themes/classy/templates/navigation/links.html.twig", "/var/www/html/d8/web/core/themes/classy/templates/navigation/links.html.twig");
}
}
| sunlight25/d8 | web/sites/default/files/php/twig/59f57a8199fdd_links.html.twig_KA9UNfGPPAAfgCg_weyFshk4D/eGH-5KeXbrawrU3zrI3hz1yHDaZZ4DUVkjEVaxxYPiQ.php | PHP | gpl-2.0 | 7,563 |
/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "InstanceScript.h"
#include "SpellScript.h"
#include "ScriptedCreature.h"
#include "violet_hold.h"
enum Spells
{
SPELL_SUMMON_PLAYER = 21150,
SPELL_ARCANE_VACUUM = 58694,
SPELL_BLIZZARD = 58693,
SPELL_MANA_DESTRUCTION = 59374,
SPELL_TAIL_SWEEP = 58690,
SPELL_UNCONTROLLABLE_ENERGY = 58688,
SPELL_TRANSFORM = 58668
};
enum Yells
{
SAY_AGGRO = 0,
SAY_SLAY = 1,
SAY_DEATH = 2,
SAY_SPAWN = 3,
SAY_DISRUPTION = 4,
SAY_BREATH_ATTACK = 5,
SAY_SPECIAL_ATTACK = 6
};
class boss_cyanigosa : public CreatureScript
{
public:
boss_cyanigosa() : CreatureScript("boss_cyanigosa") { }
struct boss_cyanigosaAI : public BossAI
{
boss_cyanigosaAI(Creature* creature) : BossAI(creature, DATA_CYANIGOSA) { }
void EnterCombat(Unit* who) override
{
BossAI::EnterCombat(who);
Talk(SAY_AGGRO);
}
void KilledUnit(Unit* victim) override
{
if (victim->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_SLAY);
}
void JustDied(Unit* killer) override
{
BossAI::JustDied(killer);
Talk(SAY_DEATH);
}
void MoveInLineOfSight(Unit* /*who*/) override { }
void ScheduleTasks() override
{
me->GetScheduler().Schedule(Seconds(10), [this](TaskContext task)
{
DoCastAOE(SPELL_ARCANE_VACUUM);
task.Repeat();
});
me->GetScheduler().Schedule(Seconds(15), [this](TaskContext task)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 45.0f, true))
DoCast(target, SPELL_BLIZZARD);
task.Repeat();
});
me->GetScheduler().Schedule(Seconds(20), [this](TaskContext task)
{
DoCastVictim(SPELL_TAIL_SWEEP);
task.Repeat();
});
me->GetScheduler().Schedule(Seconds(25), [this](TaskContext task)
{
DoCastVictim(SPELL_UNCONTROLLABLE_ENERGY);
task.Repeat();
});
if (IsHeroic())
{
me->GetScheduler().Schedule(Seconds(30), [this](TaskContext task)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 50.0f, true))
DoCast(target, SPELL_MANA_DESTRUCTION);
task.Repeat();
});
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetVioletHoldAI<boss_cyanigosaAI>(creature);
}
};
class achievement_defenseless : public AchievementCriteriaScript
{
public:
achievement_defenseless() : AchievementCriteriaScript("achievement_defenseless") { }
bool OnCheck(Player* /*player*/, Unit* target) override
{
if (!target)
return false;
InstanceScript* instance = target->GetInstanceScript();
if (!instance)
return false;
return instance->GetData(DATA_DEFENSELESS) != 0;
}
};
class spell_cyanigosa_arcane_vacuum : public SpellScriptLoader
{
public:
spell_cyanigosa_arcane_vacuum() : SpellScriptLoader("spell_cyanigosa_arcane_vacuum") { }
class spell_cyanigosa_arcane_vacuum_SpellScript : public SpellScript
{
PrepareSpellScript(spell_cyanigosa_arcane_vacuum_SpellScript);
bool Validate(SpellInfo const* /*spellInfo*/) override
{
return ValidateSpellInfo({ SPELL_SUMMON_PLAYER });
}
void HandleScript(SpellEffIndex /*effIndex*/)
{
GetCaster()->CastSpell(GetHitUnit(), SPELL_SUMMON_PLAYER, true);
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_cyanigosa_arcane_vacuum_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_DUMMY);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_cyanigosa_arcane_vacuum_SpellScript();
}
};
void AddSC_boss_cyanigosa()
{
new boss_cyanigosa();
new achievement_defenseless();
new spell_cyanigosa_arcane_vacuum();
}
| AshamaneProject/AshamaneCore | src/server/scripts/Northrend/VioletHold/boss_cyanigosa.cpp | C++ | gpl-2.0 | 5,736 |
<?php
//root nicht verändern wenn von einer anderen seite aufgerufen!
if (!isset ($fehler) || $fehler == true){
$root = "..";
}
include_once($root."/conf/rdbmsConfig.inc.php");
include_once($root."/include/uebersetzer.inc.php");
include_once($root."/include/benutzerFunctions.inc.php");
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Wartungsseite Reservierungsplan UTILO.eu Belegungsplan und Kundendatenbank Rezervi Generic</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="<?php echo $root ?>/templates/stylesheets.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="95%" height="90%" border="0" align="center" cellpadding="0" cellspacing="3" class="table">
<tr>
<td align="center" valign="middle"><table border="0" align="center" cellpadding="0" cellspacing="2" class="table">
<tr>
<td class="ueberschrift" align="right">Welcome at the
webinterface of 'Rezervi Generic'
<a href="http://www.UTILO.eu/" target="_blank" class="ueberschrift">© UTILO.eu</a>
</td>
<td><a href="http://www.UTILO.eu" target="_blank"><img src="<?php echo $root ?>/webinterface/utilologo200px.gif" border="0"></a></td>
<td class="ueberschrift">Willkommen auf der Wartungsseite
von
'Rezervi Generic'
<a href="http://www.rezervi.com/" target="_blank" class="ueberschrift">© UTILO.eu</a>
</td>
</tr>
</table>
<p class="ueberschrift">
<?php
//passwort wurde falsch eingegeben:
if (!(empty($fehlgeschlagen)) && $fehlgeschlagen) {
?>
</p>
<table width="100%" border="0" cellpadding="0" cellspacing="0" class="belegt">
<tr>
<td><div align="center"><?php echo(getUebersetzung("Der Benutzername und/oder das Passwort wurden falsch eingegeben, bitte wiederholen Sie Ihre Eingabe!")); ?></div></td>
</tr>
</table>
<br />
<?php
} //ende if passwort falsch
?>
<table border="0" align="center" cellpadding="0" cellspacing="2" class="table">
<tr>
<td><p align="center" class="standardSchrift">
Please login with your username and password:<br/>
Bitte melden Sie sich mit Ihrem Benutzernamen und Passwort an:<br/><br/>
If you login for the first time please use 'test' for username and password.
Change the password after your first login!<br/>
Verwenden sie den Benutzernamen und das Password 'test',
wenn sie sich das erste mal anmelden. Vergessen sie nicht diese Daten danach zu ändern!</p>
<form action="<?php echo $root ?>/webinterface/inhalt.php" method="post" name="passwortEingabe" target="_self" id="passwortEingabe">
<table width="10" border="0" align="center" cellpadding="0" cellspacing="5" class="table">
<tr>
<td valign="middle">Username/Benutzername</td>
<td><input name="ben" type="text" class="table" id="ben">
</td>
</tr>
<tr>
<td valign="middle">Password/Passwort</td>
<td><input name="pass" type="password" class="table" id="pass"></td>
</tr>
<tr>
<td valign="middle">Language/Sprache</td>
<td><select name="sprache">
<?php
$res = getSprachen($link);
while($d = mysqli_fetch_array($res)){
$bezeichnung = $d["BEZEICHNUNG"];
$spracheID = $d["SPRACHE_ID"];
$sprache = "en";
$bezeichnung_en = getUebersetzung($bezeichnung);
?>
<option value="<?php echo($spracheID); ?>" <?php if ($sprache == $spracheID) echo(" selected"); ?>>
<?php
echo($bezeichnung_en."/".$bezeichnung);
?>
</option>
<?php
}
?>
</select></td>
</tr>
</table>
<p align="center">
<input name="anmelden" type="submit" class="button200pxA" onMouseOver="this.className='button200pxB';"
onMouseOut="this.className='button200pxA';" id="anmelden" value="login/anmelden"/>
</p>
</form>
<span class="standardSchriftBold"></span></td>
</tr>
</table>
</tr>
<tr>
<td align="center" valign="middle"><font size="1">© UTILO.eu,
2005 - <?php $timestamp = time();
$datum = date("Y",$timestamp);
echo($datum); ?></font></td>
</tr>
</table>
</body>
</html>
<?php
include_once($root."/include/closeDB.inc.php");
?> | utilo-web-app-development/REZERVI | rezerviGeneric/webinterface/index.php | PHP | gpl-2.0 | 4,790 |
using Catel.Data;
using System;
using System.Diagnostics;
namespace Wpf2048.Models
{
[DebuggerDisplay("({PosX},{PosY}) {Tile}")]
public class CellModel : ModelBase
{
public CellModel(int x, int y)
{
PosX = x;
PosY = y;
}
public int PosX { get; private set; }
public int PosY { get; private set; }
public TileModel Tile { get; set; }
internal void Reset()
{
Tile = null;
}
// Check if the specified cell is taken
public bool IsAvailable
{
get
{
return Tile == null;
}
}
public bool IsOccupied
{
get
{
return Tile != null;
}
}
/// <summary>
/// Returns the value of the tile if this cell is occupied, 0 otherwise
/// </summary>
public int Value
{
get
{
return Tile != null ? Tile.Value : 0;
}
}
}
}
| jdehaan/Arena2048 | Models/CellModel.cs | C# | gpl-2.0 | 1,147 |
package data.logic;
import java.util.ArrayList;
import java.util.List;
import data.DatenLogik;
import data.Person;
import database.DBPerson;
import enums.DatabaseErrors;
import enums.ErrorMessage;
import enums.ErrorsPersonLogik;
public class PersonLogik implements DatenLogik<Person> {
private Person object = null;
private List<ErrorMessage> errors = new ArrayList<ErrorMessage>();
public boolean createNew(String nachname, String vorname, String kuenstlername) {
if (nachname == null) {
errors.add(ErrorsPersonLogik.KeinNachname);
}
if (vorname == null) {
errors.add(ErrorsPersonLogik.KeinVorname);
}
if (kuenstlername == null || kuenstlername.trim().length() == 0) {
errors.add(ErrorsPersonLogik.KeinKuenstlername);
}
if (errors.size() > 0) {
return false;
}
object = new Person();
object.setKuenstlername(kuenstlername);
object.setNachname(nachname);
object.setVorname(vorname);
return true;
}
public boolean editLoaded(String nachname, String vorname, String kuenstlername) {
if (nachname == null) {
errors.add(ErrorsPersonLogik.KeinNachname);
}
if (vorname == null) {
errors.add(ErrorsPersonLogik.KeinVorname);
}
if (kuenstlername == null || kuenstlername.trim().length() == 0) {
errors.add(ErrorsPersonLogik.KeinKuenstlername);
}
if (errors.size() > 0) {
return false;
}
object.setKuenstlername(kuenstlername);
object.setNachname(nachname);
object.setVorname(vorname);
return true;
}
@Override
public boolean delete() {
try {
DBPerson dbLogic = getDBLogic();
if (!dbLogic.delete(object)) {
errors.add(DatabaseErrors.UnableToDeletePerson);
return false;
} else {
return true;
}
} catch (ClassNotFoundException e) {
errors.add(DatabaseErrors.NoDBAvailable);
}
return false;
}
@Override
public boolean write() {
try {
DBPerson dbLogic = getDBLogic();
if (!dbLogic.writePerson(object)) {
errors.add(DatabaseErrors.UnableToWrite);
return false;
} else {
return true;
}
} catch (ClassNotFoundException e) {
errors.add(DatabaseErrors.NoDBAvailable);
}
return false;
}
@Override
public boolean loadObject(int id) {
try {
DBPerson dbLogic = getDBLogic();
object = dbLogic.getPerson(id);
if (object == null) {
errors.add(DatabaseErrors.UnableToRead);
return false;
} else {
return true;
}
} catch (ClassNotFoundException e) {
errors.add(DatabaseErrors.NoDBAvailable);
}
return false;
}
@Override
public Person getObject() {
return object;
}
@Override
public List<Person> getAll() {
try {
DBPerson dbLogic = getDBLogic();
List<Person> ret = dbLogic.getAll();
if (ret == null) {
errors.add(DatabaseErrors.UnableToRead);
return null;
} else {
return ret;
}
} catch (ClassNotFoundException e) {
errors.add(DatabaseErrors.NoDBAvailable);
}
return null;
}
@Override
public List<ErrorMessage> getErrors() {
return errors;
}
private DBPerson getDBLogic() throws ClassNotFoundException {
return new DBPerson();
}
@Override
public void reset() {
this.object = null;
this.errors = new ArrayList<ErrorMessage>();
}
}
| ColdanR/medienverwaltung | src/data/logic/PersonLogik.java | Java | gpl-2.0 | 3,180 |
<?php
/**
* Install theme administration panel.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
require( ABSPATH . 'wp-admin/includes/theme-install.php' );
wp_reset_vars( array( 'tab' ) );
if ( ! current_user_can('install_themes') )
wp_die( __( 'You do not have sufficient permissions to install themes on this site.' ) );
if ( is_multisite() && ! is_network_admin() ) {
wp_redirect( network_admin_url( 'theme-install.php' ) );
exit();
}
$title = __( 'Add Themes' );
$parent_file = 'themes.php';
if ( ! is_network_admin() ) {
$submenu_file = 'themes.php';
}
$installed_themes = search_theme_directories();
foreach ( $installed_themes as $k => $v ) {
if ( false !== strpos( $k, '/' ) ) {
unset( $installed_themes[ $k ] );
}
}
wp_localize_script( 'theme', '_wpThemeSettings', array(
'themes' => false,
'settings' => array(
'isInstall' => true,
'canInstall' => current_user_can( 'install_themes' ),
'installURI' => current_user_can( 'install_themes' ) ? self_admin_url( 'theme-install.php' ) : null,
'adminUrl' => parse_url( self_admin_url(), PHP_URL_PATH )
),
'l10n' => array(
'addNew' => __( 'Add New Theme' ),
'search' => __( 'Search Themes' ),
'searchPlaceholder' => __( 'Search themes...' ), // placeholder (no ellipsis)
'upload' => __( 'Upload Theme' ),
'back' => __( 'Back' ),
'error' => __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the <a href="https://wordpress.org/support/">support forums</a>.' ),
'themesFound' => __( 'Number of Themes found: %d' ),
'noThemesFound' => __( 'No themes found. Try a different search.' ),
'collapseSidebar' => __( 'Collapse Sidebar' ),
'expandSidebar' => __( 'Expand Sidebar' ),
),
'installedThemes' => array_keys( $installed_themes ),
) );
wp_enqueue_script( 'theme' );
if ( $tab ) {
/**
* Fires before each of the tabs are rendered on the Install Themes page.
*
* The dynamic portion of the hook name, `$tab`, refers to the current
* theme install tab. Possible values are 'dashboard', 'search', 'upload',
* 'featured', 'new', or 'updated'.
*
* @since 2.8.0
*/
do_action( "install_themes_pre_{$tab}" );
}
$help_overview =
'<p>' . sprintf(__('You can find additional themes for your site by using the Theme Browser/Installer on this screen, which will display themes from the <a href="%s" target="_blank">WordPress.org Theme Directory</a>. These themes are designed and developed by third parties, are available free of charge, and are compatible with the license WordPress uses.'), 'https://wordpress.org/themes/') . '</p>' .
'<p>' . __( 'You can Search for themes by keyword, author, or tag, or can get more specific and search by criteria listed in the feature filter.' ) . ' <span id="live-search-desc">' . __( 'The search results will be updated as you type.' ) . '</span></p>' .
'<p>' . __( 'Alternately, you can browse the themes that are Featured, Popular, or Latest. When you find a theme you like, you can preview it or install it.' ) . '</p>' .
'<p>' . __('You can Upload a theme manually if you have already downloaded its ZIP archive onto your computer (make sure it is from a trusted and original source). You can also do it the old-fashioned way and copy a downloaded theme’s folder via FTP into your <code>/wp-content/themes</code> directory.') . '</p>';
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' => $help_overview
) );
$help_installing =
'<p>' . __('Once you have generated a list of themes, you can preview and install any of them. Click on the thumbnail of the theme you’re interested in previewing. It will open up in a full-screen Preview page to give you a better idea of how that theme will look.') . '</p>' .
'<p>' . __('To install the theme so you can preview it with your site’s content and customize its theme options, click the "Install" button at the top of the left-hand pane. The theme files will be downloaded to your website automatically. When this is complete, the theme is now available for activation, which you can do by clicking the "Activate" link, or by navigating to your Manage Themes screen and clicking the "Live Preview" link under any installed theme’s thumbnail image.') . '</p>';
get_current_screen()->add_help_tab( array(
'id' => 'installing',
'title' => __('Previewing and Installing'),
'content' => $help_installing
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="https://codex.wordpress.org/Using_Themes#Adding_New_Themes" target="_blank">Documentation on Adding New Themes</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>'
);
include(ABSPATH . 'wp-admin/admin-header.php');
?>
<div class="wrap">
<h1><?php
echo esc_html( $title );
/**
* Filter the tabs shown on the Add Themes screen.
*
* This filter is for backwards compatibility only, for the suppression
* of the upload tab.
*
* @since 2.8.0
*
* @param array $tabs The tabs shown on the Add Themes screen. Default is 'upload'.
*/
$tabs = apply_filters( 'install_themes_tabs', array( 'upload' => __( 'Upload Theme' ) ) );
if ( ! empty( $tabs['upload'] ) && current_user_can( 'upload_themes' ) ) {
echo ' <a href="#" class="upload page-title-action">' . __( 'Upload Theme' ) . '</a>';
}
?></h1>
<div class="upload-theme">
<?php install_themes_upload(); ?>
</div>
<br class="clear" />
<?php
if ( $tab ) {
/**
* Fires at the top of each of the tabs on the Install Themes page.
*
* The dynamic portion of the hook name, `$tab`, refers to the current
* theme install tab. Possible values are 'dashboard', 'search', 'upload',
* 'featured', 'new', or 'updated'.
*
* @since 2.8.0
*
* @param int $paged Number of the current page of results being viewed.
*/
do_action( "install_themes_{$tab}", $paged );
}
?>
</div>
<script id="tmpl-theme" type="text/template">
<# if ( data.screenshot_url ) { #>
<div class="theme-screenshot">
<img src="{{ data.screenshot_url }}" alt="" />
</div>
<# } else { #>
<div class="theme-screenshot blank"></div>
<# } #>
<span class="more-details"><?php _ex( 'Details & Preview', 'theme' ); ?></span>
<div class="theme-author"><?php printf( __( 'By %s' ), '{{ data.author }}' ); ?></div>
<h3 class="theme-name">{{ data.name }}</h3>
<div class="theme-actions">
<a class="button button-primary" href="{{ data.install_url }}"><?php esc_html_e( 'Install' ); ?></a>
<a class="button button-secondary preview install-theme-preview" href="#"><?php esc_html_e( 'Preview' ); ?></a>
</div>
<# if ( data.installed ) { #>
<div class="theme-installed"><?php _ex( 'Already Installed', 'theme' ); ?></div>
<# } #>
</script>
<script id="tmpl-theme-preview" type="text/template">
<div class="wp-full-overlay-sidebar">
<div class="wp-full-overlay-header">
<a href="#" class="close-full-overlay"><span class="screen-reader-text"><?php _e( 'Close' ); ?></span></a>
<a href="#" class="previous-theme"><span class="screen-reader-text"><?php _ex( 'Previous', 'Button label for a theme' ); ?></span></a>
<a href="#" class="next-theme"><span class="screen-reader-text"><?php _ex( 'Next', 'Button label for a theme' ); ?></span></a>
<# if ( data.installed ) { #>
<a href="#" class="button button-primary theme-install disabled"><?php _ex( 'Installed', 'theme' ); ?></a>
<# } else { #>
<a href="{{ data.install_url }}" class="button button-primary theme-install"><?php _e( 'Install' ); ?></a>
<# } #>
</div>
<div class="wp-full-overlay-sidebar-content">
<div class="install-theme-info">
<h3 class="theme-name">{{ data.name }}</h3>
<span class="theme-by"><?php printf( __( 'By %s' ), '{{ data.author }}' ); ?></span>
<img class="theme-screenshot" src="{{ data.screenshot_url }}" alt="" />
<div class="theme-details">
<# if ( data.rating ) { #>
<div class="theme-rating">
{{{ data.stars }}}
<span class="num-ratings">({{ data.num_ratings }})</span>
</div>
<# } else { #>
<span class="no-rating"><?php _e( 'This theme has not been rated yet.' ); ?></span>
<# } #>
<div class="theme-version"><?php printf( __( 'Version: %s' ), '{{ data.version }}' ); ?></div>
<div class="theme-description">{{{ data.description }}}</div>
</div>
</div>
</div>
<div class="wp-full-overlay-footer">
<button type="button" class="collapse-sidebar button-secondary" aria-expanded="true" aria-label="<?php esc_attr_e( 'Collapse Sidebar' ); ?>">
<span class="collapse-sidebar-arrow"></span>
<span class="collapse-sidebar-label"><?php _e( 'Collapse' ); ?></span>
</button>
</div>
</div>
<div class="wp-full-overlay-main">
<iframe src="{{ data.preview_url }}" title="<?php esc_attr_e( 'Preview' ); ?>" />
</div>
</script>
<?php
include(ABSPATH . 'wp-admin/admin-footer.php');
| dwrensha/WordPress | wp-admin/theme-install.php | PHP | gpl-2.0 | 9,199 |
//==============================================================================
//
// Copyright (c) 2002-
// Authors:
// * Dave Parker <david.parker@comlab.ox.ac.uk> (University of Oxford)
//
//------------------------------------------------------------------------------
//
// This file is part of PRISM.
//
// PRISM is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// PRISM is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with PRISM; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//==============================================================================
package explicit;
import java.util.BitSet;
import java.util.Map;
import parser.ast.ExpressionTemporal;
import prism.PrismComponent;
import prism.PrismException;
/**
* Explicit-state model checker for continuous-time Markov decision processes (CTMDPs).
*
* This uses various bits of functionality of MDPModelChecker, so we inherit from that.
* (This way MDPModelChecker picks up any options set on this one.)
*/
public class CTMDPModelChecker extends MDPModelChecker
{
/**
* Create a new CTMDPModelChecker, inherit basic state from parent (unless null).
*/
public CTMDPModelChecker(PrismComponent parent) throws PrismException
{
super(parent);
}
// Model checking functions
@Override
protected StateValues checkProbBoundedUntil(Model model, ExpressionTemporal expr, MinMax minMax) throws PrismException
{
double uTime;
BitSet b1, b2;
StateValues probs = null;
ModelCheckerResult res = null;
// get info from bounded until
uTime = expr.getUpperBound().evaluateDouble(constantValues);
if (uTime < 0 || (uTime == 0 && expr.upperBoundIsStrict())) {
String bound = (expr.upperBoundIsStrict() ? "<" : "<=") + uTime;
throw new PrismException("Invalid upper bound " + bound + " in time-bounded until formula");
}
// model check operands first
b1 = checkExpression(model, expr.getOperand1()).getBitSet();
b2 = checkExpression(model, expr.getOperand2()).getBitSet();
// compute probabilities
// a trivial case: "U<=0"
if (uTime == 0) {
// prob is 1 in b2 states, 0 otherwise
probs = StateValues.createFromBitSetAsDoubles(b2, model);
} else {
res = computeBoundedUntilProbs((CTMDP) model, b1, b2, uTime, minMax.isMin());
probs = StateValues.createFromDoubleArray(res.soln, model);
}
return probs;
}
/**
* Compute bounded until probabilities.
* i.e. compute the min/max probability of reaching a state in {@code target},
* within time t, and while remaining in states in @{code remain}.
* @param ctmdp The CTMDP
* @param remain Remain in these states (optional: null means "all")
* @param target Target states
* @param t Bound
* @param min Min or max probabilities (true=min, false=max)
*/
public ModelCheckerResult computeBoundedUntilProbs(CTMDP ctmdp, BitSet remain, BitSet target, double t, boolean min) throws PrismException
{
return computeBoundedReachProbs(ctmdp, remain, target, t, min, null, null);
}
/**
* Compute bounded probabilistic reachability.
* @param ctmdp The CTMDP
* @param remain Remain in these states (optional: null means "all")
* @param target Target states
* @param t Time bound
* @param min Min or max probabilities for (true=min, false=max)
* @param init Initial solution vector - pass null for default
* @param results Optional array of size b+1 to store (init state) results for each step (null if unused)
*/
public ModelCheckerResult computeBoundedReachProbs(CTMDP ctmdp, BitSet remain, BitSet target, double t, boolean min, double init[], double results[]) throws PrismException
{
// TODO: implement until
MDP mdp;
MDPModelChecker mc;
ModelCheckerResult res;
if (!ctmdp.isLocallyUniform())
throw new PrismException("Can't compute bounded reachability probabilities for non-locally uniform CTMDP");
// TODO: check locally uniform
double epsilon = 1e-3;
double q = ctmdp.getMaxExitRate();
int k = (int) Math.ceil((q * t * q * t) / (2 * epsilon));
double tau = t / k;
mainLog.println("q = " + q + ", k = " + k + ", tau = " + tau);
mdp = ctmdp.buildDiscretisedMDP(tau);
mainLog.println(mdp);
mc = new MDPModelChecker(this);
mc.inheritSettings(this);
res = mc.computeBoundedUntilProbs(mdp, null, target, k, min);
return res;
}
/**
* Compute bounded reachability/until probabilities.
* i.e. compute the min/max probability of reaching a state in {@code target},
* within time t, and while remaining in states in @{code remain}.
* @param ctmdp The CTMDP
* @param remain Remain in these states (optional: null means "all")
* @param target Target states
* @param t: Time bound
* @param min Min or max probabilities (true=min, false=max)
* @param init: Initial solution vector - pass null for default
* @param results: Optional array of size b+1 to store (init state) results for each step (null if unused)
*/
public ModelCheckerResult computeBoundedReachProbsOld(CTMDP ctmdp, BitSet remain, BitSet target, double t, boolean min, double init[], double results[]) throws PrismException
{
// TODO: implement until
ModelCheckerResult res = null;
int i, n, iters;
double soln[], soln2[], tmpsoln[], sum[];
long timer;
// Fox-Glynn stuff
FoxGlynn fg;
int left, right;
double q, qt, weights[], totalWeight;
// Start bounded probabilistic reachability
timer = System.currentTimeMillis();
mainLog.println("Starting time-bounded probabilistic reachability...");
// Store num states
n = ctmdp.getNumStates();
// Get uniformisation rate; do Fox-Glynn
q = 99;//ctmdp.unif;
qt = q * t;
mainLog.println("\nUniformisation: q.t = " + q + " x " + t + " = " + qt);
fg = new FoxGlynn(qt, 1e-300, 1e+300, termCritParam / 8.0);
left = fg.getLeftTruncationPoint();
right = fg.getRightTruncationPoint();
if (right < 0) {
throw new PrismException("Overflow in Fox-Glynn computation (time bound too big?)");
}
weights = fg.getWeights();
totalWeight = fg.getTotalWeight();
for (i = left; i <= right; i++) {
weights[i - left] /= totalWeight;
}
mainLog.println("Fox-Glynn: left = " + left + ", right = " + right);
// Create solution vector(s)
soln = new double[n];
soln2 = (init == null) ? new double[n] : init;
sum = new double[n];
// Initialise solution vectors. Use passed in initial vector, if present
if (init != null) {
for (i = 0; i < n; i++)
soln[i] = soln2[i] = target.get(i) ? 1.0 : init[i];
} else {
for (i = 0; i < n; i++)
soln[i] = soln2[i] = target.get(i) ? 1.0 : 0.0;
}
for (i = 0; i < n; i++)
sum[i] = 0.0;
// If necessary, do 0th element of summation (doesn't require any matrix powers)
if (left == 0)
for (i = 0; i < n; i++)
sum[i] += weights[0] * soln[i];
// Start iterations
iters = 1;
while (iters <= right) {
// Matrix-vector multiply and min/max ops
ctmdp.mvMultMinMax(soln, min, soln2, target, true, null);
// Since is globally uniform, can do this? and more?
for (i = 0; i < n; i++)
soln2[i] /= q;
// Store intermediate results if required
// TODO?
// Swap vectors for next iter
tmpsoln = soln;
soln = soln2;
soln2 = tmpsoln;
// Add to sum
if (iters >= left) {
for (i = 0; i < n; i++)
sum[i] += weights[iters - left] * soln[i];
}
iters++;
}
// Print vector (for debugging)
mainLog.println(sum);
// Finished bounded probabilistic reachability
timer = System.currentTimeMillis() - timer;
mainLog.print("Time-bounded probabilistic reachability (" + (min ? "min" : "max") + ")");
mainLog.println(" took " + iters + " iters and " + timer / 1000.0 + " seconds.");
// Return results
res = new ModelCheckerResult();
res.soln = sum;
res.lastSoln = soln2;
res.numIters = iters;
res.timeTaken = timer / 1000.0;
return res;
}
/**
* Simple test program.
*/
public static void main(String args[])
{
CTMDPModelChecker mc;
CTMDPSimple ctmdp;
ModelCheckerResult res;
BitSet target;
Map<String, BitSet> labels;
boolean min = true;
try {
mc = new CTMDPModelChecker(null);
ctmdp = new CTMDPSimple();
ctmdp.buildFromPrismExplicit(args[0]);
System.out.println(ctmdp);
labels = mc.loadLabelsFile(args[1]);
System.out.println(labels);
target = labels.get(args[2]);
if (target == null)
throw new PrismException("Unknown label \"" + args[2] + "\"");
for (int i = 4; i < args.length; i++) {
if (args[i].equals("-min"))
min = true;
else if (args[i].equals("-max"))
min = false;
else if (args[i].equals("-nopre"))
mc.setPrecomp(false);
}
res = mc.computeBoundedReachProbs(ctmdp, null, target, Double.parseDouble(args[3]), min, null, null);
System.out.println(res.soln[0]);
} catch (PrismException e) {
System.out.println(e);
}
}
}
| bharathk005/prism-4.2.1-src-teaser-patch | src/explicit/CTMDPModelChecker.java | Java | gpl-2.0 | 9,311 |
/*
Project: WhileInterpreter
Author: Gyorgy Rethy
Date: 2017.08.17.
--------------------------------------------------------------------------------
Descrpition: The object for lexical analysis.
*/
import java.io.*;
import java.util.*;
public class Lexer {
private BufferedReader reader;
private List<String> sourceFileTokens = new ArrayList<String>();
private List<Token> tokens = new ArrayList<Token>();
//empty constructor
public Lexer() {super();}
public Token[] tokens(String filepath) {
readFile(filepath);
enhanceSourceFileTokens();
createTokenList();
//printTokenList();
return tokens.toArray(new Token[0]);
} //tokens
private void readFile(String filepath) {
try {
reader = new BufferedReader(new FileReader(new File(filepath)));
String line = reader.readLine();
while(line != null) {
char[] characters = line.toCharArray();
String word = "";
for(char item : characters) {
switch(item) {
case ' ':
case '\t':
case '\n':
if(!word.equals("")) {
sourceFileTokens.add(word);
word = "";
}
break;
case '(':
case ')':
case '{':
case '}':
case ';':
case '+':
case '-':
case '*':
case '!':
case '=':
case '&':
case '|':
case '<':
if(!word.equals("")) {
sourceFileTokens.add(word);
word = "";
}
sourceFileTokens.add(Character.toString(item));
break;
default:
word += Character.toString(item);
} //switch
} //for
line = reader.readLine();
} //while
} //try
catch(IOException e) {
e.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
reader.close();
}
catch(IOException e) {
System.err.println("Could not close reader");
e.printStackTrace();
}
catch(Exception e) {
System.err.println("Could not close reader");
e.printStackTrace();
}
} //finally
} //readFile
private void enhanceSourceFileTokens() {
List<String> enhancedList = new ArrayList<String>();
//cast to array for easier access
String[] tokensNow = sourceFileTokens.toArray(new String[0]);
for(int i = 0; i < tokensNow.length; i++){
switch(tokensNow[i]) {
case ":":
case "<":
if(tokensNow[i+1].equals("=")) {
String wordToAdd = tokensNow[i] + "=";
enhancedList.add(wordToAdd);
i++;
} //if
break;
default:
enhancedList.add(tokensNow[i]);
break;
} //switch
} //for
sourceFileTokens = enhancedList;
}
//method to identify tokens and create a list from them
private void createTokenList() {
for(String item : sourceFileTokens) {
switch(item) {
case ":=":
tokens.add(new Token (item,TokenType.ASSIGNEMENT));
break;
case "skip":
tokens.add(new Token(item,TokenType.SKIP));
break;
case ";":
tokens.add(new Token(item,TokenType.SEMICOLON));
break;
case "(":
tokens.add(new Token(item,TokenType.OPAREN));
break;
case ")":
tokens.add(new Token(item,TokenType.CPAREN));
break;
case "{":
tokens.add(new Token(item,TokenType.LBRACE));
break;
case "}":
tokens.add(new Token(item,TokenType.RBRACE));
break;
case "if":
tokens.add(new Token(item,TokenType.IF));
break;
case "then":
tokens.add(new Token(item,TokenType.THEN));
break;
case "else":
tokens.add(new Token(item,TokenType.ELSE));
break;
case "while":
tokens.add(new Token(item,TokenType.WHILE));
break;
case "do":
tokens.add(new Token(item,TokenType.DO));
break;
case "print":
tokens.add(new Token(item,TokenType.PRINT));
break;
case "true":
tokens.add(new Token(item,TokenType.TRUE));
break;
case "false":
tokens.add(new Token(item,TokenType.FALSE));
break;
case "=":
tokens.add(new Token(item,TokenType.EQUAL));
break;
case "<":
tokens.add(new Token(item,TokenType.LESSTHAN));
break;
case "<=":
tokens.add(new Token(item,TokenType.LESSTHANOREQUAL));
break;
case "!":
tokens.add(new Token(item,TokenType.NOT));
break;
case "&":
tokens.add(new Token(item,TokenType.AND));
break;
case "|":
tokens.add(new Token(item,TokenType.OR));
break;
case "+":
tokens.add(new Token(item,TokenType.PLUS));
break;
case "-":
tokens.add(new Token(item,TokenType.MINUS));
break;
case "*":
tokens.add(new Token(item,TokenType.MULTIPLICATION));
break;
default:
if(isStringNumeric(item))
tokens.add(new Token(item,TokenType.INT));
else
tokens.add(new Token(item, TokenType.NAME));
break;
} //switch
} //for
} //createTokenList
//helper method for printing the tokens
private void printTokenList() {
for(String item : sourceFileTokens) {
System.out.println(item);
} //for
for(Token item : tokens) {
System.out.println(item);
}
} //printTokenList
private boolean isStringNumeric(String s) {
//nasty solution but using exceptions
boolean isNumber = true;
try {
int i = Integer.parseInt(s);
}
catch (NumberFormatException e) {
isNumber = false;
}
return isNumber;
}
} //Lexer | GyorgyR/WhileInterpreter | src/Lexer.java | Java | gpl-2.0 | 7,740 |
/*
* Copyright (C) 2008-2008 LeGACY <http://www.legacy-project.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <cstdlib>
#include "ObjectLifeTime.h"
namespace LeGACY
{
extern "C" void external_wrapper(void *p)
{
std::atexit( (void (*)())p );
}
void at_exit( void (*func)() )
{
external_wrapper((void*)func);
}
}
| PyroSamurai/legacy-project | src/framework/Policies/ObjectLifeTime.cpp | C++ | gpl-2.0 | 1,013 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_supperadmin
*
* @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* component model.
*
* @package Joomla.Administrator
* @subpackage com_supperadmin
* @since 1.6
*/
class supperadminModelplugin extends JModelAdmin
{
/**
* @var string The help screen key for the plugin.
* @since 1.6
*/
protected $helpKey = 'JHELP_pluginS_component_MANAGER_EDIT';
/**
* @var string The help screen base URL for the plugin.
* @since 1.6
*/
protected $helpURL;
/**
* @var array An array of cached component items.
* @since 1.6
*/
protected $_cache;
/**
* @var string The event to trigger after saving the data.
* @since 1.6
*/
protected $event_after_save = 'onpluginAfterSave';
/**
* @var string The event to trigger after before the data.
* @since 1.6
*/
protected $event_before_save = 'onpluginBeforeSave';
/**
* Method to get the record form.
*
* @param array $data Data for the form.
* @param boolean $loadData True if the form is to load its own data (default case), false if not.
*
* @return JForm A JForm object on success, false on failure
* @since 1.6
*/
public function getForm($data = array(), $loadData = true)
{
// The folder and element vars are passed when saving the form.
if (empty($data))
{
$item = $this->getItem();
$folder = $item->folder;
$element = $item->element;
}
else
{
$folder = JArrayHelper::getValue($data, 'folder', '', 'cmd');
$element = JArrayHelper::getValue($data, 'element', '', 'cmd');
}
// These variables are used to add data from the component XML files.
$this->setState('item.folder', $folder);
$this->setState('item.element', $element);
// Get the form.
$form = $this->loadForm('com_supperadmin.plugin', 'plugin', array('control' => 'jform', 'load_data' => $loadData));
if (empty($form))
{
return false;
}
// Modify the form based on access controls.
if (!$this->canEditState((object) $data))
{
// Disable fields for display.
$form->setFieldAttribute('ordering', 'disabled', 'true');
$form->setFieldAttribute('enabled', 'disabled', 'true');
// Disable fields while saving.
// The controller has already verified this is a record you can edit.
$form->setFieldAttribute('ordering', 'filter', 'unset');
$form->setFieldAttribute('enabled', 'filter', 'unset');
}
return $form;
}
function ajaxSaveForm($pks)
{
$input=JFactory::getApplication()->input;
$title=$input->get('title',array(),'array');
$table = $this->getTable();
$pks = (array) $pks;
foreach ($pks as $i => $pk)
{
if ($table->load($pk))
{
$table->name=$title[$pk];
$table->store();
}
}
// Clean the cache
$this->cleanCache();
// Ensure that previous checks doesn't empty the array
if (empty($pks))
{
return true;
}
}
/**
* Method to get the data that should be injected in the form.
*
* @return mixed The data for the form.
* @since 1.6
*/
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_supperadmin.edit.plugin.data', array());
if (empty($data))
{
$data = $this->getItem();
}
$this->preprocessData('com_supperadmin.plugin', $data);
return $data;
}
/**
* Method to duplicate plugins.
*
* @param array &$pks An array of primary key IDs.
*
* @return boolean True if successful.
*
* @since 1.6
* @throws Exception
*/
public function duplicate(&$pks)
{
$user = JFactory::getUser();
$db = $this->getDbo();
// Access checks.
if (!$user->authorise('core.create', 'com_supperadmin'))
{
throw new Exception(JText::_('JERROR_CORE_CREATE_NOT_PERMITTED'));
}
$table = $this->getTable();
foreach ($pks as $pk)
{
if ($table->load($pk, true))
{
echo "<pre>";
print_r($table);
echo "</pre>";
die;
// Reset the id to create a new record.
$table->id = 0;
// Alter the title.
$m = null;
if (preg_match('#\((\d+)\)$#', $table->name, $m))
{
$table->title = preg_replace('#\(\d+\)$#', '(' . ($m[1] + 1) . ')', $table->name);
}
else
{
$table->name .= ' (2)';
}
// Unpublish duplicate plugin
$table->published = 0;
if (!$table->check() || !$table->store())
{
throw new Exception($table->getError());
}
}
else
{
throw new Exception($table->getError());
}
}
// Clear plugins cache
$this->cleanCache();
return parent::duplicate($pks);
}
/**
* Method to delete rows.
*
* @param array &$pks An array of item ids.
*
* @return boolean Returns true on success, false on failure.
*
* @since 1.6
* @throws Exception
*/
public function delete(&$pks)
{
$pks = (array) $pks;
$user = JFactory::getUser();
$table = $this->getTable();
// Iterate the items to delete each one.
foreach ($pks as $pk)
{
if ($table->load($pk))
{
// Access checks.
if ($table->enabled != -2)
{
$this->setError('You cannot delete');
return false;
}
if($table->issystem)
{
$this->setError('you cannot delete plugin system');
return false;
}
if (!$table->delete($pk))
{
throw new Exception($table->getError());
}
// Clear plugin cache
}
else
{
throw new Exception($table->getError());
}
}
// Clear plugins cache
$this->cleanCache();
return true;
}
public function duplicateAndAssign(&$pks,$website_id=0)
{
$user = JFactory::getUser();
$db = $this->getDbo();
$tuples=array();
/* // Access checks.
if (!$user->authorise('core.create', 'com_plugin'))
{
throw new Exception(JText::_('JERROR_CORE_CREATE_NOT_PERMITTED'));
}*/
$table = $this->getTable();
foreach ($pks as $pk)
{
if ($table->load($pk, true))
{
// Reset the id to create a new record.
$table->id = 0;
$table->website_id = $website_id;
// Unpublish duplicate plugin
if (!$table->check() || !$table->store())
{
throw new Exception($table->getError());
}
}
else
{
throw new Exception($table->getError());
}
}
return true;
}
public function quick_assign_website(&$pks,$website_id)
{
$user = JFactory::getUser();
$db = $this->getDbo();
// Access checks.
if (!$user->authorise('core.create', 'com_supperadmin'))
{
throw new Exception(JText::_('JERROR_CORE_CREATE_NOT_PERMITTED'));
}
$table = $this->getTable();
foreach ($pks as $pk)
{
if ($table->load($pk, true))
{
$table->website_id=$website_id;
if (!$table->check() || !$table->store())
{
throw new Exception($table->getError());
}
}
else
{
throw new Exception($table->getError());
}
}
// Clear plugins cache
$this->cleanCache();
return true;
}
/**
* Method to get a single record.
*
* @param integer The id of the primary key.
*
* @return mixed Object on success, false on failure.
*/
public function getItem($pk = null)
{
$pk = (!empty($pk)) ? $pk : (int) $this->getState('plugin.id');
if (!isset($this->_cache[$pk]))
{
$false = false;
// Get a row instance.
$table = $this->getTable();
// Attempt to load the row.
$return = $table->load($pk);
// Check for a table object error.
if ($return === false && $table->getError())
{
$this->setError($table->getError());
return $false;
}
// Convert to the JObject before adding other data.
$properties = $table->getProperties(1);
$this->_cache[$pk] = JArrayHelper::toObject($properties, 'JObject');
// Convert the params field to an array.
$registry = new JRegistry;
$registry->loadString($table->params);
$this->_cache[$pk]->params = $registry->toArray();
// Get the plugin XML.
$path = JPath::clean(JPATH_ROOT . '/' . $table->folder . '/' . $table->element . '/' . $table->element . '.xml');
if (file_exists($path))
{
$this->_cache[$pk]->xml = simplexml_load_file($path);
}
else
{
$this->_cache[$pk]->xml = null;
}
}
return $this->_cache[$pk];
}
/**
* Returns a reference to the a Table object, always creating it.
*
* @param type The table type to instantiate
* @param string A prefix for the table class name. Optional.
* @param array Configuration array for model. Optional.
* @return JTable A database object
*/
public function getTable($type = 'supperadminplugin', $prefix = 'JTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
/**
* Auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* @return void
* @since 1.6
*/
protected function populateState()
{
// Execute the parent method.
parent::populateState();
$app = JFactory::getApplication('site');
// Load the User state.
$pk = $app->input->getInt('id');
$this->setState('plugin.id', $pk);
}
/**
* A protected method to get a set of ordering conditions.
*
* @param object A record object.
* @return array An array of conditions to add to add to ordering queries.
* @since 1.6
*/
protected function getReorderConditions($table)
{
$condition = array();
$condition[] = 'type = ' . $this->_db->quote($table->type);
$condition[] = 'folder = ' . $this->_db->quote($table->folder);
return $condition;
}
/**
* Get the necessary data to load an item help screen.
*
* @return object An object with key, url, and local properties for loading the item help screen.
* @since 1.6
*/
public function getHelp()
{
return (object) array('key' => $this->helpKey, 'url' => $this->helpURL);
}
/**
* Custom clean cache method, supperadmin are cached in 2 places for different clients
*
* @since 1.6
*/
protected function cleanCache($group = null, $client_id = 0)
{
parent::cleanCache('com_supperadmin');
}
}
| cuongnd/test_pro | components/website/website_supper_admin/com_supperadmin/models/plugin.php | PHP | gpl-2.0 | 11,622 |
<?php
if ($doc_per_canview == 0 || $doc_per_editcat == 0) {
?>
<table cellspacing='0' class='c1'>
<tr class='h'>
<td class='b h' colspan=2><?php echo $loc_no_access; ?></td>
<tr>
<td class='b n2'><center><h1><?php echo $loc_no_access; ?>.</h1><?php echo $loc_sorry; ?><br /><br /></center></td>
</table>
<?php
}
else {
$mysqli = new mysqli($hosty, $uname, $paswd, $dbnme);
$aid = (int) $_GET['aid'];
//$admin = htmlentities($_SESSION['username']['group'], ENT_QUOTES, 'UTF-8') <= 1;
//$owner = htmlentities($_SESSION['username']['username'], ENT_QUOTES, 'UTF-8');
$uid = $cookuid;//htmlentities($_SESSION['username']['id'], ENT_QUOTES, 'UTF-8');
$select = $mysqli->prepare("SELECT u.id, u.username, a.user_id FROM for_users AS u, for_announce AS a WHERE u.id = a.user_id AND a.id = ".$aid);
$select->execute();
$select->bind_result($uuid, $uuname, $auid);
$select->store_result();
while ($select->fetch()) {
$uuname = htmlspecialchars($uuname);
while (true) {
if (!$admin) {
header('Location: index.php');
exit();
break;
}
else {
if ($_POST['submit']) {
$title = $mysqli->real_escape_string($_POST['title']);
$message = $mysqli->real_escape_string(nl2br($_POST['message']));
$nolayout = cbx('nolayout');
$update = "UPDATE for_announce SET title = '$title', message = '$message', nolayout = $nolayout WHERE id = ".$aid;
$result = $mysqli->query($update);
echo "<table cellspacing='0' class='c1'>
<tr class='h'>
<td class='b h' colspan=2>$loc_edit_anno</td>
<tr>
<td class='b n2'><center>$loc_edited!<br /><a href=forum.php?page=announcement&aid=$aid>$loc_return</a></center></td>
</table>";
echo "<meta http-equiv='refresh' content='0; forum.php?page=announcement&aid=$aid' />";
if ($result) {
//$result->close();
$mysqli->close();
}
}
else {
$sql = "SELECT id, title, message FROM for_announce WHERE id = ".$aid;
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$stmt->bind_result($aaid, $atitle, $amessage);
while ($stmt->fetch()) {
?>
<table cellspacing="0" class="c1">
<form action="forum.php?page=editanno&aid=<?php echo $aid; ?>" method="post">
<tr class="h">
<td class="b h" colspan=2>$loc_edit_anno</td>
<tr>
<td class="b n1" align="center" width=120>$loc_title:</td>
<td class="b n2"><input type="text" name=title size=100 maxlength=100<?php echo " value='".htmlspecialchars($atitle, ENT_QUOTES)."'"; ?>></td>
<tr>
<td class="b n1" align="center" width=120>$loc_format:</td>
<td class="b n2"><?php include ("module/textbuttons.php"); ?></td>
<tr>
<td class="b n1" align="center">$loc_smilies:</td>
<td class="b n2"><?php include ("module/smilebuttons.php"); ?></td>
<tr>
<td class="b n1" align="center" width=120>$loc_message:</td>
<td class="b n2"><textarea wrap="virtual" name=message id='message' rows=20 cols=80><?php echo strbr($amessage); ?></textarea></td>
<tr>
<td class="b"> </td>
<td class="b">
<input name="submit" type="submit" value="$loc_edit" />
<input type="checkbox" name=nolayout id=nolayout value=1 ><label for=nolayout>$loc_dis_post_lay</label>
</td>
</form>
</table>
<?php
}
$stmt->close();
$mysqli->close();
}
}
break;
}
}
}
?>
| ArmyOfCoders/YamiBoard | docs/editanno.php | PHP | gpl-2.0 | 3,383 |
/*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2013 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:
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 Intel Corporation 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 INTEL OR
ITS 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.
END_LEGAL */
/*
* This tool mimics the behavior of TPSS on Linux by adding probes to various libc functions.
* However, in this tool these probes are merely empty wrappers that call the original functions.
* The objective of the test is to verify that probe generation and insertion don't cause Pin
* to crash.
*/
#include "pin.H"
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <sys/types.h>
#include <sys/timeb.h>
#include <rpc/rpc.h>
#include <rpc/pmap_clnt.h>
#include <semaphore.h>
#include <dlfcn.h>
#include <signal.h>
#include <poll.h>
#include <time.h>
#include <link.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/epoll.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/uio.h>
#include <sys/ioctl.h>
#include <sys/file.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/mman.h>
#include <stdio.h>
#include <string.h>
#include <wchar.h>
#include <sys/socket.h>
#include <sys/utsname.h>
#include <sched.h>
#include <time.h>
/* ===================================================================== */
/* Commandline Switches */
/* ===================================================================== */
typedef int * INT_PTR;
typedef void * VOID_PTR;
typedef char * CHAR_PTR;
ofstream OutFile;
KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool", "o", "tpss_lin_libc.txt",
"specify tool log file name");
/* ===================================================================== */
/* Utility functions */
/* ===================================================================== */
// Print help information
INT32 Usage() {
cerr
<< "This tool mimics the behavior of TPSS on Linux by adding probes to various libc functions."
<< endl;
cerr << KNOB_BASE::StringKnobSummary();
cerr << endl;
return 1;
}
// Utility function to return the time
string CurrentTime() {
char tmpbuf[128];
time_t thetime = time(NULL);
ctime_r(&thetime, tmpbuf);
return tmpbuf;
}
/* ===================================================================== */
/* Function signatures - these functions will be probed */
/* ===================================================================== */
int (*fptrnanosleep)(const struct timespec *__rqtp, struct timespec *__rmtp);
int (*fptrdl_iterate_phdr)(int (*__callback)(struct dl_phdr_info *__info, size_t __size,
VOID_PTR __data), VOID_PTR __data);
int (*fptrsystem)(const CHAR_PTR __command);
unsigned int (*fptralarm)(unsigned int __seconds);
ssize_t (*fptrrecvmsg)(int __socket, struct msghdr *__message, int __flags);
ssize_t (*fptrsendmsg)(int __sockfd, const struct msghdr *__msg, int __flags);
int (*fptrpause)(void);
int (*fptrsigtimedwait)(const sigset_t *__set, siginfo_t *__info, const struct timespec *__timeout);
int (*fptrsigwaitinfo)(const sigset_t *__set, siginfo_t *__info);
int (*fptrepoll_wait)(int __epfd, struct epoll_event *__events, int __maxevents,
int __timeout);
int (*fptrepoll_pwait)(int __epfd, struct epoll_event *__events,
int __maxevents, int __timeout, const sigset_t *__sigmask);
int (*fptrppoll)(struct pollfd *__fds, nfds_t __nfds,
const struct timespec *__timeout_ts, const sigset_t *__sigmask);
int (*fptrmsgsnd)(int __msqid, const VOID_PTR __msgp, size_t __msgsz, int __msgflg);
ssize_t (*fptrmsgrcv)(int __msqid, VOID_PTR __msgp, size_t __msgsz, long __msgtyp, int __msgflg);
int (*fptrsemop)(int __semid, struct sembuf *__sops, unsigned __nsops);
int (*fptrsemtimedop)(int __semid, struct sembuf *__sops);
int (*fptrusleep)(useconds_t __usec);
useconds_t (*fptrualarm)(useconds_t __usecs, useconds_t __interval);
int (*fptrgetitimer)(int __which, struct itimerval *__curr_value);
int (*fptrsigwait)(const sigset_t *__set, INT_PTR __sig);
int (*fptrmsgget)(key_t __key, int __msgflg);
int (*fptrsemget)(key_t __key, int __nsems, int __semflg);
pid_t (*fptrwait)(INT_PTR __status);
pid_t (*fptrwaitpid)(pid_t __pid, INT_PTR __atus, int __options);
int (*fptrwaitid)(idtype_t __idtype, id_t __id, siginfo_t *__infop,int __options);
pid_t (*fptrwait3)(INT_PTR __status, int __options, struct rusage *__rusage);
pid_t (*fptrwait4)(pid_t __pid, INT_PTR status, int __options, struct rusage *__rusage);
ssize_t (*fptrreadv)(int __fd, const struct iovec *__iov, int __iovcnt);
ssize_t (*fptrwritev)(int __fd, const struct iovec *__iov, int __iovcnt);
int (*fptrflock)(int __fd, int __operation);
void (*fptrflockfile)(FILE *__filehandle);
void (*fptrfunlockfile)(FILE *__filehandle);
int (*fptrlockf)(int __fd, int __cmd, off_t __len);
int (*fptrsetenv)(const CHAR_PTR __name, const CHAR_PTR __value, int __overwrite);
int (*fptrunsetenv)(const CHAR_PTR __name);
CHAR_PTR (*fptrgetenv)(const CHAR_PTR __name);
void (*fptrperror)(const CHAR_PTR __s);
VOID_PTR (*fptrmmap)(VOID_PTR __addr, size_t __len, int __prot, int __flags,
int __fildes, off_t __off);
int (*fptrmunmap)(VOID_PTR __addr, size_t __len);
int (*fptrfileno)(FILE *__stream);
pid_t (*fptrgetpid)(void);
pid_t (*fptrgetppid)(void);
VOID_PTR (*fptrmemset)(VOID_PTR __s, int __c, size_t __n);
VOID_PTR (*fptrmemcpy)(VOID_PTR __dest, const VOID_PTR __src, size_t __n);
int (*fptraccess)(const CHAR_PTR __pathname, int __mode);
off_t (*fptrlseek)(int __fd, off_t __offset, int __whence);
off64_t (*fptrlseek64)(int __fd, off64_t __offset, int __whence);
int (*fptrfdatasync)(int __fd);
int (*fptrunlink)(const CHAR_PTR __pathname);
size_t (*fptrstrlen)(const CHAR_PTR __s);
size_t (*fptrwcslen)(const wchar_t *__s);
CHAR_PTR (*fptrstrcpy)(CHAR_PTR __dest, const CHAR_PTR __src);
CHAR_PTR (*fptrstrncpy)(CHAR_PTR __dest, const CHAR_PTR __src, size_t __n);
CHAR_PTR (*fptrstrcat)(CHAR_PTR __dest, const CHAR_PTR __src);
CHAR_PTR (*fptrstrstr)(const CHAR_PTR __haystack, const CHAR_PTR __needle);
CHAR_PTR (*fptrstrchr0)(const CHAR_PTR __s, int __c);
CHAR_PTR (*fptrstrrchr)(const CHAR_PTR __s, int __c);
int (*fptrstrcmp)(const CHAR_PTR __s1, const CHAR_PTR __s2);
int (*fptrstrncmp)(const CHAR_PTR __s1, const CHAR_PTR __s2, size_t __n);
int (*fptrsigaddset)(sigset_t *__set, int __signum);
int (*fptrsigdelset)(sigset_t *__set, int __signum);
int (*fptrsigismember)(const sigset_t *__set, int __signum);
CHAR_PTR (*fptrstrerror)(int __errnum);
int (*fptrbind)(int __sockfd, const struct sockaddr *__addr, socklen_t __addrlen);
int (*fptrlisten)(int __sockfd, int __backlog);
int (*fptruname)(struct utsname *__name);
int (*fptrgethostname)(CHAR_PTR __name, size_t __len);
int (*fptrkill)(pid_t __pid, int __sig);
int (*fptrsched_yield)(void);
int (*fptrtimer_settime)(timer_t __timerid, int __flags, const struct itimerspec * __value, struct itimerspec * __ovalue);
int (*fptrsigaltstack)(const stack_t *__ss, stack_t *__oss);
int (*fptrshutdown)(int, int);
int (*fptrsleep)(unsigned int);
int (*fptrsocket)(int, int, int);
int (*fptrselect)(int, fd_set *__restrict, fd_set *__restrict, fd_set *__restrict, struct timeval *__restrict);
int (*fptrpoll)(struct pollfd *, nfds_t, int);
int (*fptraccept)(int, __SOCKADDR_ARG, socklen_t *__restrict);
int (*fptrconnect)(int, __CONST_SOCKADDR_ARG, socklen_t);
ssize_t (*fptrrecv)(int, VOID_PTR , size_t, int);
ssize_t (*fptrrecvfrom)(int, VOID_PTR __restrict, size_t, int, __SOCKADDR_ARG, socklen_t *__restrict);
ssize_t (*fptrsend)(int, __const VOID_PTR , size_t, int);
wint_t (*fptrgetwc)(__FILE *);
int (*fptrsetitimer)(__itimer_which_t, __const struct itimerval *__restrict, struct itimerval *__restrict);
int (*fptrsigpending)(sigset_t *);
int (*fptrsigaction)(int, __const struct sigaction *__restrict, struct sigaction *__restrict);
__sighandler_t (*fptrsignal)(int, __sighandler_t);
void (*fptrabort)();
ssize_t (*fptrsendto)(int, __const VOID_PTR , size_t, int, __CONST_SOCKADDR_ARG, socklen_t);
int (*fptr_IO_getc)(FILE *);
int (*fptrgetchar)();
wint_t (*fptrgetwchar)();
CHAR_PTR (*fptrgets)(CHAR_PTR );
CHAR_PTR (*fptrfgets)(CHAR_PTR __restrict, int, FILE *__restrict);
wint_t (*fptrfgetwc)(__FILE *);
size_t (*fptrfread)(VOID_PTR __restrict, size_t, size_t, FILE *__restrict);
size_t (*fptrfwrite)(__const VOID_PTR __restrict, size_t, size_t, FILE *__restrict);
int (*fptropen)(__const CHAR_PTR , int, mode_t);
int (*fptrgetw)(FILE *);
void (*fptrfgetc)(__FILE *);
wchar_t * (*fptrfgetws)(wchar_t *__restrict, int, __FILE *__restrict);
int (*fptrpipe)(int[2]);
ssize_t (*fptrread)(int, VOID_PTR , size_t);
ssize_t (*fptrwrite)(int, __const VOID_PTR , size_t);
FILE * (*fptrfopen)(__const CHAR_PTR __restrict, __const CHAR_PTR __restrict);
FILE * (*fptrfdopen)(int, __const CHAR_PTR );
int (*fptrclose)(int);
int (*fptrfclose)(FILE *);
int (*fptrcallrpc)(__const CHAR_PTR , u_long, u_long, u_long, xdrproc_t, __const CHAR_PTR , xdrproc_t, CHAR_PTR );
enum clnt_stat (*fptrclnt_broadcast)(u_long, u_long, u_long, xdrproc_t, caddr_t,
xdrproc_t, caddr_t, resultproc_t);
CLIENT * (*fptrclntudp_create)(struct sockaddr_in *, u_long, u_long, struct timeval, INT_PTR );
CLIENT * (*fptrclntudp_bufcreate)(struct sockaddr_in *, u_long, u_long, struct timeval, INT_PTR , u_int, u_int);
struct pmaplist * (*fptrpmap_getmaps)(struct sockaddr_in *);
u_short (*fptrpmap_getport)(struct sockaddr_in *, u_long, u_long, u_int);
enum clnt_stat (*fptrpmap_rmtcall)(struct sockaddr_in *, u_long, u_long, u_long, xdrproc_t, caddr_t, xdrproc_t, caddr_t, struct timeval, u_long *);
bool_t (*fptrpmap_set)(u_long, u_long, int, u_short);
CLIENT * (*fptrclntraw_create)(u_long, u_long);
void (*fptrsvc_run)();
bool_t (*fptrsvc_sendreply)(SVCXPRT *, xdrproc_t, caddr_t);
SVCXPRT * (*fptrsvcraw_create)();
SVCXPRT * (*fptrsvctcp_create)(int, u_int, u_int);
SVCXPRT * (*fptrsvcudp_bufcreate)(int, u_int, u_int);
SVCXPRT * (*fptrsvcudp_create)(int);
void (*fptr_exit)(int);
int (*fptrsigprocmask)(int, __const sigset_t *__restrict, sigset_t *__restrict);
void (*fptrexit)(int);
int (*fptrpselect)(int, fd_set *__restrict, fd_set *__restrict, fd_set *__restrict,
const struct timespec *__restrict, const __sigset_t *__restrict);
int (*fptrioctl)(int __d, int __request, CHAR_PTR __argp);
int (*fptrfcntl)(int __fd, int __cmd, VOID_PTR __argp);
VOID_PTR (*fptr__libc_dlopen_mode)(const CHAR_PTR __name, int __mode);
INT_PTR (*fptr__errno_location)(void);
int (*fptrsyscall)(int __number, long int __arg1, long int __arg2, long int __arg3,
long int __arg4, long int __arg5, long int __arg6, long int __arg7);
/* ===================================================================== */
/* Probes - implementation of the wrapper functions */
/* ===================================================================== */
int mynanosleep(const struct timespec *__rqtp, struct timespec *__rmtp)
{
OutFile << CurrentTime() << "mynanosleep called " << endl;
OutFile.flush();
int res = fptrnanosleep(__rqtp, __rmtp);
return res;
}
int mydl_iterate_phdr(
int (*__callback)(struct dl_phdr_info *__info, size_t __size,
VOID_PTR __data), VOID_PTR __sec_data)
{
OutFile << CurrentTime() << "mydl_iterate_phdr called " << endl;
OutFile.flush();
int res = fptrdl_iterate_phdr((__callback), __sec_data);
return res;
}
int mysystem(const CHAR_PTR __command)
{
OutFile << CurrentTime() << "mysystem called " << endl;
OutFile.flush();
int res = fptrsystem(__command);
return res;
}
unsigned int myalarm(unsigned int __seconds)
{
OutFile << CurrentTime() << "myalarm called " << endl;
OutFile.flush();
unsigned int res = fptralarm(__seconds);
return res;
}
ssize_t myrecvmsg(int __socket, struct msghdr *__message, int __flags)
{
OutFile << CurrentTime() << "myrecvmsg called " << endl;
OutFile.flush();
ssize_t res = fptrrecvmsg(__socket, __message, __flags);
return res;
}
ssize_t mysendmsg(int __sockfd, const struct msghdr *__msg, int __flags)
{
OutFile << CurrentTime() << "mysendmsg called " << endl;
OutFile.flush();
ssize_t res = fptrsendmsg(__sockfd, __msg, __flags);
return res;
}
int mypause(void)
{
OutFile << CurrentTime() << "mypause called " << endl;
OutFile.flush();
int res = fptrpause();
return res;
}
int mysigtimedwait(const sigset_t *__set, siginfo_t *__info,
const struct timespec *__timeout)
{
OutFile << CurrentTime() << "mysigtimedwait called " << endl;
OutFile.flush();
int res = fptrsigtimedwait(__set, __info, __timeout);
return res;
}
int mysigwaitinfo(const sigset_t *__set, siginfo_t *__info)
{
OutFile << CurrentTime() << "mysigwaitinfo called " << endl;
OutFile.flush();
int res = fptrsigwaitinfo(__set, __info);
return res;
}
int myepoll_wait(int __epfd, struct epoll_event *__events, int __maxevents,
int __timeout)
{
OutFile << CurrentTime() << "myepoll_wait called " << endl;
OutFile.flush();
int res = fptrepoll_wait(__epfd, __events, __maxevents, __timeout);
return res;
}
int myepoll_pwait(int __epfd, struct epoll_event *__events, int __maxevents,
int __timeout)
{
OutFile << CurrentTime() << "myepoll_pwait called " << endl;
OutFile.flush();
int res = fptrepoll_wait(__epfd, __events, __maxevents, __timeout);
return res;
}
int myppoll(struct pollfd *__fds, nfds_t __nfds,
const struct timespec *__timeout_ts, const sigset_t *__sigmask)
{
OutFile << CurrentTime() << "myppoll called " << endl;
OutFile.flush();
int res = fptrppoll(__fds, __nfds, __timeout_ts, __sigmask);
return res;
}
int mymsgsnd(int __msqid, const VOID_PTR __msgp, size_t __msgsz, int __msgflg)
{
OutFile << CurrentTime() << "mymsgsnd called " << endl;
OutFile.flush();
int res = fptrmsgsnd(__msqid, __msgp, __msgsz, __msgflg);
return res;
}
ssize_t mymsgrcv(int __msqid, VOID_PTR __msgp, size_t __msgsz, long __msgtyp,
int __msgflg)
{
OutFile << CurrentTime() << "mymsgrcv called " << endl;
OutFile.flush();
ssize_t res = fptrmsgrcv(__msqid, __msgp, __msgsz, __msgtyp, __msgflg);
return res;
}
int mysemtimedop(int __semid, struct sembuf *__sops)
{
OutFile << CurrentTime() << "mysemtimedop called " << endl;
OutFile.flush();
int res = fptrsemtimedop(__semid, __sops);
return res;
}
int myusleep(useconds_t __usecs)
{
OutFile << CurrentTime() << "myusleep called " << endl;
OutFile.flush();
int res = fptrusleep(__usecs);
return res;
}
useconds_t myualarm(useconds_t __usecs, useconds_t __interval)
{
OutFile << CurrentTime() << "myualarm called " << endl;
OutFile.flush();
useconds_t res = fptrualarm(__usecs, __interval);
return res;
}
int mygetitimer(int __which, struct itimerval *__curr_value)
{
OutFile << CurrentTime() << "mygetitimer called " << endl;
OutFile.flush();
int res = fptrgetitimer(__which, __curr_value);
return res;
}
int mysigwait(const sigset_t *__set, INT_PTR __sig)
{
OutFile << CurrentTime() << "mysigwait called " << endl;
OutFile.flush();
int res = fptrsigwait(__set, __sig);
return res;
}
int mymsgget(key_t __key, int __msgflg)
{
OutFile << CurrentTime() << "mymsgget called " << endl;
OutFile.flush();
int res = fptrmsgget(__key, __msgflg);
return res;
}
int mysemget(key_t __key, int __nsems, int __semflg)
{
OutFile << CurrentTime() << "mysemget called " << endl;
OutFile.flush();
int res = fptrsemget(__key, __nsems, __semflg);
return res;
}
pid_t mywaitpid(pid_t __pid, INT_PTR __status, int __options)
{
OutFile << CurrentTime() << "mywaitpid called " << endl;
OutFile.flush();
pid_t res = fptrwaitpid(__pid, __status, __options);
return res;
}
int mywaitid(idtype_t __idtype, id_t __id, siginfo_t *__infop, int __options)
{
OutFile << CurrentTime() << "mywaittid called " << endl;
OutFile.flush();
int res = fptrwaitid(__idtype, __id, __infop, __options);
return res;
}
pid_t mywait3(INT_PTR __status, int __options, struct rusage *__rusage)
{
OutFile << CurrentTime() << "mywait3 called " << endl;
OutFile.flush();
pid_t res = fptrwait3(__status, __options, __rusage);
return res;
}
pid_t mywait4(pid_t __pid, INT_PTR __status, int __options,
struct rusage *__rusage)
{
OutFile << CurrentTime() << "mywait4 called " << endl;
OutFile.flush();
pid_t res = fptrwait4(__pid, __status, __options, __rusage);
return res;
}
ssize_t myreadv(int __fd, const struct iovec *__iov, int __iovcnt)
{
OutFile << CurrentTime() << "myreadv called " << endl;
OutFile.flush();
ssize_t res = fptrreadv(__fd, __iov, __iovcnt);
return res;
}
ssize_t mywritev(int __fd, const struct iovec *__iov, int __iovcnt)
{
OutFile << CurrentTime() << "mywritev called " << endl;
OutFile.flush();
ssize_t res = fptrwritev(__fd, __iov, __iovcnt);
return res;
}
int myflock(int __fd, int __operation)
{
OutFile << CurrentTime() << "myflock called " << endl;
OutFile.flush();
int res = fptrflock(__fd, __operation);
return res;
}
void myflockfile(FILE *__filehandle)
{
OutFile << CurrentTime() << "myflockfile called " << endl;
OutFile.flush();
fptrflockfile(__filehandle);
}
void myfunlockfile(FILE *__filehandle)
{
OutFile << CurrentTime() << "myfunlockfile called " << endl;
OutFile.flush();
fptrfunlockfile(__filehandle);
}
int mylockf(int __fd, int __cmd, off_t __len)
{
OutFile << CurrentTime() << "mylockf called " << endl;
OutFile.flush();
int res = fptrlockf(__fd, __cmd, __len);
return res;
}
int mysetenv(const CHAR_PTR __name, const CHAR_PTR __value, int __overwrite)
{
OutFile << CurrentTime() << "mysetenv called " << endl;
OutFile.flush();
int res = fptrsetenv(__name, __value, __overwrite);
return res;
}
int myunsetenv(const CHAR_PTR __name)
{
OutFile << CurrentTime() << "myunsetenv called " << endl;
OutFile.flush();
int res = fptrunsetenv(__name);
return res;
}
CHAR_PTR mygetenv(const CHAR_PTR __name)
{
OutFile << CurrentTime() << "mygetenv called " << endl;
OutFile.flush();
CHAR_PTR res = fptrgetenv(__name);
return res;
}
void myperror(const CHAR_PTR __s)
{
OutFile << CurrentTime() << "myperrorcalled " << endl;
OutFile.flush();
fptrperror(__s);
}
VOID_PTR mymmap(VOID_PTR __addr, size_t __len, int __prot, int __flags, int __fildes,
off_t __off)
{
OutFile << CurrentTime() << "mymmap called " << endl;
OutFile.flush();
VOID_PTR res = fptrmmap(__addr, __len, __prot, __flags, __fildes, __off);
return res;
}
int mymunmap(VOID_PTR __addr, size_t __len)
{
OutFile << CurrentTime() << "mymunmap called " << endl;
OutFile.flush();
int res = fptrmunmap(__addr, __len);
return res;
}
int myfileno(FILE *__stream)
{
OutFile << CurrentTime() << "myfileno called " << endl;
OutFile.flush();
int res = fptrfileno(__stream);
return res;
}
pid_t mygetpid(void)
{
OutFile << CurrentTime() << "mygetpid called " << endl;
OutFile.flush();
pid_t res = fptrgetpid();
return res;
}
pid_t mygetppid(void)
{
OutFile << CurrentTime() << "mygetppid called " << endl;
OutFile.flush();
pid_t res = fptrgetppid();
return res;
}
VOID_PTR mymemset(VOID_PTR __s, int __c, size_t __n) {
OutFile << CurrentTime() << "mymemset called " << endl;
OutFile.flush();
VOID_PTR res = fptrmemset(__s, __c, __n);
return res;
}
VOID_PTR mymemcpy(VOID_PTR __dest, const VOID_PTR __src, size_t __n)
{
OutFile << CurrentTime() << "mymemcpy called " << endl;
OutFile.flush();
VOID_PTR res = fptrmemcpy(__dest, __src, __n);
return res;
}
int myaccess(const CHAR_PTR __pathname, int __mode)
{
OutFile << CurrentTime() << "myaccess called " << endl;
OutFile.flush();
int res = fptraccess(__pathname, __mode);
return res;
}
off_t mylseek(int __fd, off_t __offset, int __whence)
{
OutFile << CurrentTime() << "mylseek called " << endl;
OutFile.flush();
off_t res = fptrlseek(__fd, __offset, __whence);
return res;
}
off64_t mylseek64(int __fd, off64_t __offset, int __whence)
{
OutFile << CurrentTime() << "mylseek64 called " << endl;
OutFile.flush();
off64_t res = fptrlseek64(__fd, __offset, __whence);
return res;
}
int myfdatasync(int __fd) {
OutFile << CurrentTime() << "myfdatasync called " << endl;
OutFile.flush();
int res = fptrfdatasync(__fd);
return res;
}
int myunlink(const CHAR_PTR __pathname)
{
OutFile << CurrentTime() << "myunlink called " << endl;
OutFile.flush();
int res = fptrunlink(__pathname);
return res;
}
size_t mystrlen(const CHAR_PTR __s)
{
OutFile << CurrentTime() << "mystrlen called " << endl;
OutFile.flush();
size_t res = fptrstrlen(__s);
return res;
}
size_t mywcslen(const wchar_t *__s)
{
OutFile << CurrentTime() << "mywcslen called " << endl;
OutFile.flush();
size_t res = fptrwcslen(__s);
return res;
}
CHAR_PTR mystrcpy(CHAR_PTR __dest, const CHAR_PTR __src)
{
OutFile << CurrentTime() << "mystrcpy called " << endl;
OutFile.flush();
CHAR_PTR res = fptrstrcpy(__dest, __src);
return res;
}
CHAR_PTR mystrncpy(CHAR_PTR __dest, const CHAR_PTR __src, size_t __n)
{
OutFile << CurrentTime() << "mystrncpy called " << endl;
OutFile.flush();
CHAR_PTR res = fptrstrncpy(__dest, __src, __n);
return res;
}
CHAR_PTR mystrcat(CHAR_PTR __dest, const CHAR_PTR __src)
{
OutFile << CurrentTime() << "mystrcat called " << endl;
OutFile.flush();
CHAR_PTR res = fptrstrcat(__dest, __src);
return res;
}
CHAR_PTR mystrstr(const CHAR_PTR __haystack, const CHAR_PTR __needle)
{
OutFile << CurrentTime() << "mystrstr called " << endl;
OutFile.flush();
CHAR_PTR res = fptrstrstr(__haystack, __needle);
return res;
}
CHAR_PTR mystrchr0(const CHAR_PTR __s, int __c)
{
OutFile << CurrentTime() << "mystrchr0 called " << endl;
OutFile.flush();
CHAR_PTR res = fptrstrchr0(__s, __c);
return res;
}
CHAR_PTR mystrrchr(const CHAR_PTR __s, int __c)
{
OutFile << CurrentTime() << "mystrrchr called " << endl;
OutFile.flush();
CHAR_PTR res = fptrstrrchr(__s, __c);
return res;
}
int mystrcmp(const CHAR_PTR __s1, const CHAR_PTR __s2)
{
OutFile << CurrentTime() << "mystrcmp called " << endl;
OutFile.flush();
int res = fptrstrcmp(__s1, __s2);
return res;
}
int mystrncmp(const CHAR_PTR __s1, const CHAR_PTR __s2, size_t __n)
{
OutFile << CurrentTime() << "mystrncmp called " << endl;
OutFile.flush();
int res = fptrstrncmp(__s1, __s2, __n);
return res;
}
int mysigaddset(sigset_t *__set, int __signum)
{
OutFile << CurrentTime() << "mysigaddset called " << endl;
OutFile.flush();
int res = fptrsigaddset(__set, __signum);
return res;
}
int mysigdelset(sigset_t *__set, int __signum) {
OutFile << CurrentTime() << "mysigdelset called " << endl;
OutFile.flush();
int res = fptrsigdelset(__set, __signum);
return res;
}
int mysigismember(sigset_t *__set, int __signum)
{
OutFile << CurrentTime() << "mysigismember called " << endl;
OutFile.flush();
int res = fptrsigismember(__set, __signum);
return res;
}
CHAR_PTR mystrerror(int __errnum)
{
OutFile << CurrentTime() << "mystrerror called " << endl;
OutFile.flush();
CHAR_PTR res = fptrstrerror(__errnum);
return res;
}
int mybind(int __sockfd, const struct sockaddr *__addr, socklen_t __addrlen)
{
OutFile << CurrentTime() << "mybind called " << endl;
OutFile.flush();
int res = fptrbind(__sockfd, __addr, __addrlen);
return res;
}
int mylisten(int __sockfd, int __backlog)
{
OutFile << CurrentTime() << "mylisten called " << endl;
OutFile.flush();
int res = fptrlisten(__sockfd, __backlog);
return res;
}
int myuname(struct utsname *__name)
{
OutFile << CurrentTime() << "myuname called " << endl;
OutFile.flush();
int res = fptruname(__name);
return res;
}
int mygethostname(CHAR_PTR __name, size_t __len)
{
OutFile << CurrentTime() << "mygethostname called " << endl;
OutFile.flush();
int res = fptrgethostname(__name, __len);
return res;
}
int mykill(pid_t __pid, int __sig)
{
OutFile << CurrentTime() << "mykill called " << endl;
OutFile.flush();
int res = fptrkill(__pid, __sig);
return res;
}
int mysched_yield(void)
{
OutFile << CurrentTime() << "mysched_yield called " << endl;
OutFile.flush();
int res = fptrsched_yield();
return res;
}
int mytimer_settime(timer_t __timerid, int __flags,
const struct itimerspec * __value, struct itimerspec * __ovalue)
{
OutFile << CurrentTime() << "mytimer_settime called " << endl;
OutFile.flush();
int res = fptrtimer_settime(__timerid, __flags, __value, __ovalue);
return res;
}
int mysigaltstack(const stack_t *__ss, stack_t *__oss)
{
OutFile << CurrentTime() << "mysigaltstacke called " << endl;
OutFile.flush();
int res = fptrsigaltstack(__ss, __oss);
return res;
}
int mysleep(unsigned int __seconds)
{
OutFile << CurrentTime() << "mysleep called " << endl;
OutFile.flush();
int res = fptrsleep(__seconds);
return res;
}
int mysocket(int __domain, int __type, int __protocol)
{
OutFile << CurrentTime() << "mysocket called " << endl;
OutFile.flush();
int res = fptrsocket(__domain, __type, __protocol);
return res;
}
int myshutdown(int __fd, int __how)
{
OutFile << CurrentTime() << "myshutdown called " << endl;
OutFile.flush();
int res = fptrshutdown(__fd, __how);
return res;
}
int myselect(int __nfds, fd_set *__restrict __readfds,
fd_set *__restrict __writefds, fd_set *__restrict __exceptfds,
struct timeval *__restrict __timeout)
{
OutFile << CurrentTime() << "myselect called " << endl;
OutFile.flush();
int res = fptrselect(__nfds, __readfds, __writefds, __exceptfds, __timeout);
return res;
}
int mypoll(struct pollfd * __fds, nfds_t __nfds, int __timeout)
{
OutFile << CurrentTime() << "mypoll called " << endl;
OutFile.flush();
int res = fptrpoll(__fds, __nfds, __timeout);
return res;
}
int myaccept(int __fd, __SOCKADDR_ARG __addr,
socklen_t *__restrict __addr_len)
{
OutFile << CurrentTime() << "myaccept called " << endl;
OutFile.flush();
int res = fptraccept(__fd, __addr, __addr_len);
return res;
}
int myconnect(int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len)
{
OutFile << CurrentTime() << "myconnect called " << endl;
OutFile.flush();
int res = fptrconnect(__fd, __addr, __len);
return res;
}
ssize_t myrecv(int __fd, VOID_PTR __buf, size_t __n, int __flags)
{
OutFile << CurrentTime() << "myrecv called " << endl;
OutFile.flush();
ssize_t res = fptrrecv(__fd, __buf, __n, __flags);
return res;
}
ssize_t myrecvfrom(int __fd, VOID_PTR __restrict __buf, size_t __n, int __flags,
__SOCKADDR_ARG __addr, socklen_t *__restrict __addr_len)
{
OutFile << CurrentTime() << "myrecvfrom called " << endl;
OutFile.flush();
ssize_t res = fptrrecvfrom(__fd, __buf, __n, __flags, __addr, __addr_len);
return res;
}
ssize_t mysend(int __fd, __const VOID_PTR __buf, size_t __n, int __flags)
{
OutFile << CurrentTime() << "mysend called " << endl;
OutFile.flush();
ssize_t res = fptrsend(__fd, __buf, __n, __flags);
return res;
}
wint_t mygetwc(__FILE * __stream)
{
OutFile << CurrentTime() << "mygetwc called " << endl;
OutFile.flush();
wint_t res = fptrgetwc(__stream);
return res;
}
void myexit(int __status)
{
OutFile << CurrentTime() << "myexit called " << endl;
OutFile.flush();
fptrexit(__status);
}
int mysetitimer(__itimer_which_t __which, __const
struct itimerval *__restrict __new,
struct itimerval *__restrict __old)
{
OutFile << CurrentTime() << "mysetitimer called " << endl;
OutFile.flush();
int res = fptrsetitimer(__which, __new, __old);
return res;
}
int mysigpending(sigset_t * __set)
{
OutFile << CurrentTime() << "mysigpending called " << endl;
OutFile.flush();
int res = fptrsigpending(__set);
return res;
}
__sighandler_t mysignal(int __sig, __sighandler_t __handler)
{
OutFile << CurrentTime() << "mysignal called " << endl;
OutFile.flush();
__sighandler_t res = fptrsignal(__sig, __handler);
return res;
}
void myabort()
{
OutFile << CurrentTime() << "myabort called " << endl;
OutFile.flush();
fptrabort();
}
int myclose(int __fd)
{
OutFile << CurrentTime() << "myclose called " << endl;
OutFile.flush();
int res = fptrclose(__fd);
return res;
}
ssize_t mysendto(int __fd, __const VOID_PTR __buf, size_t __n, int __flags,
__CONST_SOCKADDR_ARG __addr, socklen_t __addr_len)
{
OutFile << CurrentTime() << "mysendto called " << endl;
OutFile.flush();
ssize_t res = fptrsendto(__fd, __buf, __n, __flags, __addr, __addr_len);
return res;
}
int my_IO_getc(FILE * __stream)
{
OutFile << CurrentTime() << "my_IO_getc called " << endl;
OutFile.flush();
int res = fptr_IO_getc(__stream);
return res;
}
int mygetchar()
{
OutFile << CurrentTime() << "mygetchar called " << endl;
OutFile.flush();
int res = fptrgetchar();
return res;
}
wint_t mygetwchar()
{
OutFile << CurrentTime() << "mygetwchar called " << endl;
OutFile.flush();
wint_t res = fptrgetwchar();
return res;
}
CHAR_PTR mygets(CHAR_PTR __s)
{
OutFile << CurrentTime() << "mygets called " << endl;
OutFile.flush();
CHAR_PTR res = fptrgets(__s);
return res;
}
CHAR_PTR myfgets(CHAR_PTR __restrict __s, int __n, FILE *__restrict __stream)
{
OutFile << CurrentTime() << "myfgets called " << endl;
OutFile.flush();
CHAR_PTR res = fptrfgets(__s, __n, __stream);
return res;
}
wint_t myfgetwc(__FILE * __stream)
{
OutFile << CurrentTime() << "myfgetwc called " << endl;
OutFile.flush();
wint_t res = fptrfgetwc(__stream);
return res;
}
size_t myfread(VOID_PTR __restrict __ptr, size_t __size, size_t __n,
FILE *__restrict __stream)
{
OutFile << CurrentTime() << "myfread called " << endl;
OutFile.flush();
size_t res = fptrfread(__ptr, __size, __n, __stream);
return res;
}
size_t myfwrite(__const VOID_PTR __restrict __ptr, size_t __size, size_t __n,
FILE *__restrict __s)
{
OutFile << CurrentTime() << "myfwrite called " << endl;
OutFile.flush();
size_t res = fptrfwrite(__ptr, __size, __n, __s);
return res;
}
int myopen(__const CHAR_PTR __file, int __flags, mode_t __mode)
{
OutFile << CurrentTime() << "myopen called " << endl;
OutFile.flush();
int res = fptropen(__file, __flags, __mode);
return res;
}
int mygetw(FILE * __stream)
{
OutFile << CurrentTime() << "mygetw called " << endl;
OutFile.flush();
int res = fptrgetw(__stream);
return res;
}
void myfgetc(__FILE * __stream)
{
OutFile << CurrentTime() << "myfgetc called " << endl;
OutFile.flush();
fptrfgetc(__stream);
}
wchar_t * myfgetws(wchar_t *__restrict __ws, int __n,
__FILE *__restrict __stream)
{
OutFile << CurrentTime() << "myfgetws called " << endl;
OutFile.flush();
wchar_t * res = fptrfgetws(__ws, __n, __stream);
return res;
}
int mypipe(int* __pipedes)
{
OutFile << CurrentTime() << "mypipe called " << endl;
OutFile.flush();
int res = fptrpipe(__pipedes);
return res;
}
ssize_t myread(int __fd, VOID_PTR __buf, size_t __nbytes)
{
OutFile << CurrentTime() << "myread called " << endl;
OutFile.flush();
ssize_t res = fptrread(__fd, __buf, __nbytes);
return res;
}
ssize_t mywrite(int __fd, __const VOID_PTR __buf, size_t __n)
{
OutFile << CurrentTime() << "mywrite called " << endl;
OutFile.flush();
ssize_t res = fptrwrite(__fd, __buf, __n);
return res;
}
FILE * myfopen(__const CHAR_PTR __restrict __filename,
__const CHAR_PTR __restrict __modes)
{
OutFile << CurrentTime() << "myfopen called " << endl;
OutFile.flush();
FILE * res = fptrfopen(__filename, __modes);
return res;
}
FILE * myfdopen(int __fd, __const CHAR_PTR __modes)
{
OutFile << CurrentTime() << "myfdopen called " << endl;
OutFile.flush();
FILE * res = fptrfdopen(__fd, __modes);
return res;
}
int mycallrpc(__const CHAR_PTR __host, u_long __prognum, u_long __versnum,
u_long __procnum, xdrproc_t __inproc, __const CHAR_PTR __in,
xdrproc_t __outproc, CHAR_PTR __out)
{
OutFile << CurrentTime() << "mycallrpc called " << endl;
OutFile.flush();
int res = fptrcallrpc(__host, __prognum, __versnum, __procnum, __inproc,
__in, __outproc, __out);
return res;
}
enum clnt_stat myclnt_broadcast(u_long __prog, u_long __vers, u_long __proc,
xdrproc_t __xargs, caddr_t __argsp, xdrproc_t __xresults,
caddr_t __resultsp, resultproc_t __eachresult)
{
OutFile << CurrentTime() << "myclnt_broadcast called " << endl;
OutFile.flush();
enum clnt_stat res = fptrclnt_broadcast(__prog, __vers, __proc, __xargs,
__argsp, __xresults, __resultsp, __eachresult);
return res;
}
CLIENT * myclntudp_create(struct sockaddr_in * __raddr, u_long __program,
u_long __version, struct timeval __wait_resend, INT_PTR __sockp)
{
OutFile << CurrentTime() << "myclntudp_create called " << endl;
OutFile.flush();
CLIENT * res = fptrclntudp_create(__raddr, __program, __version,
__wait_resend, __sockp);
return res;
}
CLIENT * myclntudp_bufcreate(struct sockaddr_in * __raddr, u_long __program,
u_long __version, struct timeval __wait_resend, INT_PTR __sockp,
u_int __sendsz, u_int __recvsz)
{
OutFile << CurrentTime() << "myclntudp_bufcreate called " << endl;
OutFile.flush();
CLIENT * res = fptrclntudp_bufcreate(__raddr, __program, __version,
__wait_resend, __sockp, __sendsz, __recvsz);
return res;
}
struct pmaplist * mypmap_getmaps(struct sockaddr_in * __address)
{
OutFile << CurrentTime() << "mypmap_getmaps called " << endl;
OutFile.flush();
struct pmaplist * res = fptrpmap_getmaps(__address);
return res;
}
u_short mypmap_getport(struct sockaddr_in * __address, u_long __program,
u_long __version, u_int __protocol)
{
OutFile << CurrentTime() << "mypmap_getport called " << endl;
OutFile.flush();
u_short res = fptrpmap_getport(__address, __program, __version, __protocol);
return res;
}
enum clnt_stat mypmap_rmtcall(struct sockaddr_in * __addr, u_long __prog,
u_long __vers, u_long __proc, xdrproc_t __xdrargs, caddr_t __argsp,
xdrproc_t __xdrres, caddr_t __resp, struct timeval __tout,
u_long * __port_ptr)
{
OutFile << CurrentTime() << "mypmap_rmtcall called " << endl;
OutFile.flush();
enum clnt_stat res = fptrpmap_rmtcall(__addr, __prog, __vers, __proc,
__xdrargs, __argsp, __xdrres, __resp, __tout, __port_ptr);
return res;
}
bool_t mypmap_set(u_long __program, u_long __vers, int __protocol, u_short __port)
{
OutFile << CurrentTime() << "mypmap_set called " << endl;
OutFile.flush();
bool_t res = fptrpmap_set(__program, __vers, __protocol, __port);
return res;
}
CLIENT * myclntraw_create(u_long __prog, u_long __vers)
{
OutFile << CurrentTime() << "myclntraw_create called " << endl;
OutFile.flush();
CLIENT * res = fptrclntraw_create(__prog, __vers);
return res;
}
void mysvc_run()
{
OutFile << CurrentTime() << "mysvc_run called " << endl;
OutFile.flush();
fptrsvc_run();
}
bool_t mysvc_sendreply(SVCXPRT * xprt, xdrproc_t __xdr_results,
caddr_t __xdr_location)
{
OutFile << CurrentTime() << "mysvc_sendreply called " << endl;
OutFile.flush();
bool_t res = fptrsvc_sendreply(xprt, __xdr_results, __xdr_location);
return res;
}
SVCXPRT * mysvcraw_create()
{
OutFile << CurrentTime() << "mysvcraw_create called " << endl;
OutFile.flush();
SVCXPRT * res = fptrsvcraw_create();
return res;
}
SVCXPRT * mysvctcp_create(int __sock, u_int __sendsize, u_int __recvsize)
{
OutFile << CurrentTime() << "mypmap_rmtcall called " << endl;
OutFile.flush();
SVCXPRT * res = fptrsvctcp_create(__sock, __sendsize, __recvsize);
return res;
}
SVCXPRT * mysvcudp_bufcreate(int __sock, u_int __sendsz, u_int __recvsz)
{
OutFile << CurrentTime() << "mysvcudp_bufcreate called " << endl;
OutFile.flush();
SVCXPRT * res = fptrsvcudp_bufcreate(__sock, __sendsz, __recvsz);
return res;
}
SVCXPRT * mysvcudp_create(int __sock)
{
OutFile << CurrentTime() << "mysvcudp_create called " << endl;
OutFile.flush();
SVCXPRT * res = fptrsvcudp_create(__sock);
return res;
}
void my_exit(int __status)
{
OutFile << CurrentTime() << "my_exit called " << endl;
OutFile.flush();
fptr_exit(__status);
}
int my_nanosleep(const struct timespec *__rqtp, struct timespec *__rmtp)
{
OutFile << CurrentTime() << "my_nanosleep called " << endl;
OutFile.flush();
int res = fptrnanosleep(__rqtp, __rmtp);
return res;
}
int mysigprocmask(int __how, __const sigset_t *__restrict __set,
sigset_t *__restrict __oset)
{
OutFile << CurrentTime() << "mysigprocmask called " << endl;
OutFile.flush();
int res = fptrsigprocmask(__how, __set, __oset);
return res;
}
int mypselect(int __nfds, fd_set *__restrict __readfds,
fd_set *__restrict __writefds, fd_set *__restrict __exceptfds,
const struct timespec *__restrict __timeout,
const __sigset_t *__restrict __sigmask)
{
OutFile << CurrentTime() << "mypselect called " << endl;
OutFile.flush();
int res = fptrpselect(__nfds, __readfds, __writefds, __exceptfds, __timeout,
__sigmask);
return res;
}
pid_t mywait(INT_PTR __status)
{
OutFile << CurrentTime() << "mywait called " << endl;
OutFile.flush();
int res = fptrwait(__status);
return res;
}
int myfclose(FILE * __stream)
{
OutFile << CurrentTime() << "myfclose called " << endl;
OutFile.flush();
int res = fptrfclose(__stream);
return res;
}
int myioctl(int __d, int __request, CHAR_PTR __argp)
{
OutFile << CurrentTime() << "myioctl called " << endl;
OutFile.flush();
int res = fptrioctl(__d, __request, __argp);
return res;
}
int myfcntl(int __fd, int __cmd, VOID_PTR __argp)
{
OutFile << CurrentTime() << "myfcntl called " << endl;
OutFile.flush();
int res = fptrfcntl(__fd, __cmd, __argp);
return res;
}
VOID_PTR my__libc_dlopen_mode(const CHAR_PTR __name, int __mode)
{
OutFile << CurrentTime() << "my__libc_dlopen_mode called " << endl;
OutFile.flush();
VOID_PTR res = fptr__libc_dlopen_mode(__name, __mode);
return res;
}
INT_PTR my__errno_location(void)
{
OutFile << CurrentTime() << "my__errno_location called " << endl;
OutFile.flush();
INT_PTR res = fptr__errno_location();
return res;
}
int mysyscall(int __number, long int __arg1, long int __arg2, long int __arg3,
long int __arg4, long int __arg5, long int __arg6, long int __arg7)
{
OutFile << CurrentTime() << "mysyscall called " << endl;
OutFile.flush();
int res = fptrsyscall(__number, __arg1, __arg2, __arg3, __arg4, __arg5,
__arg6, __arg7);
return res;
}
int mysigaction(int __sig, __const struct sigaction *__restrict __act,
struct sigaction *__restrict __oact)
{
OutFile << CurrentTime() << "mysigaction called " << endl;
OutFile.flush();
int res = fptrsigaction(__sig, __act, __oact);
return res;
}
/* ===================================================================== */
/* Instrumnetation functions */
/* ===================================================================== */
// Image load callback - inserts the probes.
void ImgLoad(IMG img, VOID_PTR v) {
// Called every time a new image is loaded
if ((IMG_Name(img).find("libc.so") != string::npos)
|| (IMG_Name(img).find("LIBC.SO") != string::npos)
|| (IMG_Name(img).find("LIBC.so") != string::npos))
{
RTN rtnsleep = RTN_FindByName(img, "sleep");
if (RTN_Valid(rtnsleep) && RTN_IsSafeForProbedReplacement(rtnsleep))
{
OutFile << CurrentTime() << "Inserting probe for sleep at "
<< RTN_Address(rtnsleep) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsleep, AFUNPTR(mysleep)));
fptrsleep = (int (*)(unsigned int))fptr;
}
RTN rtnsocket = RTN_FindByName(img, "socket");
if (RTN_Valid(rtnsocket) && RTN_IsSafeForProbedReplacement(rtnsocket))
{
OutFile << CurrentTime() << "Inserting probe for socket at "
<< RTN_Address(rtnsocket) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsocket, AFUNPTR(mysocket)));
fptrsocket = (int (*)(int, int, int))fptr;
}
RTN rtnshutdown = RTN_FindByName(img, "shutdown");
if (RTN_Valid(rtnshutdown)
&& RTN_IsSafeForProbedReplacement(rtnshutdown))
{
OutFile << CurrentTime() << "Inserting probe for shutdown at " << RTN_Address(rtnshutdown) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnshutdown, AFUNPTR(myshutdown)));
fptrshutdown = (int (*)(int, int))fptr;
}
RTN rtnselect = RTN_FindByName(img, "select");
if (RTN_Valid(rtnselect) && RTN_IsSafeForProbedReplacement(rtnselect))
{
OutFile << CurrentTime() << "Inserting probe for select at " << RTN_Address(rtnselect) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnselect, AFUNPTR(myselect)));
fptrselect = (int (*)(int, fd_set *, fd_set *, fd_set *, struct timeval *))fptr;
}
RTN rtnpoll = RTN_FindByName(img, "poll");
if (RTN_Valid(rtnpoll) && RTN_IsSafeForProbedReplacement(rtnpoll))
{
OutFile << CurrentTime() << "Inserting probe for poll at " << RTN_Address(rtnpoll) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnpoll, AFUNPTR(mypoll)));
fptrpoll = (int (*)(struct pollfd *, nfds_t, int))fptr;
}
RTN rtnpselect = RTN_FindByName(img, "pselect");
if (RTN_Valid(rtnpselect)
&& RTN_IsSafeForProbedReplacement(rtnpselect))
{
OutFile << CurrentTime() << "Inserting probe for pselect at "
<< RTN_Address(rtnpselect) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnpselect, AFUNPTR(mypselect)));
fptrpselect = (int (*)(int, fd_set *, fd_set *, fd_set *,
const struct timespec *, const __sigset_t *))fptr;
}
RTN rtnaccept = RTN_FindByName(img, "accept");
if (RTN_Valid(rtnaccept) && RTN_IsSafeForProbedReplacement(rtnaccept))
{
OutFile << CurrentTime() << "Inserting probe for accept at " << RTN_Address(rtnaccept) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnaccept, AFUNPTR(myaccept)));
fptraccept = (int (*)(int, __SOCKADDR_ARG, socklen_t *__restrict))fptr;
}
RTN rtnconnect = RTN_FindByName(img, "connect");
if (RTN_Valid(rtnconnect) && RTN_IsSafeForProbedReplacement(rtnconnect))
{
OutFile << CurrentTime() << "Inserting probe for connect at " << RTN_Address(rtnconnect) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnconnect, AFUNPTR(myconnect)));
fptrconnect = (int (*)(int, __CONST_SOCKADDR_ARG, socklen_t))fptr;
}
RTN rtnrecv = RTN_FindByName(img, "recv");
if (RTN_Valid(rtnrecv) && RTN_IsSafeForProbedReplacement(rtnrecv))
{
OutFile << CurrentTime() << "Inserting probe for recv at " << RTN_Address(rtnrecv) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnrecv, AFUNPTR(myrecv)));
fptrrecv = (ssize_t (*)(int, VOID_PTR , size_t, int))fptr;
}
RTN rtnrecvfrom = RTN_FindByName(img, "recvfrom");
if (RTN_Valid(rtnrecvfrom) && RTN_IsSafeForProbedReplacement(rtnrecvfrom))
{
OutFile << CurrentTime() << "Inserting probe for recvfrom at " << RTN_Address(rtnrecvfrom) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnrecvfrom, AFUNPTR(myrecvfrom)));
fptrrecvfrom = (ssize_t (*)(int, VOID_PTR , size_t, int, __SOCKADDR_ARG, socklen_t *))fptr;
}
RTN rtnsend = RTN_FindByName(img, "send");
if (RTN_Valid(rtnsend) && RTN_IsSafeForProbedReplacement(rtnsend))
{
OutFile << CurrentTime() << "Inserting probe for send at " << RTN_Address(rtnsend) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsend, AFUNPTR(mysend)));
fptrsend = (ssize_t (*)(int, __const VOID_PTR, size_t, int))fptr;
}
RTN rtnsendto = RTN_FindByName(img, "sendto");
if (RTN_Valid(rtnsendto) && RTN_IsSafeForProbedReplacement(rtnsendto))
{
OutFile << CurrentTime() << "Inserting probe for sendto at " << RTN_Address(rtnsendto) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsendto, AFUNPTR(mysendto)));
fptrsendto = (ssize_t (*)(int, __const VOID_PTR , size_t, int, __CONST_SOCKADDR_ARG, socklen_t))fptr;
}
RTN rtngetwc = RTN_FindByName(img, "getwc");
if (RTN_Valid(rtngetwc) && RTN_IsSafeForProbedReplacement(rtngetwc))
{
OutFile << CurrentTime() << "Inserting probe for getwc at " << RTN_Address(rtngetwc) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtngetwc, AFUNPTR(mygetwc)));
fptrgetwc = (wint_t (*)(__FILE *))fptr;
}
RTN rtngetw = RTN_FindByName(img, "getw");
if (RTN_Valid(rtngetw) && RTN_IsSafeForProbedReplacement(rtngetw))
{
OutFile << CurrentTime() << "Inserting probe for getw at " << RTN_Address(rtngetw) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtngetw, AFUNPTR(mygetw)));
fptrgetw = (int (*)(FILE *))fptr;
}
RTN rtn_IO_getc = RTN_FindByName(img, "_IO_getc");
if (RTN_Valid(rtn_IO_getc)
&& RTN_IsSafeForProbedReplacement(rtn_IO_getc))
{
OutFile << CurrentTime() << "Inserting probe for _IO_getc at " << RTN_Address(rtn_IO_getc) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtn_IO_getc, AFUNPTR(my_IO_getc)));
fptr_IO_getc = (int (*)(FILE *))fptr;
}
RTN rtngetchar = RTN_FindByName(img, "getchar");
if (RTN_Valid(rtngetchar) && RTN_IsSafeForProbedReplacement(rtngetchar))
{
OutFile << CurrentTime() << "Inserting probe for getchar at " << RTN_Address(rtngetchar) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtngetchar, AFUNPTR(mygetchar)));
fptrgetchar = (int (*)())fptr;
}
RTN rtngetwchar = RTN_FindByName(img, "getwchar");
if (RTN_Valid(rtngetwchar) && RTN_IsSafeForProbedReplacement(rtngetwchar))
{
OutFile << CurrentTime() << "Inserting probe for getwchar at "
<< RTN_Address(rtngetwchar) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtngetwchar, AFUNPTR(mygetwchar)));
fptrgetwchar = (wint_t (*)())fptr;
}
RTN rtngets = RTN_FindByName(img, "gets");
if (RTN_Valid(rtngets) && RTN_IsSafeForProbedReplacement(rtngets))
{
OutFile << CurrentTime() << "Inserting probe for gets at " << RTN_Address(rtngets) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtngets, AFUNPTR(mygets)));
fptrgets = (CHAR_PTR (*)(CHAR_PTR ))fptr;
}
RTN rtnfgetc = RTN_FindByName(img, "fgetc");
if (RTN_Valid(rtnfgetc) && RTN_IsSafeForProbedReplacement(rtnfgetc))
{
OutFile << CurrentTime() << "Inserting probe for fgetc at " << RTN_Address(rtnfgetc) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnfgetc, AFUNPTR(myfgetc)));
fptrfgetc = (void (*)(__FILE *))fptr;
}
RTN rtnfgetwc = RTN_FindByName(img, "fgetwc");
if (RTN_Valid(rtnfgetwc) && RTN_IsSafeForProbedReplacement(rtnfgetwc))
{
OutFile << CurrentTime() << "Inserting probe for fgetwc at " << RTN_Address(rtnfgetwc) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnfgetwc, AFUNPTR(myfgetwc)));
fptrfgetwc = (wint_t (*)(__FILE *))fptr;
}
RTN rtnfgets = RTN_FindByName(img, "fgets");
if (RTN_Valid(rtnfgets) && RTN_IsSafeForProbedReplacement(rtnfgets))
{
OutFile << CurrentTime() << "Inserting probe for fgets at " << RTN_Address(rtnfgets) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnfgets, AFUNPTR(myfgets)));
fptrfgets = (CHAR_PTR (*)(CHAR_PTR __restrict, int,
FILE *__restrict))fptr;
}
RTN rtnfgetws = RTN_FindByName(img, "fgetws");
if (RTN_Valid(rtnfgetws) && RTN_IsSafeForProbedReplacement(rtnfgetws))
{
OutFile << CurrentTime() << "Inserting probe for fgetws at " << RTN_Address(rtnfgetws) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnfgetws, AFUNPTR(myfgetws)));
fptrfgetws = (wchar_t * (*)(wchar_t *, int, __FILE *))fptr;
}
RTN rtnfread = RTN_FindByName(img, "fread");
if (RTN_Valid(rtnfread) && RTN_IsSafeForProbedReplacement(rtnfread))
{
OutFile << CurrentTime() << "Inserting probe for fread at " << RTN_Address(rtnfread) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnfread, AFUNPTR(myfread)));
fptrfread = (size_t (*)(VOID_PTR , size_t, size_t, FILE *))fptr;
}
RTN rtnfwrite = RTN_FindByName(img, "fwrite");
if (RTN_Valid(rtnfwrite) && RTN_IsSafeForProbedReplacement(rtnfwrite))
{
OutFile << CurrentTime() << "Inserting probe for fwrite at " << RTN_Address(rtnfwrite) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnfwrite, AFUNPTR(myfwrite)));
fptrfwrite = (size_t (*)(__const VOID_PTR __restrict, size_t, size_t,
FILE *__restrict))fptr;
}
RTN rtnpipe = RTN_FindByName(img, "pipe");
if (RTN_Valid(rtnpipe) && RTN_IsSafeForProbedReplacement(rtnpipe))
{
OutFile << CurrentTime() << "Inserting probe for pipe at " << RTN_Address(rtnpipe) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnpipe, AFUNPTR(mypipe)));
fptrpipe = (int (*)(int[2]))fptr;
}
RTN rtnread = RTN_FindByName(img, "read");
if (RTN_Valid(rtnread) && RTN_IsSafeForProbedReplacement(rtnread))
{
OutFile << CurrentTime() << "Inserting probe for read at " << RTN_Address(rtnread) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnread, AFUNPTR(myread)));
fptrread = (ssize_t (*)(int, VOID_PTR , size_t))fptr;
}
RTN rtnwrite = RTN_FindByName(img, "write");
if (RTN_Valid(rtnwrite) && RTN_IsSafeForProbedReplacement(rtnwrite))
{
OutFile << CurrentTime() << "Inserting probe for write at " << RTN_Address(rtnwrite) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnwrite, AFUNPTR(mywrite)));
fptrwrite = (ssize_t (*)(int, __const VOID_PTR , size_t))fptr;
}
RTN rtnopen = RTN_FindByName(img, "open");
if (RTN_Valid(rtnopen) && RTN_IsSafeForProbedReplacement(rtnopen))
{
OutFile << CurrentTime() << "Inserting probe for open at " << RTN_Address(rtnopen) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnopen, AFUNPTR(myopen)));
fptropen = (int (*)(__const CHAR_PTR , int, mode_t))fptr;
}
RTN rtnfopen = RTN_FindByName(img, "fopen");
if (RTN_Valid(rtnfopen) && RTN_IsSafeForProbedReplacement(rtnfopen))
{
OutFile << CurrentTime() << "Inserting probe for fopen at " << RTN_Address(rtnfopen) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnfopen, AFUNPTR(myfopen)));
fptrfopen = (FILE * (*)(__const CHAR_PTR __restrict, __const CHAR_PTR __restrict))fptr;
}
RTN rtnfdopen = RTN_FindByName(img, "fdopen");
if (RTN_Valid(rtnfdopen) && RTN_IsSafeForProbedReplacement(rtnfdopen))
{
OutFile << CurrentTime() << "Inserting probe for fdopen at " << RTN_Address(rtnfdopen) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnfdopen, AFUNPTR(myfdopen)));
fptrfdopen = (FILE * (*)(int, __const CHAR_PTR ))fptr;
}
RTN rtnclose = RTN_FindByName(img, "close");
if (RTN_Valid(rtnclose) && RTN_IsSafeForProbedReplacement(rtnclose))
{
OutFile << CurrentTime() << "Inserting probe for close at " << RTN_Address(rtnclose) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnclose, AFUNPTR(myclose)));
fptrclose = (int (*)(int))fptr;
}
RTN rtnfclose = RTN_FindByName(img, "fclose");
if (RTN_Valid(rtnfclose) && RTN_IsSafeForProbedReplacement(rtnfclose))
{
OutFile << CurrentTime() << "Inserting probe for fclose at " << RTN_Address(rtnfclose) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnfclose, AFUNPTR(myfclose)));
fptrfclose = (int (*)(FILE *))fptr;
}
RTN rtncallrpc = RTN_FindByName(img, "callrpc");
if (RTN_Valid(rtncallrpc)&& RTN_IsSafeForProbedReplacement(rtncallrpc))
{
OutFile << CurrentTime() << "Inserting probe for callrpc at " << RTN_Address(rtncallrpc) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtncallrpc, AFUNPTR(mycallrpc)));
fptrcallrpc = (int (*)(__const CHAR_PTR , u_long, u_long, u_long,
xdrproc_t, __const CHAR_PTR , xdrproc_t, CHAR_PTR ))fptr;
}
RTN rtnclnt_broadcast = RTN_FindByName(img, "clnt_broadcast");
if (RTN_Valid(rtnclnt_broadcast)
&& RTN_IsSafeForProbedReplacement(rtnclnt_broadcast))
{
OutFile << CurrentTime() << "Inserting probe for clnt_broadcast at " << RTN_Address(rtnclnt_broadcast) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnclnt_broadcast, AFUNPTR(myclnt_broadcast)));
fptrclnt_broadcast = (enum clnt_stat (*)(u_long, u_long, u_long,
xdrproc_t, caddr_t, xdrproc_t, caddr_t, resultproc_t))fptr;
}
RTN rtnclntudp_create = RTN_FindByName(img, "clntudp_create");
if (RTN_Valid(rtnclntudp_create)
&& RTN_IsSafeForProbedReplacement(rtnclntudp_create))
{
OutFile << CurrentTime() << "Inserting probe for clntudp_create at " << RTN_Address(rtnclntudp_create) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnclntudp_create, AFUNPTR(myclntudp_create)));
fptrclntudp_create = (CLIENT * (*)(struct sockaddr_in *, u_long,
u_long, struct timeval, INT_PTR ))fptr;
}
RTN rtnclntudp_bufcreate = RTN_FindByName(img, "clntudp_bufcreate");
if (RTN_Valid(rtnclntudp_bufcreate) && RTN_IsSafeForProbedReplacement(rtnclntudp_bufcreate))
{
OutFile << CurrentTime() << "Inserting probe for clntudp_bufcreate at " << RTN_Address(rtnclntudp_bufcreate) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnclntudp_bufcreate, AFUNPTR(myclntudp_bufcreate)));
fptrclntudp_bufcreate = (CLIENT * (*)(struct sockaddr_in *, u_long, u_long, struct timeval, INT_PTR , u_int, u_int))fptr;
}
RTN rtnpmap_getmaps = RTN_FindByName(img, "pmap_getmaps");
if (RTN_Valid(rtnpmap_getmaps) && RTN_IsSafeForProbedReplacement(rtnpmap_getmaps))
{
OutFile << CurrentTime() << "Inserting probe for pmap_getmaps at " << RTN_Address(rtnpmap_getmaps) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnpmap_getmaps, AFUNPTR(mypmap_getmaps)));
fptrpmap_getmaps = (struct pmaplist * (*)( struct sockaddr_in *))fptr;
}
RTN rtnpmap_getport = RTN_FindByName(img, "pmap_getport");
if (RTN_Valid(rtnpmap_getport) && RTN_IsSafeForProbedReplacement(rtnpmap_getport))
{
OutFile << CurrentTime() << "Inserting probe for pmap_getport at " << RTN_Address(rtnpmap_getport) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnpmap_getport, AFUNPTR(mypmap_getport)));
fptrpmap_getport = (u_short (*)(struct sockaddr_in *, u_long, u_long, u_int))fptr;
}
RTN rtnpmap_rmtcall = RTN_FindByName(img, "pmap_rmtcall");
if (RTN_Valid(rtnpmap_rmtcall) && RTN_IsSafeForProbedReplacement(rtnpmap_rmtcall))
{
OutFile << CurrentTime() << "Inserting probe for pmap_rmtcall at " << RTN_Address(rtnpmap_rmtcall) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnpmap_rmtcall, AFUNPTR(mypmap_rmtcall)));
fptrpmap_rmtcall = (enum clnt_stat (*)(struct sockaddr_in *, u_long,
u_long, u_long, xdrproc_t, caddr_t, xdrproc_t, caddr_t,
struct timeval, u_long *))fptr;
}
RTN rtnpmap_set = RTN_FindByName(img, "pmap_set");
if (RTN_Valid(rtnpmap_set) && RTN_IsSafeForProbedReplacement(rtnpmap_set))
{
OutFile << CurrentTime() << "Inserting probe for pmap_set at " << RTN_Address(rtnpmap_set) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnpmap_set, AFUNPTR(mypmap_set)));
fptrpmap_set = (bool_t (*)(u_long, u_long, int, u_short))fptr;
}
RTN rtnclntraw_create = RTN_FindByName(img, "clntraw_create");
if (RTN_Valid(rtnclntraw_create)
&& RTN_IsSafeForProbedReplacement(rtnclntraw_create))
{
OutFile << CurrentTime() << "Inserting probe for clntraw_create at " << RTN_Address(rtnclntraw_create) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnclntraw_create, AFUNPTR(myclntraw_create)));
fptrclntraw_create = (CLIENT * (*)(u_long, u_long))fptr;
}
RTN rtnsvc_run = RTN_FindByName(img, "svc_run");
if (RTN_Valid(rtnsvc_run) && RTN_IsSafeForProbedReplacement(rtnsvc_run))
{
OutFile << CurrentTime() << "Inserting probe for svc_run at "
<< RTN_Address(rtnsvc_run) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsvc_run, AFUNPTR(mysvc_run)));
fptrsvc_run = (void (*)())fptr;
}
RTN rtnsvc_sendreply = RTN_FindByName(img, "svc_sendreply");
if (RTN_Valid(rtnsvc_sendreply) && RTN_IsSafeForProbedReplacement(rtnsvc_sendreply))
{
OutFile << CurrentTime() << "Inserting probe for svc_sendreply at " << RTN_Address(rtnsvc_sendreply) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsvc_sendreply, AFUNPTR(mysvc_sendreply)));
fptrsvc_sendreply = (bool_t (*)(SVCXPRT *, xdrproc_t, caddr_t))fptr;
}
RTN rtnsvcraw_create = RTN_FindByName(img, "svcraw_create");
if (RTN_Valid(rtnsvcraw_create) && RTN_IsSafeForProbedReplacement(rtnsvcraw_create))
{
OutFile << CurrentTime() << "Inserting probe for svcraw_create at " << RTN_Address(rtnsvcraw_create) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsvcraw_create, AFUNPTR(mysvcraw_create)));
fptrsvcraw_create = (SVCXPRT * (*)())fptr;
}
RTN rtnsvctcp_create = RTN_FindByName(img, "svctcp_create");
if (RTN_Valid(rtnsvctcp_create) && RTN_IsSafeForProbedReplacement(rtnsvctcp_create))
{
OutFile << CurrentTime() << "Inserting probe for svctcp_create at " << RTN_Address(rtnsvctcp_create) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsvctcp_create, AFUNPTR(mysvctcp_create)));
fptrsvctcp_create = (SVCXPRT * (*)(int, u_int, u_int))fptr;
}
RTN rtnsvcudp_bufcreate = RTN_FindByName(img, "svcudp_bufcreate");
if (RTN_Valid(rtnsvcudp_bufcreate) && RTN_IsSafeForProbedReplacement(rtnsvcudp_bufcreate))
{
OutFile << CurrentTime() << "Inserting probe for svcudp_bufcreate at " << RTN_Address(rtnsvcudp_bufcreate) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsvcudp_bufcreate, AFUNPTR(mysvcudp_bufcreate)));
fptrsvcudp_bufcreate = (SVCXPRT * (*)(int, u_int, u_int))fptr;
}
RTN rtnsvcudp_create = RTN_FindByName(img, "svcudp_create");
if (RTN_Valid(rtnsvcudp_create) && RTN_IsSafeForProbedReplacement(rtnsvcudp_create))
{
OutFile << CurrentTime() << "Inserting probe for svcudp_create at " << RTN_Address(rtnsvcudp_create) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsvcudp_create, AFUNPTR(mysvcudp_create)));
fptrsvcudp_create = (SVCXPRT * (*)(int))fptr;
}
RTN rtnabort = RTN_FindByName(img, "abort");
if (RTN_Valid(rtnabort) && RTN_IsSafeForProbedReplacement(rtnabort))
{
OutFile << CurrentTime() << "Inserting probe for abort at " << RTN_Address(rtnabort) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnabort, AFUNPTR(myabort)));
fptrabort = (void (*)())fptr;
}
RTN rtn_exit = RTN_FindByName(img, "_exit");
if (RTN_Valid(rtn_exit) && RTN_IsSafeForProbedReplacement(rtn_exit))
{
OutFile << CurrentTime() << "Inserting probe for _exit at " << RTN_Address(rtn_exit) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtn_exit, AFUNPTR(my_exit)));
fptr_exit = (void (*)(int))fptr;
}
RTN rtnnanosleep = RTN_FindByName(img, "nanosleep");
if (RTN_Valid(rtnnanosleep) && RTN_IsSafeForProbedReplacement(rtnnanosleep))
{
OutFile << CurrentTime() << "Inserting probe for nanosleep at " << RTN_Address(rtnnanosleep) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnnanosleep, AFUNPTR(my_nanosleep)));
fptrnanosleep = (int (*)(const struct timespec *, struct timespec *))fptr;
}
RTN rtnsignal = RTN_FindByName(img, "signal");
if (RTN_Valid(rtnsignal) && RTN_IsSafeForProbedReplacement(rtnsignal))
{
OutFile << CurrentTime() << "Inserting probe for signal at " << RTN_Address(rtnsignal) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsignal, AFUNPTR(mysignal)));
fptrsignal = (__sighandler_t (*)(int, __sighandler_t))fptr;
}
RTN rtnsigprocmask = RTN_FindByName(img, "sigprocmask");
if (RTN_Valid(rtnsigprocmask) && RTN_IsSafeForProbedReplacement(rtnsigprocmask))
{
OutFile << CurrentTime() << "Inserting probe for sigprocmask at " << RTN_Address(rtnsigprocmask) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsigprocmask, AFUNPTR(mysigprocmask)));
fptrsigprocmask = (int (*)(int, __const sigset_t *__restrict, sigset_t *__restrict))fptr;
}
RTN rtnsigpending = RTN_FindByName(img, "sigpending");
if (RTN_Valid(rtnsigpending) && RTN_IsSafeForProbedReplacement(rtnsigpending))
{
OutFile << CurrentTime() << "Inserting probe for sigpending at " << RTN_Address(rtnsigpending) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsigpending, AFUNPTR(mysigpending)));
fptrsigpending = (int (*)(sigset_t *))fptr;
}
RTN rtnsigaction = RTN_FindByName(img, "sigaction");
if (RTN_Valid(rtnsigaction) && RTN_IsSafeForProbedReplacement(rtnsigaction))
{
OutFile << CurrentTime() << "Inserting probe for sigaction at " << RTN_Address(rtnsigaction) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsigaction, AFUNPTR(mysigaction)));
fptrsigaction = (int (*)(int __sig, __const struct sigaction *__restrict __act, struct sigaction *__restrict __oact))fptr;
}
RTN rtnsetitimer = RTN_FindByName(img, "setitimer");
if (RTN_Valid(rtnsetitimer) && RTN_IsSafeForProbedReplacement(rtnsetitimer))
{
OutFile << CurrentTime() << "Inserting probe for setitimer at " << RTN_Address(rtnsetitimer) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsetitimer, AFUNPTR(mysetitimer)));
fptrsetitimer = (int (*)(__itimer_which_t, __const struct itimerval *__restrict, struct itimerval *__restrict))fptr;
}
RTN rtnexit = RTN_FindByName(img, "exit");
if (RTN_Valid(rtnexit) && RTN_IsSafeForProbedReplacement(rtnexit))
{
OutFile << CurrentTime() << "Inserting probe for exit at " << RTN_Address(rtnexit) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnexit, AFUNPTR(myexit)));
fptrexit = (void (*)(int))fptr;
}
RTN rtndl_iterate_phdr = RTN_FindByName(img, "dl_iterate_phdr");
if (RTN_Valid(rtnexit) && RTN_IsSafeForProbedReplacement(rtndl_iterate_phdr))
{
OutFile << CurrentTime() << "Inserting probe for dl_iterate_phdr at " << RTN_Address(rtndl_iterate_phdr) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtndl_iterate_phdr, AFUNPTR(mydl_iterate_phdr)));
fptrdl_iterate_phdr = (int (*)( int (*callback)(struct dl_phdr_info *info, size_t size, VOID_PTR data), VOID_PTR data))fptr;
}
RTN rtnsystem = RTN_FindByName(img, "system");
if (RTN_Valid(rtnsystem) && RTN_IsSafeForProbedReplacement(rtnsystem))
{
OutFile << CurrentTime() << "Inserting probe for system at "
<< RTN_Address(rtnsystem) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsystem, AFUNPTR(mysystem)));
fptrsystem = (int (*)(const CHAR_PTR ))fptr;
}
RTN rtnalarm = RTN_FindByName(img, "alarm");
if (RTN_Valid(rtnalarm) && RTN_IsSafeForProbedReplacement(rtnalarm))
{
OutFile << CurrentTime() << "Inserting probe for alarm at "
<< RTN_Address(rtnalarm) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnalarm, AFUNPTR(myalarm)));
fptralarm = (unsigned int (*)(unsigned int))fptr;
}
RTN rtnrecvmsg = RTN_FindByName(img, "recvmsg");
if (RTN_Valid(rtnrecvmsg) && RTN_IsSafeForProbedReplacement(rtnrecvmsg))
{
OutFile << CurrentTime() << "Inserting probe for recvmsg at " << RTN_Address(rtnrecvmsg) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnrecvmsg, AFUNPTR(myrecvmsg)));
fptrrecvmsg = (ssize_t (*)(int, struct msghdr *, int))fptr;
}
RTN rtnsendmsg = RTN_FindByName(img, "sendmsg");
if (RTN_Valid(rtnsendmsg) && RTN_IsSafeForProbedReplacement(rtnsendmsg))
{
OutFile << CurrentTime() << "Inserting probe for sendmsg at "
<< RTN_Address(rtnsendmsg) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsendmsg, AFUNPTR(mysendmsg)));
fptrsendmsg = (ssize_t (*)(int, const struct msghdr *, int))fptr;
}
RTN rtnpause = RTN_FindByName(img, "pause");
if (RTN_Valid(rtnpause) && RTN_IsSafeForProbedReplacement(rtnpause))
{
OutFile << CurrentTime() << "Inserting probe for pause at "
<< RTN_Address(rtnpause) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnpause, AFUNPTR(mypause)));
fptrpause = (int (*)(void))fptr;
}
RTN rtnsigtimedwait = RTN_FindByName(img, "sigtimedwait");
if (RTN_Valid(rtnsigtimedwait) && RTN_IsSafeForProbedReplacement(rtnsigtimedwait))
{
OutFile << CurrentTime() << "Inserting probe for sigtimedwait at " << RTN_Address(rtnsigtimedwait) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsigtimedwait, AFUNPTR(mysigtimedwait)));
fptrsigtimedwait = (int (*)(const sigset_t *, siginfo_t *, const struct timespec *))fptr;
}
RTN rtnsigwaitinfo = RTN_FindByName(img, "sigwaitinfo");
if (RTN_Valid(rtnsigwaitinfo) && RTN_IsSafeForProbedReplacement(rtnsigwaitinfo))
{
OutFile << CurrentTime() << "Inserting probe for sigwaitinfo at " << RTN_Address(rtnsigwaitinfo) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsigwaitinfo, AFUNPTR(mysigwaitinfo)));
fptrsigwaitinfo = (int (*)(const sigset_t *, siginfo_t *))fptr;
}
RTN rtnepoll_wait = RTN_FindByName(img, "epoll_wait");
if (RTN_Valid(rtnepoll_wait) && RTN_IsSafeForProbedReplacement(rtnepoll_wait))
{
OutFile << CurrentTime() << "Inserting probe for epoll_wait at " << RTN_Address(rtnepoll_wait) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnepoll_wait, AFUNPTR(myepoll_wait)));
fptrepoll_wait = (int (*)(int, struct epoll_event *, int, int))fptr;
}
RTN rtnppoll = RTN_FindByName(img, "ppoll");
if (RTN_Valid(rtnppoll) && RTN_IsSafeForProbedReplacement(rtnppoll))
{
OutFile << CurrentTime() << "Inserting probe for ppoll at " << RTN_Address(rtnppoll) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnppoll, AFUNPTR(myppoll)));
fptrppoll = (int (*)(struct pollfd *, nfds_t, const struct timespec *, const sigset_t *))fptr;
}
RTN rtnmsgsnd = RTN_FindByName(img, "msgsnd");
if (RTN_Valid(rtnmsgsnd) && RTN_IsSafeForProbedReplacement(rtnmsgsnd))
{
OutFile << CurrentTime() << "Inserting probe for msgsnd at " << RTN_Address(rtnmsgsnd) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnmsgsnd, AFUNPTR(mymsgsnd)));
fptrmsgsnd = (int (*)(int, const VOID_PTR , size_t, int))fptr;
}
RTN rtnmsgrcv = RTN_FindByName(img, "msgrcv");
if (RTN_Valid(rtnmsgrcv) && RTN_IsSafeForProbedReplacement(rtnmsgrcv))
{
OutFile << CurrentTime() << "Inserting probe for msgrcv at " << RTN_Address(rtnmsgrcv) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnmsgrcv, AFUNPTR(mymsgrcv)));
fptrmsgrcv = (ssize_t (*)(int, VOID_PTR , size_t, long, int))fptr;
}
RTN rtnsemop = RTN_FindByName(img, "semop");
if (RTN_Valid(rtnsemop) && RTN_IsSafeForProbedReplacement(rtnsemop))
{
OutFile << CurrentTime() << "Inserting probe for semop at " << RTN_Address(rtnsemop) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsemop, AFUNPTR(mymsgrcv)));
fptrsemop = (int (*)(int, struct sembuf *, unsigned))fptr;
}
RTN rtnsemtimedop = RTN_FindByName(img, "semtimedop");
if (RTN_Valid(rtnsemtimedop)
&& RTN_IsSafeForProbedReplacement(rtnsemtimedop)) {
OutFile << CurrentTime() << "Inserting probe for semtimedop at "
<< RTN_Address(rtnsemtimedop) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsemtimedop,
AFUNPTR(mysemtimedop)));
fptrsemtimedop = (int (*)(int, struct sembuf *))fptr;}
RTN rtnusleep = RTN_FindByName(img, "usleep");
if (RTN_Valid(rtnusleep) && RTN_IsSafeForProbedReplacement(rtnusleep)) {
OutFile << CurrentTime() << "Inserting probe for usleep at "
<< RTN_Address(rtnusleep) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnusleep, AFUNPTR(myusleep)));
fptrusleep = (int (*)(useconds_t))fptr;}
RTN rtnualarm = RTN_FindByName(img, "ualarm");
if (RTN_Valid(rtnualarm) && RTN_IsSafeForProbedReplacement(rtnualarm)) {
OutFile << CurrentTime() << "Inserting probe for ualarm at "
<< RTN_Address(rtnualarm) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnualarm, AFUNPTR(myualarm)));
fptrualarm = (useconds_t (*)(useconds_t, useconds_t))fptr;}
RTN rtngetitimer = RTN_FindByName(img, "getitimer");
if (RTN_Valid(rtngetitimer) && RTN_IsSafeForProbedReplacement(rtngetitimer))
{
OutFile << CurrentTime() << "Inserting probe for getitimer at " << RTN_Address(rtngetitimer) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtngetitimer, AFUNPTR(mygetitimer)));
fptrgetitimer = (int (*)(int, struct itimerval *))fptr;}
RTN rtnsigwait = RTN_FindByName(img, "sigwait");
if (RTN_Valid(rtnsigwait) && RTN_IsSafeForProbedReplacement(rtnsigwait))
{
OutFile << CurrentTime() << "Inserting probe for sigwait at " << RTN_Address(rtnsigwait) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsigwait, AFUNPTR(mysigwait)));
fptrsigwait = (int (*)(const sigset_t *, INT_PTR ))fptr;
}
RTN rtnmsgget = RTN_FindByName(img, "msgget");
if (RTN_Valid(rtnmsgget) && RTN_IsSafeForProbedReplacement(rtnmsgget))
{
OutFile << CurrentTime() << "Inserting probe for msgget at " << RTN_Address(rtnmsgget) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnmsgget, AFUNPTR(mymsgget)));
fptrmsgget = (int (*)(key_t, int))fptr;
}
RTN rtnsemget = RTN_FindByName(img, "semget");
if (RTN_Valid(rtnsemget) && RTN_IsSafeForProbedReplacement(rtnsemget))
{
OutFile << CurrentTime() << "Inserting probe for semget at " << RTN_Address(rtnsemget) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsemget, AFUNPTR(mysemget)));
fptrsemget = (int (*)(key_t, int, int))fptr;
}
RTN rtnwait = RTN_FindByName(img, "wait");
if (RTN_Valid(rtnwait) && RTN_IsSafeForProbedReplacement(rtnwait))
{
OutFile << CurrentTime() << "Inserting probe for wait at " << RTN_Address(rtnwait) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnwait, AFUNPTR(mywait)));
fptrwait = (pid_t (*)(INT_PTR ))fptr;
}
RTN rtnwaitpid = RTN_FindByName(img, "waitpid");
if (RTN_Valid(rtnwaitpid) && RTN_IsSafeForProbedReplacement(rtnwaitpid))
{
OutFile << CurrentTime() << "Inserting probe for waitpid at " << RTN_Address(rtnwaitpid) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnwaitpid, AFUNPTR(mywaitpid)));
fptrwaitpid = (pid_t (*)(pid_t, INT_PTR , int))fptr;
}
RTN rtnwaitid = RTN_FindByName(img, "waitid");
if (RTN_Valid(rtnwaitid) && RTN_IsSafeForProbedReplacement(rtnwaitid))
{
OutFile << CurrentTime() << "Inserting probe for waitid at " << RTN_Address(rtnwaitid) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnwaitid, AFUNPTR(mywaitid)));
fptrwaitid = (int (*)(idtype_t, id_t, siginfo_t *, int))fptr;
}
RTN rtnwait3 = RTN_FindByName(img, "wait3");
if (RTN_Valid(rtnwait3) && RTN_IsSafeForProbedReplacement(rtnwait3))
{
OutFile << CurrentTime() << "Inserting probe for wait3 at " << RTN_Address(rtnwait3) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnwait3, AFUNPTR(mywait3)));
fptrwait3 = (pid_t (*)(INT_PTR , int, struct rusage *))fptr;
}
RTN rtnwait4 = RTN_FindByName(img, "wait4");
if (RTN_Valid(rtnwait3) && RTN_IsSafeForProbedReplacement(rtnwait4))
{
OutFile << CurrentTime() << "Inserting probe for wait4 at " << RTN_Address(rtnwait4) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnwait3, AFUNPTR(mywait4)));
fptrwait4 = (pid_t (*)(pid_t, INT_PTR , int, struct rusage *))fptr;
}
RTN rtnreadv = RTN_FindByName(img, "readv");
if (RTN_Valid(rtnreadv) && RTN_IsSafeForProbedReplacement(rtnreadv))
{
OutFile << CurrentTime() << "Inserting probe for readv at " << RTN_Address(rtnreadv) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnreadv, AFUNPTR(myreadv)));
fptrreadv = (ssize_t (*)(int, const struct iovec *, int))fptr;
}
RTN rtnwritev = RTN_FindByName(img, "writev");
if (RTN_Valid(rtnwritev) && RTN_IsSafeForProbedReplacement(rtnwritev))
{
OutFile << CurrentTime() << "Inserting probe for writev at " << RTN_Address(rtnwritev) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnwritev, AFUNPTR(mywritev)));
fptrwritev = (ssize_t (*)(int, const struct iovec *, int))fptr;
}
RTN rtnflockfile = RTN_FindByName(img, "flockfile");
if (RTN_Valid(rtnflockfile) && RTN_IsSafeForProbedReplacement(rtnflockfile))
{
OutFile << CurrentTime() << "Inserting probe for flockfile at " << RTN_Address(rtnflockfile) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnflockfile, AFUNPTR(myflockfile)));
fptrflockfile = (void (*)(FILE *))fptr;
}
RTN rtnfunlockfile = RTN_FindByName(img, "funlockfile");
if (RTN_Valid(rtnfunlockfile)
&& RTN_IsSafeForProbedReplacement(rtnfunlockfile)) {
OutFile << CurrentTime() << "Inserting probe for funlockfile at "
<< RTN_Address(rtnfunlockfile) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnfunlockfile,
AFUNPTR(myfunlockfile)));
fptrfunlockfile = (void (*)(FILE *))fptr;}
RTN rtnlockf = RTN_FindByName(img, "lockf");
if (RTN_Valid(rtnlockf) && RTN_IsSafeForProbedReplacement(rtnlockf))
{
OutFile << CurrentTime() << "Inserting probe for lockf at " << RTN_Address(rtnlockf) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnlockf, AFUNPTR(mylockf)));
fptrlockf = (int (*)(int, int, off_t))fptr;
}
RTN rtnsetenv = RTN_FindByName(img, "setenv");
if (RTN_Valid(rtnsetenv) && RTN_IsSafeForProbedReplacement(rtnsetenv))
{
OutFile << CurrentTime() << "Inserting probe for setenv at " << RTN_Address(rtnsetenv) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsetenv, AFUNPTR(mysetenv)));
fptrsetenv = (int (*)(const CHAR_PTR , const CHAR_PTR , int))fptr;
}
RTN rtnunsetenv = RTN_FindByName(img, "unsetenv");
if (RTN_Valid(rtnunsetenv) && RTN_IsSafeForProbedReplacement(rtnunsetenv))
{
OutFile << CurrentTime() << "Inserting probe for unsetenv at " << RTN_Address(rtnunsetenv) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnunsetenv, AFUNPTR(myunsetenv)));
fptrunsetenv = (int (*)(const CHAR_PTR ))fptr;
}
RTN rtngetenv = RTN_FindByName(img, "getenv");
if (RTN_Valid(rtngetenv) && RTN_IsSafeForProbedReplacement(rtngetenv))
{
OutFile << CurrentTime() << "Inserting probe for getenv at "
<< RTN_Address(rtngetenv) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtngetenv, AFUNPTR(mygetenv)));
fptrgetenv = (CHAR_PTR (*)(const CHAR_PTR ))fptr;
}
RTN rtnperror = RTN_FindByName(img, "perror");
if (RTN_Valid(rtnperror) && RTN_IsSafeForProbedReplacement(rtnperror))
{
OutFile << CurrentTime() << "Inserting probe for perror at "
<< RTN_Address(rtnperror) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnperror, AFUNPTR(myperror)));
fptrperror = (void (*)(const CHAR_PTR ))fptr;
}
RTN rtnmmap = RTN_FindByName(img, "mmap");
if (RTN_Valid(rtnmmap) && RTN_IsSafeForProbedReplacement(rtnmmap))
{
OutFile << CurrentTime() << "Inserting probe for mmap at "
<< RTN_Address(rtnmmap) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnmmap, AFUNPTR(mymmap)));
fptrmmap = (VOID_PTR (*)(VOID_PTR , size_t, int, int, int, off_t))fptr;
}
RTN rtnmunmap = RTN_FindByName(img, "munmap");
if (RTN_Valid(rtnmunmap) && RTN_IsSafeForProbedReplacement(rtnmunmap))
{
OutFile << CurrentTime() << "Inserting probe for munmap at "
<< RTN_Address(rtnmunmap) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnmunmap, AFUNPTR(mymunmap)));
fptrmunmap = (int (*)(VOID_PTR , size_t))fptr;
}
RTN rtnfileno = RTN_FindByName(img, "fileno");
if (RTN_Valid(rtnfileno) && RTN_IsSafeForProbedReplacement(rtnfileno))
{
OutFile << CurrentTime() << "Inserting probe for fileno at "
<< RTN_Address(rtnfileno) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnfileno, AFUNPTR(myfileno)));
fptrfileno = (int (*)(FILE *))fptr;
}
RTN rtngetpid = RTN_FindByName(img, "getpid");
if (RTN_Valid(rtngetpid) && RTN_IsSafeForProbedReplacement(rtngetpid))
{
OutFile << CurrentTime() << "Inserting probe for getpid at "
<< RTN_Address(rtngetpid) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtngetpid, AFUNPTR(mygetpid)));
fptrgetpid = (pid_t (*)(void))fptr;
}
RTN rtngetppid = RTN_FindByName(img, "getppid");
if (RTN_Valid(rtngetppid) && RTN_IsSafeForProbedReplacement(rtngetppid))
{
OutFile << CurrentTime() << "Inserting probe for getppid at " << RTN_Address(rtngetppid) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtngetppid, AFUNPTR(mygetppid)));
fptrgetppid = (pid_t (*)(void))fptr;
}
RTN rtnmemset = RTN_FindByName(img, "memset");
if (RTN_Valid(rtnmemset) && RTN_IsSafeForProbedReplacement(rtnmemset))
{
OutFile << CurrentTime() << "Inserting probe for memset at " << RTN_Address(rtnmemset) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnmemset, AFUNPTR(mymemset)));
fptrmemset = (VOID_PTR (*)(VOID_PTR , int, size_t))fptr;
}
RTN rtnmemcpy = RTN_FindByName(img, "memcpy");
if (RTN_Valid(rtnmemcpy) && RTN_IsSafeForProbedReplacement(rtnmemcpy))
{
OutFile << CurrentTime() << "Inserting probe for memcpy at " << RTN_Address(rtnmemcpy) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnmemcpy, AFUNPTR(mymemcpy)));
fptrmemcpy = (VOID_PTR (*)(VOID_PTR , const VOID_PTR , size_t))fptr;
}
RTN rtnaccess = RTN_FindByName(img, "access");
if (RTN_Valid(rtnaccess) && RTN_IsSafeForProbedReplacement(rtnaccess))
{
OutFile << CurrentTime() << "Inserting probe for access at " << RTN_Address(rtnaccess) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnaccess, AFUNPTR(myaccess)));
fptraccess = (int (*)(const CHAR_PTR , int))fptr;
}
RTN rtnlseek = RTN_FindByName(img, "lseek");
if (RTN_Valid(rtnlseek) && RTN_IsSafeForProbedReplacement(rtnlseek))
{
OutFile << CurrentTime() << "Inserting probe for lseek at " << RTN_Address(rtnlseek) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnlseek, AFUNPTR(mylseek)));
fptrlseek = (off_t (*)(int, off_t, int))fptr;
}
RTN rtnlseek64 = RTN_FindByName(img, "lseek64");
if (RTN_Valid(rtnlseek64) && RTN_IsSafeForProbedReplacement(rtnlseek64))
{
OutFile << CurrentTime() << "Inserting probe for lseek64 at " << RTN_Address(rtnlseek64) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnlseek64, AFUNPTR(mylseek64)));
fptrlseek64 = (off64_t (*)(int, off64_t, int))fptr;
}
RTN rtnfdatasync = RTN_FindByName(img, "fdatasync");
if (RTN_Valid(rtnfdatasync) && RTN_IsSafeForProbedReplacement(rtnfdatasync))
{
OutFile << CurrentTime() << "Inserting probe for fdatasync at " << RTN_Address(rtnfdatasync) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnfdatasync, AFUNPTR(myfdatasync)));
fptrfdatasync = (int (*)(int))fptr;
}
RTN rtnunlink = RTN_FindByName(img, "unlink");
if (RTN_Valid(rtnunlink) && RTN_IsSafeForProbedReplacement(rtnunlink))
{
OutFile << CurrentTime() << "Inserting probe for unlink at " << RTN_Address(rtnunlink) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnunlink, AFUNPTR(myunlink)));
fptrunlink = (int (*)(const CHAR_PTR ))fptr;
}
RTN rtnstrlen = RTN_FindByName(img, "strlen");
if (RTN_Valid(rtnstrlen) && RTN_IsSafeForProbedReplacement(rtnstrlen))
{
OutFile << CurrentTime() << "Inserting probe for strlen at " << RTN_Address(rtnstrlen) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnstrlen, AFUNPTR(mystrlen)));
fptrstrlen = (size_t (*)(const CHAR_PTR ))fptr;
}
RTN rtnwcslen = RTN_FindByName(img, "wcslen");
if (RTN_Valid(rtnwcslen) && RTN_IsSafeForProbedReplacement(rtnwcslen))
{
OutFile << CurrentTime() << "Inserting probe for wcslen at "<< RTN_Address(rtnwcslen) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnwcslen, AFUNPTR(mywcslen)));
fptrwcslen = (size_t (*)(const wchar_t *))fptr;
}
RTN rtnstrcpy = RTN_FindByName(img, "strcpy");
if (RTN_Valid(rtnstrcpy) && RTN_IsSafeForProbedReplacement(rtnstrcpy))
{
OutFile << CurrentTime() << "Inserting probe for strcpy at " << RTN_Address(rtnstrcpy) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnstrcpy, AFUNPTR(mystrcpy)));
fptrstrcpy = (CHAR_PTR (*)(CHAR_PTR , const CHAR_PTR ))fptr;
}
RTN rtnstrncpy = RTN_FindByName(img, "strncpy");
if (RTN_Valid(rtnstrncpy) && RTN_IsSafeForProbedReplacement(rtnstrncpy))
{
OutFile << CurrentTime() << "Inserting probe for strncpy at " << RTN_Address(rtnstrncpy) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnstrncpy, AFUNPTR(mystrcpy)));
fptrstrncpy = (CHAR_PTR (*)(CHAR_PTR , const CHAR_PTR , size_t))fptr;
}
RTN rtnstrcat = RTN_FindByName(img, "strcat");
if (RTN_Valid(rtnstrcat) && RTN_IsSafeForProbedReplacement(rtnstrcat))
{
OutFile << CurrentTime() << "Inserting probe for strcat at " << RTN_Address(rtnstrcat) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnstrcat, AFUNPTR(mystrcat)));
fptrstrcat = (CHAR_PTR (*)(CHAR_PTR , const CHAR_PTR ))fptr;
}
RTN rtnstrstr = RTN_FindByName(img, "strstr");
if (RTN_Valid(rtnstrstr) && RTN_IsSafeForProbedReplacement(rtnstrstr))
{
OutFile << CurrentTime() << "Inserting probe for strstr at " << RTN_Address(rtnstrstr) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnstrstr, AFUNPTR(mystrstr)));
fptrstrstr = (CHAR_PTR (*)(const CHAR_PTR , const CHAR_PTR ))fptr;
}
RTN rtnstrchr0 = RTN_FindByName(img, "strchr0");
if (RTN_Valid(rtnstrchr0) && RTN_IsSafeForProbedReplacement(rtnstrchr0))
{
OutFile << CurrentTime() << "Inserting probe for strchr0 at " << RTN_Address(rtnstrchr0) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnstrchr0, AFUNPTR(mystrchr0)));
fptrstrrchr = (CHAR_PTR (*)(const CHAR_PTR , int))fptr;
}
RTN rtnstrrchr = RTN_FindByName(img, "strrchr");
if (RTN_Valid(rtnstrrchr) && RTN_IsSafeForProbedReplacement(rtnstrrchr))
{
OutFile << CurrentTime() << "Inserting probe for strrchr at "
<< RTN_Address(rtnstrrchr) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnstrrchr, AFUNPTR(mystrrchr)));
fptrstrrchr = (CHAR_PTR (*)(const CHAR_PTR , int))fptr;
}
RTN rtnstrcmp = RTN_FindByName(img, "strcmp");
if (RTN_Valid(rtnstrcmp) && RTN_IsSafeForProbedReplacement(rtnstrcmp))
{
OutFile << CurrentTime() << "Inserting probe for strcmp at " << RTN_Address(rtnstrcmp) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnstrcmp, AFUNPTR(mystrcmp)));
fptrstrcmp = (int (*)(const CHAR_PTR , const CHAR_PTR ))fptr;
}
RTN rtnstrncmp = RTN_FindByName(img, "strncmp");
if (RTN_Valid(rtnstrncmp) && RTN_IsSafeForProbedReplacement(rtnstrncmp))
{
OutFile << CurrentTime() << "Inserting probe for strncmp at " << RTN_Address(rtnstrncmp) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnstrncmp, AFUNPTR(mystrncmp)));
fptrstrncmp = (int (*)(const CHAR_PTR , const CHAR_PTR , size_t))fptr;
}
RTN rtnsigaddset = RTN_FindByName(img, "sigaddset");
if (RTN_Valid(rtnsigaddset) && RTN_IsSafeForProbedReplacement(rtnsigaddset))
{
OutFile << CurrentTime() << "Inserting probe for sigaddset at " << RTN_Address(rtnsigaddset) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsigaddset, AFUNPTR(mysigaddset)));
fptrsigaddset = (int (*)(sigset_t *, int))fptr;
}
RTN rtnsigdelset = RTN_FindByName(img, "sigdelset");
if (RTN_Valid(rtnsigdelset) && RTN_IsSafeForProbedReplacement(rtnsigdelset))
{
OutFile << CurrentTime() << "Inserting probe for sigdelset at "<< RTN_Address(rtnsigdelset) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsigdelset, AFUNPTR(mysigdelset)));
fptrsigdelset = (int (*)(sigset_t *, int))fptr;
}
RTN rtnsigismember = RTN_FindByName(img, "sigismember");
if (RTN_Valid(rtnsigismember) && RTN_IsSafeForProbedReplacement(rtnsigismember))
{
OutFile << CurrentTime() << "Inserting probe for sigismember at " << RTN_Address(rtnsigismember) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsigismember, AFUNPTR(mysigismember)));
fptrsigdelset = (int (*)(sigset_t *, int))fptr;
}
RTN rtnstrerror = RTN_FindByName(img, "strerror");
if (RTN_Valid(rtnstrerror) && RTN_IsSafeForProbedReplacement(rtnstrerror))
{
OutFile << CurrentTime() << "Inserting probe for strerror at " << RTN_Address(rtnstrerror) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnstrerror, AFUNPTR(mystrerror)));
fptrstrerror = (CHAR_PTR (*)(int))fptr;
}
RTN rtnbind = RTN_FindByName(img, "bind");
if (RTN_Valid(rtnbind) && RTN_IsSafeForProbedReplacement(rtnbind))
{
OutFile << CurrentTime() << "Inserting probe for bind at " << RTN_Address(rtnbind) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnbind, AFUNPTR(mybind)));
fptrbind = (int (*)(int, const struct sockaddr *, socklen_t))fptr;
}
RTN rtnlisten = RTN_FindByName(img, "listen");
if (RTN_Valid(rtnlisten) && RTN_IsSafeForProbedReplacement(rtnlisten))
{
OutFile << CurrentTime() << "Inserting probe for listen at " << RTN_Address(rtnlisten) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnlisten, AFUNPTR(mylisten)));
fptrlisten = (int (*)(int, int))fptr;
}
RTN rtnuname = RTN_FindByName(img, "uname");
if (RTN_Valid(rtnuname) && RTN_IsSafeForProbedReplacement(rtnuname))
{
OutFile << CurrentTime() << "Inserting probe for uname at " << RTN_Address(rtnuname) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnuname, AFUNPTR(myuname)));
fptruname = (int (*)(struct utsname *))fptr;
}
RTN rtngethostname = RTN_FindByName(img, "gethostname");
if (RTN_Valid(rtngethostname) && RTN_IsSafeForProbedReplacement(rtngethostname))
{
OutFile << CurrentTime() << "Inserting probe for gethostname at " << RTN_Address(rtngethostname) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtngethostname, AFUNPTR(mygethostname)));
fptrgethostname = (int (*)(CHAR_PTR , size_t))fptr;
}
RTN rtnkill = RTN_FindByName(img, "kill");
if (RTN_Valid(rtnkill) && RTN_IsSafeForProbedReplacement(rtnkill))
{
OutFile << CurrentTime() << "Inserting probe for kill at " << RTN_Address(rtnkill) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnkill, AFUNPTR(mykill)));
fptrkill = (int (*)(pid_t, int))fptr;
}
RTN rtnsched_yield = RTN_FindByName(img, "sched_yield");
if (RTN_Valid(rtnsched_yield) && RTN_IsSafeForProbedReplacement(rtnsched_yield)) {
OutFile << CurrentTime() << "Inserting probe for sched_yield at " << RTN_Address(rtnsched_yield) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsched_yield, AFUNPTR(mysched_yield)));
fptrsched_yield = (int (*)())fptr;
}
RTN rtntimer_settime = RTN_FindByName(img, "timer_settime");
if (RTN_Valid(rtntimer_settime) && RTN_IsSafeForProbedReplacement(rtntimer_settime))
{
OutFile << CurrentTime() << "Inserting probe for timer_settime at " << RTN_Address(rtntimer_settime) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtntimer_settime, AFUNPTR(mytimer_settime)));
fptrtimer_settime = (int (*)(timer_t, int, const struct itimerspec *, struct itimerspec *))fptr;
}
RTN rtnsigaltstack = RTN_FindByName(img, "sigaltstack");
if (RTN_Valid(rtnsigaltstack) && RTN_IsSafeForProbedReplacement(rtnsigaltstack))
{
OutFile << CurrentTime() << "Inserting probe for sigaltstack at " << RTN_Address(rtnsigaltstack) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsigaltstack, AFUNPTR(mysigaltstack)));
fptrsigaltstack = (int (*)(const stack_t *, stack_t *))fptr;
}
RTN rtnioctl = RTN_FindByName(img, "ioctl");
if (RTN_Valid(rtnioctl) && RTN_IsSafeForProbedReplacement(rtnioctl))
{
OutFile << CurrentTime() << "Inserting probe for ioctl at " << RTN_Address(rtnioctl) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnioctl, AFUNPTR(myioctl)));
fptrioctl = (int (*)(int, int, CHAR_PTR ))fptr;
}
RTN rtnflock = RTN_FindByName(img, "flock");
if (RTN_Valid(rtnflock) && RTN_IsSafeForProbedReplacement(rtnflock))
{
OutFile << CurrentTime() << "Inserting probe for flock at " << RTN_Address(rtnflock) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnflock, AFUNPTR(myflock)));
fptrflock = (int (*)(int, int))fptr;
}
RTN rtn__libc_dlopen_mode = RTN_FindByName(img, "__libc_dlopen_mode");
if (RTN_Valid(rtn__libc_dlopen_mode) && RTN_IsSafeForProbedReplacement(rtn__libc_dlopen_mode))
{
OutFile << CurrentTime() << "Inserting probe for __libc_dlopen_mode at " << RTN_Address(rtn__libc_dlopen_mode) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtn__libc_dlopen_mode, AFUNPTR(my__libc_dlopen_mode)));
fptr__libc_dlopen_mode = (VOID_PTR (*)(const CHAR_PTR , int))fptr;
}
RTN rtn__errno_location = RTN_FindByName(img, "__errno_location");
if (RTN_Valid(rtn__errno_location) && RTN_IsSafeForProbedReplacement(rtn__errno_location))
{
OutFile << CurrentTime() << "Inserting probe for __errno_location at " << RTN_Address(rtn__errno_location) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtn__errno_location, AFUNPTR(my__errno_location)));
fptr__errno_location = (INT_PTR (*)())fptr;
}
RTN rtnsyscall = RTN_FindByName(img, "syscall");
if (RTN_Valid(rtnsyscall) && RTN_IsSafeForProbedReplacement(rtnsyscall))
{
OutFile << CurrentTime() << "Inserting probe for syscall at " << RTN_Address(rtnsyscall) << endl;
OutFile.flush();
AFUNPTR fptr = (RTN_ReplaceProbed(rtnsyscall, AFUNPTR(mysyscall)));
fptrsyscall = (int (*)(int, long int, long int, long int, long int, long int, long int, long int))fptr;}
}
// finished instrumentation
}
/* ===================================================================== */
/* Main function */
/* ===================================================================== */
int main(int argc, char *argv[]) {
// Initialize Pin
PIN_InitSymbols();
if (PIN_Init(argc, argv)) {
return Usage();
}
OutFile.open(KnobOutputFile.Value().c_str());
OutFile << hex;
OutFile.setf(ios::showbase);
OutFile << CurrentTime() << "started!" << endl;
OutFile.flush();
// Register the instrumentation callback
IMG_AddInstrumentFunction(ImgLoad, 0);
// Start the application
PIN_StartProgramProbed(); // never returns
return 0;
}
| cyjseagull/SHMA | zsim-nvmain/pin_kit/source/tools/Probes/tpss_lin_libc.cpp | C++ | gpl-2.0 | 102,427 |
<?php
/**
* Functions
*
* @since 1.0
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;
/**
* Allowed post types
*
* @since 1.0.4
* @return array $post_types an array of post types allowed
*/
function edd_wl_allowed_post_types() {
$post_types = apply_filters( 'edd_wl_allowed_post_types', array( 'download' ) );
return $post_types;
}
/**
* Is view page?
*
* @return boolean
*/
function edd_wl_is_view_page() {
$pages = apply_filters( 'edd_wl_is_view_page',
array(
edd_get_option( 'edd_wl_page_view', '' )
)
);
if ( $pages ) {
foreach ( $pages as $page ) {
if ( is_page( $page ) ) {
return true;
}
}
}
return false;
}
/**
* Is edit page?
*
* @return boolean
*/
function edd_wl_is_edit_page() {
$pages = apply_filters( 'edd_wl_is_edit_page',
array(
edd_get_option( 'edd_wl_page_edit', '' )
)
);
if ( $pages ) {
foreach ( $pages as $page ) {
if ( is_page( $page ) ) {
return true;
}
}
}
return false;
}
/**
* Get list ID
* Performs a simple lookup of the 'view' query var
*
* @return int ID of list
* @since 1.0
*/
function edd_wl_get_list_id() {
if ( get_query_var( 'wl_view' ) ) {
$list_id = get_query_var( 'wl_view' );
} elseif ( get_query_var( 'wl_edit' ) ) {
$list_id = get_query_var( 'wl_edit' );
}
if ( $list_id ) {
return apply_filters( 'edd_wl_get_list_id', $list_id );
}
return false;
}
/**
* Gets the downloads of a specific wish list
*
* @param int $wish_list_id the ID of the wish list
* @return array the contents of the wish list
* @since 1.0
*/
function edd_wl_get_wish_list( $list_id = '' ) {
if ( $list_id ) {
// retrieve the wish list
return apply_filters( 'edd_wl_get_wish_list', get_post_meta( $list_id, 'edd_wish_list', true ) );
}
return false;
}
/**
* Has pretty permalinks
*
* @since 1.0
*/
function edd_wl_has_pretty_permalinks() {
global $wp_rewrite;
if ( $wp_rewrite->using_permalinks() ) {
return true;
}
return false;
}
/**
* List is private
*
* This is used to redirect, or prevent viewing or editing of private lists
* @return [type]
*/
function edd_wl_is_private_list() {
if ( get_query_var( 'wl_view' ) ) {
$list_id = get_query_var( 'wl_view' );
} elseif ( get_query_var( 'wl_edit' ) ) {
$list_id = get_query_var( 'wl_edit' );
} else {
$list_id = '';
}
if ( ! $list_id ) {
return;
}
$list_status = get_post_status( $list_id );
if ( 'private' == $list_status && ! edd_wl_is_users_list( $list_id ) && ( edd_wl_is_page( 'view' ) || edd_wl_is_page( 'edit' ) ) ) {
return true;
}
}
/**
* Get the status of a list (post)
*
* @since 1.0
*/
function edd_wl_get_list_status( $post_id = '' ) {
$post_id = isset( $post_id ) ? $post_id : get_the_ID();
$status = get_post_status( $post_id );
switch ( $status ) {
case 'publish':
$status = 'public';
break;
case 'private':
$status = 'private';
break;
}
return $status;
}
/**
* List of statuses
*
* @since 1.0
* @return array statuses
*/
function edd_wl_get_list_statuses() {
$statuses = array(
'public',
'private'
);
return $statuses;
}
/**
* Check if we're on a certain page
*
* @since 1.0
* @return boolean true|false
*/
function edd_wl_is_page( $page = '' ) {
global $edd_options;
switch ( $page ) {
case 'wish-lists':
$id = isset( $edd_options['edd_wl_page'] ) ? $edd_options['edd_wl_page'] : false;
break;
case 'view':
$id = isset( $edd_options['edd_wl_page_view'] ) ? $edd_options['edd_wl_page_view'] : false;
break;
case 'edit':
$id = isset( $edd_options['edd_wl_page_edit'] ) ? $edd_options['edd_wl_page_edit'] : false;
break;
case 'create':
$id = isset( $edd_options['edd_wl_page_create'] ) ? $edd_options['edd_wl_page_create'] : false;
break;
}
if ( is_page( $id ) ) {
return true;
}
return false;
}
/**
* Get Wish List URI
* @return string
*/
function edd_wl_get_wish_list_uri() {
global $edd_options;
$uri = isset( $edd_options['edd_wl_page'] ) ? get_permalink( $edd_options['edd_wl_page'] ) : false;
if ( edd_wl_has_pretty_permalinks() ) {
$url = trailingslashit( $uri );
}
else {
$url = $uri;
}
return esc_url( apply_filters( 'edd_wl_get_wish_list_uri', $url ) );
}
/**
* Get the URI for viewing a wish list
* @return string
*/
function edd_wl_get_wish_list_view_uri( $id = '' ) {
global $edd_options;
$uri = isset( $edd_options['edd_wl_page_view'] ) ? get_permalink( $edd_options['edd_wl_page_view'] ) : false;
if ( edd_wl_has_pretty_permalinks() ) {
$url = trailingslashit( $uri ) . $id;
}
else {
$url = add_query_arg( 'wl_view', $id, $uri );
}
return esc_url( apply_filters( 'edd_wl_get_wish_list_view_uri', $url ) );
}
/**
* Get Wish List Edit URI
* @return string
*/
function edd_wl_get_wish_list_edit_uri( $id = '') {
global $edd_options;
$uri = isset( $edd_options['edd_wl_page_edit'] ) ? get_permalink( $edd_options['edd_wl_page_edit'] ) : false;
if ( edd_wl_has_pretty_permalinks() ) {
$url = trailingslashit( $uri ) . $id;
}
else {
$url = add_query_arg( 'wl_edit', $id, $uri );
}
return esc_url( apply_filters( 'edd_wl_get_wish_list_edit_uri', $url ) );
}
/**
* Get Wish List create URI
* @return string
*/
function edd_wl_get_wish_list_create_uri() {
global $edd_options;
$uri = isset( $edd_options['edd_wl_page_create'] ) ? get_permalink( $edd_options['edd_wl_page_create'] ) : false;
if ( edd_wl_has_pretty_permalinks() ) {
$url = trailingslashit( $uri );
}
else {
$url = $uri;
}
return esc_url( apply_filters( 'edd_wl_get_wish_list_create_uri', $url ) );
}
/**
* Returns the slug of the page selected for view
*
* @since 1.0
* @return string
* @global $edd_options
* @param string $page_name name of page
*/
function edd_wl_get_page_slug( $page_name = '' ) {
global $edd_options;
switch ( $page_name ) {
case 'view':
$page_id = isset( $edd_options['edd_wl_page_view'] ) && 'none' != $edd_options['edd_wl_page_view'] ? $edd_options['edd_wl_page_view'] : null;
break;
case 'edit':
$page_id = isset( $edd_options['edd_wl_page_edit'] ) && 'none' != $edd_options['edd_wl_page_edit'] ? $edd_options['edd_wl_page_edit'] : null;
break;
case 'create':
$page_id = isset( $edd_options['edd_wl_page_create'] ) && 'none' != $edd_options['edd_wl_page_create'] ? $edd_options['edd_wl_page_create'] : null;
break;
}
// get post slug from post object
$slug = isset( $page_id ) ? get_post( $page_id )->post_name : null;
return $slug;
}
/**
* Returns the URL to remove an item from the wish list
*
* @since 1.0
* @global $post
* @param int $cart_key Cart item key
* @param object $post Download (post) object
* @param bool $ajax AJAX?
* @return string $remove_url URL to remove the wish list item
*/
function edd_wl_remove_item_url( $cart_key, $post, $ajax = false ) {
global $post;
if( is_page() ) {
$current_page = add_query_arg( 'page_id', $post->ID, home_url( 'index.php' ) );
} else if( is_singular() ) {
$current_page = add_query_arg( 'p', $post->ID, home_url( 'index.php' ) );
} else {
$current_page = edd_get_current_page_url();
}
$remove_url = add_query_arg( array( 'cart_item' => $cart_key, 'edd_action' => 'remove' ), $current_page );
return esc_url( apply_filters( 'edd_remove_item_url', $remove_url ) );
}
/**
* The query to return the posts on the main wish lists page
* retrieves ids of lists for either logged in user or logged out
*
* @since 1.0
*/
function edd_wl_get_query( $status = array( 'publish', 'private' ) ) {
global $current_user;
get_currentuserinfo();
if ( 'public' == $status ) {
$status = 'publish';
}
// return if user is logged out and they don't have a token
if ( ! is_user_logged_in() && ! edd_wl_get_list_token() )
return null;
// initial query
$query = array(
'post_type' => 'edd_wish_list',
'posts_per_page' => '-1',
'post_status' => $status,
);
// get lists that belong to the currently logged in user
if( is_user_logged_in() ) {
$query['author'] = $current_user->ID;
}
// get token from cookie and lookup lists with that token
if ( ! is_user_logged_in() ) {
$query['meta_query'][] = array(
'key' => 'edd_wl_token',
'value' => edd_wl_get_list_token()
);
}
$posts = new WP_Query( $query );
$ids = array();
if ( $posts->have_posts() ) {
while ( $posts->have_posts() ) {
$posts->the_post();
$ids[] = get_the_ID();
}
wp_reset_postdata();
}
if ( $ids ) {
return $ids;
}
return false;
}
/**
* Add all items in wish list to the cart
*
* Adds all downloads within a taxonomy term to the cart.
*
* @since 1.0.6
* @param int $list_id ID of the list
* @return array Array of IDs for each item added to the cart
*/
function edd_wl_add_all_to_cart( $list_id ) {
$cart_item_ids = array();
$items = edd_wl_get_wish_list( $list_id );
if ( $items ) {
foreach ( $items as $item ) {
// check that they aren't already in the cart
if ( edd_item_in_cart( $item['id'], $item['options'] ) ) {
continue;
}
edd_add_to_cart( $item['id'], $item['options'] );
$cart_item_ids[] = $item['id'];
}
}
}
/**
* Show which lists the current item is already added to
*
* @since 1.0
* @uses edd_wl_item_in_wish_list()
*/
function edd_wl_lists_included( $download_id, $options ) {
ob_start();
$found_lists = edd_wl_item_in_wish_list( $download_id, $options );
if ( $found_lists ) {
$messages = edd_wl_messages();
echo '<p>';
echo $messages['lists_included'];
$list_names = array();
foreach ( $found_lists as $list_id ) {
$list_names[] = get_the_title( $list_id );
}
// comma separate
echo implode(', ', $list_names );
echo '</p>';
}
$html = ob_get_clean();
return apply_filters( 'edd_wl_lists_included', $html );
}
/**
* Checks to see if an item is already in the wish_list and returns a boolean. Modified from edd_item_in_cart()
*
* @since 1.0
*
* @param int $download_id ID of the download to remove
* @param array $options
* @return bool Item in the list or not?
* @todo modify function to accept list ID, or run a search with get_posts or osmething
*/
function edd_wl_item_in_wish_list( $download_id = 0, $options = array(), $list_id = 0 ) {
if ( isset( $list_id ) )
$posts = array( $list_id );
else
$posts = edd_wl_get_query();
if ( $posts ) {
$found_ids = array();
foreach ( $posts as $id ) {
$cart_items = get_post_meta( $id, 'edd_wish_list', true );
$found = false;
if ( $cart_items ) {
foreach ( $cart_items as $item ) {
if ( $item['id'] == $download_id ) {
if ( isset( $options['price_id'] ) && isset( $item['options']['price_id'] ) ) {
if ( $options['price_id'] == $item['options']['price_id'] ) {
$found = true;
break;
}
}
else {
$found = true;
break;
}
}
}
}
// add each found id to array
if ( $found ) {
$found_ids[] = $id;
}
}
return $found_ids;
}
}
/**
* Allow guest creation of Wist List
* @return boolean true if Guests are allowed, false otherwise
*/
function edd_wl_allow_guest_creation() {
global $edd_options;
// return true if 'allow guests' is enabled
if ( ( isset( $edd_options['edd_wl_allow_guests'] ) && 'no' == $edd_options['edd_wl_allow_guests'] ) && ! is_user_logged_in() ) {
return false;
}
return true;
}
/**
* Total price of items in wish list
*
* Used on front end and also admin
* @since 1.0
* @param $list_id ID of list
* @todo update total as items are removed from list via ajax
*/
function edd_wl_get_list_total( $list_id ) {
// get contents of cart
$list_items = get_post_meta( $list_id, 'edd_wish_list', true );
$total = array();
if ( $list_items ) {
foreach ( $list_items as $item ) {
$item_price = edd_get_cart_item_price( $item['id'], $item['options'] );
$item_price = round( $item_price, 2 );
$total[] = $item_price;
}
}
// add up values
$total = array_sum( $total );
$total = esc_html( edd_currency_filter( edd_format_amount( $total ) ) );
return apply_filters( 'edd_wl_list_total', $total );
}
/**
* Let the customer know they have already purchased a particular download
* @param [type] $download_id [description]
* @param [type] $variable_price_id [description]
* @since 1.0
* @return string
*/
function edd_wl_has_purchased( $download_id, $variable_price_id ) {
global $user_ID;
$messages = edd_wl_messages();
$has_purchased = edd_wl_get_purchases( $user_ID, $download_id, $variable_price_id );
if ( $has_purchased ) {
return apply_filters( 'edd_wl_has_purchased', '<span class="edd-wl-item-purchased">' . $messages['item_already_purchased'] . '</span>' );
}
return null;
}
/**
* Get a customer's purchases
* @param [type] $user_id [description]
* @param [type] $download_id [description]
* @param [type] $variable_price_id [description]
* @since 1.0
* @return [type] [description]
*/
function edd_wl_get_purchases( $user_id, $download_id, $variable_price_id = null ) {
$users_purchases = edd_get_users_purchases( $user_id );
$return = false;
if ( $users_purchases ) {
foreach ( $users_purchases as $purchase ) {
$purchased_files = edd_get_payment_meta_downloads( $purchase->ID );
if ( is_array( $purchased_files ) ) {
foreach ( $purchased_files as $download ) {
$variable_prices = edd_has_variable_prices( $download['id'] );
if ( $variable_prices && ! is_null( $variable_price_id ) && $variable_price_id !== false ) {
if ( isset( $download['options']['price_id'] ) && $variable_price_id == $download['options']['price_id'] ) {
$return = true;
break 2;
}
else {
$return = false;
}
}
elseif ( $download_id == $download['id']) {
$return = true;
}
}
}
}
}
return $return;
}
/**
* Validate emails used in the email share box
* @param string $emails string to emails to check
* @return boolean true if all emails are valid, false if one is not valid
*/
function edd_wl_validate_share_emails( $emails ) {
// explode string into array
$emails = explode( ',', $emails );
// remove whitespace and clean
$emails = array_filter( array_map( 'trim', $emails ) );
if ( $emails ) {
foreach ( $emails as $email ) {
if ( ! is_email( $email ) ) {
$valid_email = false;
break;
}
else {
$valid_email = true;
continue;
}
}
}
if ( $valid_email )
return $valid_email;
return null;
}
/**
* Get the Item Position in list
*
* @since 1.0.2
*
* @param int $download_id ID of the download to get position of
* @param array $options array of price options
* @return bool|int|string false if empty list | position of the item in the list
*/
function edd_wl_get_item_position_in_list( $download_id = 0, $list_id = 0, $options = array() ) {
$list_items = edd_wl_get_wish_list( $list_id );
if ( ! is_array( $list_items ) ) {
return false; // Empty list
} else {
foreach ( $list_items as $position => $item ) {
if ( $item['id'] == $download_id ) {
if ( isset( $options['price_id'] ) && isset( $item['options']['price_id'] ) ) {
if ( (int) $options['price_id'] == (int) $item['options']['price_id'] ) {
return $position;
}
} else {
return $position;
}
}
}
}
return false; // Not found
}
| SelaInc/eassignment | wp-content/plugins/edd-wish-lists/includes/functions.php | PHP | gpl-2.0 | 15,386 |
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.language.nativeplatform.internal;
import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import org.gradle.api.DefaultTask;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.Transformer;
import org.gradle.api.file.FileCollection;
import org.gradle.api.internal.file.collections.SimpleFileCollection;
import org.gradle.api.plugins.ExtensionAware;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.util.PatternSet;
import org.gradle.language.PreprocessingTool;
import org.gradle.language.base.LanguageSourceSet;
import org.gradle.language.base.internal.LanguageSourceSetInternal;
import org.gradle.language.base.internal.SourceTransformTaskConfig;
import org.gradle.language.base.internal.registry.LanguageTransform;
import org.gradle.language.nativeplatform.DependentSourceSet;
import org.gradle.language.nativeplatform.HeaderExportingSourceSet;
import org.gradle.language.nativeplatform.tasks.AbstractNativeCompileTask;
import org.gradle.language.nativeplatform.tasks.AbstractNativePCHCompileTask;
import org.gradle.nativeplatform.NativeDependencySet;
import org.gradle.nativeplatform.ObjectFile;
import org.gradle.nativeplatform.SharedLibraryBinarySpec;
import org.gradle.nativeplatform.Tool;
import org.gradle.nativeplatform.internal.NativeBinarySpecInternal;
import org.gradle.platform.base.BinarySpec;
import org.gradle.util.CollectionUtils;
public class CompileTaskConfig implements SourceTransformTaskConfig {
private final LanguageTransform<? extends LanguageSourceSet, ObjectFile> languageTransform;
private final Class<? extends DefaultTask> taskType;
public CompileTaskConfig(LanguageTransform<? extends LanguageSourceSet, ObjectFile> languageTransform, Class<? extends DefaultTask> taskType) {
this.languageTransform = languageTransform;
this.taskType = taskType;
}
public String getTaskPrefix() {
return "compile";
}
public Class<? extends DefaultTask> getTaskType() {
return taskType;
}
public void configureTask(Task task, BinarySpec binary, LanguageSourceSet sourceSet) {
configureCompileTaskCommon((AbstractNativeCompileTask) task, (NativeBinarySpecInternal) binary, (LanguageSourceSetInternal) sourceSet);
configureCompileTask((AbstractNativeCompileTask) task, (NativeBinarySpecInternal) binary, (LanguageSourceSetInternal) sourceSet);
}
private void configureCompileTaskCommon(AbstractNativeCompileTask task, final NativeBinarySpecInternal binary, final LanguageSourceSetInternal sourceSet) {
task.setToolChain(binary.getToolChain());
task.setTargetPlatform(binary.getTargetPlatform());
task.setPositionIndependentCode(binary instanceof SharedLibraryBinarySpec);
// TODO:DAZ Not sure if these both need to be lazy
task.includes(new Callable<Set<File>>() {
public Set<File> call() throws Exception {
return ((HeaderExportingSourceSet) sourceSet).getExportedHeaders().getSrcDirs();
}
});
task.includes(new Callable<List<FileCollection>>() {
public List<FileCollection> call() {
Collection<NativeDependencySet> libs = binary.getLibs((DependentSourceSet) sourceSet);
return CollectionUtils.collect(libs, new Transformer<FileCollection, NativeDependencySet>() {
public FileCollection transform(NativeDependencySet original) {
return original.getIncludeRoots();
}
});
}
});
for (String toolName : languageTransform.getBinaryTools().keySet()) {
Tool tool = (Tool) ((ExtensionAware) binary).getExtensions().getByName(toolName);
if (tool instanceof PreprocessingTool) {
task.setMacros(((PreprocessingTool) tool).getMacros());
}
task.setCompilerArgs(tool.getArgs());
}
}
protected void configureCompileTask(AbstractNativeCompileTask task, final NativeBinarySpecInternal binary, final LanguageSourceSetInternal sourceSet) {
task.setDescription(String.format("Compiles the %s of %s", sourceSet, binary));
task.source(sourceSet.getSource());
final Project project = task.getProject();
task.setObjectFileDir(project.file(String.valueOf(project.getBuildDir()) + "/objs/" + binary.getNamingScheme().getOutputDirectoryBase() + "/" + sourceSet.getFullName()));
// If this task uses a pre-compiled header
if (sourceSet instanceof DependentSourceSet && !((DependentSourceSet) sourceSet).getPreCompiledHeaders().isEmpty()) {
task.setPrefixHeaderFile(((DependentSourceSet)sourceSet).getPrefixHeaderFile());
task.setPreCompiledHeaders(((DependentSourceSet) sourceSet).getPreCompiledHeaders());
task.preCompiledHeaderInclude(new Callable<FileCollection>() {
public FileCollection call() {
Set<AbstractNativePCHCompileTask> pchTasks = binary.getTasks().withType(AbstractNativePCHCompileTask.class).matching(new Spec<AbstractNativePCHCompileTask>() {
@Override
public boolean isSatisfiedBy(AbstractNativePCHCompileTask pchCompileTask) {
return ((DependentSourceSet) sourceSet).getPrefixHeaderFile().equals(pchCompileTask.getPrefixHeaderFile());
}
});
if (!pchTasks.isEmpty()) {
return pchTasks.iterator().next().getOutputs().getFiles().getAsFileTree().matching(new PatternSet().include("**/*.pch", "**/*.gch"));
} else {
return new SimpleFileCollection();
}
}
});
}
binary.binaryInputs(task.getOutputs().getFiles().getAsFileTree().matching(new PatternSet().include("**/*.obj", "**/*.o")));
}
}
| cams7/gradle-samples | plugin/language-native/src/main/groovy/org/gradle/language/nativeplatform/internal/CompileTaskConfig.java | Java | gpl-2.0 | 6,675 |
<?php
/**
* The template for displaying Author Archive pages.
*
* @package bluewave
* @since bluewave 1.0
*/
get_header(); ?>
<section id="primary">
<div id="content" role="main">
<?php if ( have_posts() ) : ?>
<?php
/* Queue the first post, that way we know
* what author we're dealing with (if that is the case).
*
* We reset this later so we can run the loop
* properly with a call to rewind_posts().
*/
the_post();
?>
<header class="page-header">
<h1 class="page-title author"><?php printf( __( 'Author Archives: %s', 'futureis404' ), '<span class="vcard"><a class="url fn n" href="' . get_author_posts_url( get_the_author_meta( "ID" ) ) . '" title="' . esc_attr( get_the_author() ) . '" rel="me">' . get_the_author() . '</a></span>' ); ?></h1>
</header>
<?php
/* Since we called the_post() above, we need to
* rewind the loop back to the beginning that way
* we can run the loop properly, in full.
*/
rewind_posts();
?>
<?php futureis404_content_nav( 'nav-above' ); ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
/* Include the Post-Format-specific template for the content.
* If you want to overload this in a child theme then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'content', get_post_format() );
?>
<?php endwhile; ?>
<?php futureis404_content_nav( 'nav-below' ); ?>
<?php else : ?>
<article id="post-0" class="post no-results not-found">
<header class="entry-header">
<h1 class="entry-title"><?php _e( '糟糕!什么也没有找到。', 'futureis404' ); ?></h1>
</header><!-- .entry-header -->
<div class="entry-content">
<p><?php _e( '看起来我们找不到你要找的东西,也许搜索能帮你。', 'futureis404' ); ?></p>
<?php get_search_form(); ?>
</div><!-- .entry-content -->
</article><!-- #post-0 -->
<?php endif; ?>
</div><!-- #content -->
</section><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?> | jamesyjz/wordpress | wp-content/themes/blue/author.php | PHP | gpl-2.0 | 2,290 |
<?php
session_start();
if (!(isset($_SESSION['login']) && $_SESSION['login'] != ''))
{header ("Location: ../security/login_user.php");}
switch($_SESSION['login'])
{
case "super": break;
case "write":break;
case "read":break;
default:
echo("
<script type='text/javascript'>
alert('You are not logged in.');
window.location='../security/login_user.php';
</script>
");
}
// Set timezone
date_default_timezone_set("America/Chicago");
include("../jackets/db_connect.php"); //==OPEN DATABASE===
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
//===GET POSTS========================================================================
$errorMessage="";
$payment_type="";
$payment_type = htmlspecialchars($_POST["payment_type"],ENT_QUOTES);
if(strlen($payment_type)>20){$errorMessage = "Failure";}
$paid_unpaid = htmlspecialchars($_POST["paid_unpaid"],ENT_QUOTES);
if(strlen($paid_unpaid)>20){$errorMessage = "Failure";}
$month01="";
$month01 = htmlspecialchars($_POST["month01"],ENT_QUOTES);
if(strlen($month01)>10){$errorMessage = "Failure";}
$year01="";
$year01 = htmlspecialchars($_POST["year01"],ENT_QUOTES);
if(strlen($year01)>10){$errorMessage = "Failure";}
$month02 = "";
$month02 = htmlspecialchars($_POST["month02"],ENT_QUOTES);
if(strlen($month02)>10){$errorMessage = "Failure";}
$year02="";
$year02 = htmlspecialchars($_POST["year02"],ENT_QUOTES);
if(strlen($year02)>10){$errorMessage = "Failure";}
$unit="";
$unit = htmlspecialchars($_POST["unit"],ENT_QUOTES);
if(strlen($unit)>10){$errorMessage = "Failure";}
//===ASSEMBLE DATES====================================================================
$start_date = $year01."-".$month01;
if($month02 != "")
{$end_date = $year02."-".$month02;}
else
{$end_date = "no";}
//===START HEADER FOR TABLES============================================================
if($end_date == "no")
{
$header = "Charges due for ".$month01."/".$year01;
$header02 = "Payments made during ".$month01."/".$year01;
}
else
{
$header = "Charges due for ".$month01."/".$year01." through ".$month02."/".$year02;
$header02 = "Payments made during ".$month01."/".$year01." through ".$month02."/".$year02;
}
if($errorMessage=="")
{
if($month01!="")
{
if($db_found)
{
//===CREATE COLUMN NAMES==============================================================================
$column_names = Array("payment_id","schedule_type","last","first","unit","building","date_due",
"date_paid","amount","amount_paid","amount_due");
$column_data_out = implode(",",$column_names);
////////////////////////////////////////////////////////////////////////////////////////////////
//=== GET DATE FOR CHARGES (AND PAYMENTS WHERE SIMILAR) =========
////////////////////////////////////////////////////////////////////////////////////////////////
//===GET ALL FIELDS FROM PAYMENT TABLE================================================================
//===WITHIN WHILE LOOP GET VALUES FROM OTHER TABLES===================================================
$field_data = Array();
$sql = "SELECT * FROM payments ORDER BY schedule_type;";
$result = mysql_query($sql);
$total_amount=0; // TOTAL AMOUNT===================
$total_amount_paid=0; // TOTAL AMOUNT PAID==============
$total_amount_outstanding=0; // TOTAL AMOUNT OUTSTANDING=======
while($row_payment = mysql_fetch_assoc($result)) //loop through payments in payment table
{
//===SELECT DATES FOR PERIOD==========================================================================
$date_due_array = explode("-",$row_payment['date_due']);
$check_date = "no";
if($end_date=="no")
{
if($year01==$date_due_array[0] && $month01==$date_due_array[1])
{
$check_date = "yes";
}
}
else
{
if($year01==$year02)
{
if($date_due_array[0]==$year01 && $date_due_array[1]>=$month01 && $date_due_array[1]<=$month02)
{
$check_date = "yes";
}
}
else
{
if($date_due_array[0]==$year01 && $date_due_array[1]>=$month01)
{
$check_date = "yes";
}
if($date_due_array[0]==$year02 && $date_due_array[1]<=$month02)
{
$check_date = "yes";
}
if($date_due_array[0]>$year01 && $date_due_array[0]<$year02)
{
$check_date = "yes";
}
}
} // end check date
//===IF DATE, PAYMENT TYPE, AND UNIT ARE CORRECT, PUSH DATA INTO ARRAY $field_data==========================
if($check_date=="yes")
{
if( ($row_payment['schedule_type']==$payment_type) || ($payment_type=="all") )
{
$row_array = Array();
$schedule_id = $row_payment['schedule_id'];
array_push($row_array,$row_payment['payment_id']);
array_push($row_array,$row_payment['schedule_type']);
//===GET CUSTOMER DATA FROM CUSTOMERS TABLE===========================================================
$customer_id = $row_payment['customer_id'];
$sql = "SELECT last, first FROM customers WHERE customerID=$customer_id;";
$result_customers = mysql_query($sql);
$row_customer = mysql_fetch_assoc($result_customers);
array_push($row_array,$row_customer['last']);
array_push($row_array,$row_customer['first']);
//===GET CUSTOMER UNIT FROM UNITS TABLE================================================================
$sql = "SELECT * FROM units;";
$result_units = mysql_query($sql);
$hold_unit = "";
$hold_unit_check = "";
while($row_unit = mysql_fetch_assoc($result_units))
{
if($row_unit['current_tenant01']==$customer_id || $row_unit['current_tenant02']==$customer_id || $row_unit['current_tenant03']==$customer_id || $row_unit['current_tenant04']==$customer_id || $row_unit['current_tenant05']==$customer_id)
{
if(!strpos($hold_unit,$row_unit['unit']))
{
if($hold_unit == "")
{
$hold_unit = $row_unit['unit'];
$hold_unit_check = $row_unit['unit'];
}
else
{}
// {$hold_unit = $hold_unit."/".$row_unit['unit'];}
}
}
}
array_push($row_array,$hold_unit);
array_push($row_array,"51 E. John");
//===PUSH PAYMENT DATES=========================================================================
array_push($row_array,$row_payment['date_due']);
$row_paid_total = 0;
$date_paid = "";
for($i=0;$i<12;$i++)
{
if($i<9)
{
$name_paid="amount_paid0".($i+1);
$name_date="date_paid0".($i+1);
}
else
{
$name_paid="amount_paid".($i+1);
$name_date="date_paid".($i+1);
}
if($row_payment[$name_date]!=0)
{
$row_paid_total = $row_paid_total + $row_payment[$name_paid];
$date_paid = $row_payment[$name_date];
}
}
array_push($row_array,$date_paid);
array_push($row_array,$row_payment['amount']);
array_push($row_array,$row_paid_total);
$amount_due = $row_payment['amount']-$row_paid_total;
array_push($row_array,$amount_due);
//===PUSH 1D ROW INTO 2D FIELD DATA / UPDATE TOTALS=====================================================
if($paid_unpaid=="all" || ($paid_unpaid=="paid" && $amount_due==0)
|| ($paid_unpaid=="unpaid" && $amount_due!=0))
{array_push($field_data,$row_array);}
$total_amount += $row_payment['amount'];
$total_amount_paid += $row_paid_total;
}// end if correct schedule type
}// end if $check_date
}// end while rows from payment table
//===END WHILE THROUGH PAYMENTS=========================================================================
//===IMPLODE DATA FOR JAVASCRIPT========================================================================
$field_data_out = Array();
$field_data_hold = Array();
foreach($field_data as $row_field_data)
{
$hold = implode(",",$row_field_data);
if($hold!="")
{
array_push($field_data_hold,$hold);
}
}
$field_data_out = implode(";",$field_data_hold);
////////////////////////////////////////////////////////////////////////////////////////////////
//=== GET DATA FOR PAYMENTS =========
////////////////////////////////////////////////////////////////////////////////////////////////
//===GET ALL FIELDS FROM CHECKS TABLE================================================================
//===WITHIN WHILE LOOP GET VALUES FROM OTHER TABLES===================================================
//===CREATE COLUMN NAMES==============================================================================
$column_names02 = array("Check ID","Amount","Date Paid","Last","First","Unit","Payment ID","Amount","Date Due","Payment Type");
$column_data02_out = implode(",",$column_names02);
$field_data02 = array();
$sql = "SELECT * FROM checks ORDER BY check_id;";
$result = mysql_query($sql);
while($row_checks=mysql_fetch_assoc($result))
{//print_r($row_checks);echo("</br>");;
//===SELECT DATES FOR PERIOD==========================================================================
$date_paid_array = explode("-",$row_checks['date']);
$check_date = "no";
if($end_date=="no")
{
if($year01==$date_paid_array[0] && $month01==$date_paid_array[1])
{$check_date = "yes";}
}
else
{
if($year01==$year02)
{
if($date_paid_array[0]==$year01 && $date_paid_array[1]>=$month01 && $date_paid_array[1]<=$month02)
{$check_date = "yes";}
}
else
{
if($date_paid_array[0]==$year01 && $date_paid_array[1]>=$month01)
{ $check_date = "yes";}
if($date_paid_array[0]==$year02 && $date_paid_array[1]<=$month02)
{$check_date = "yes";}
if($date_paid_array[0]>$year01 && $date_paid_array[0]<$year02)
{$check_date = "yes";}
}
} // end check date
//===IF DATE, PAYMENT TYPE, AND UNIT ARE CORRECT, PUSH DATA INTO ARRAY $field_data==========================
if($check_date=="yes")
{
$row_array02 = array();
for($i=1;$i<9;$i++)
{
if($i<10)
{$payment_id_name="payment_id0".$i;}
else
{$payment_id_name="payment_id0".$i;}
$payment_id = $row_checks[$payment_id_name];
if($payment_id != 0)
{
$sql02 = "SELECT * FROM payments WHERE payment_id='$payment_id';";
$result02 = mysql_query($sql02);
while($row_payment = mysql_fetch_assoc($result02))
{
$row_paid_total = 0;
$date_paid = "";
$payment_count = 1;
for($j=0;$j<12;$j++)
{
if($j<9)
{
$name_paid="amount_paid0".($j+1);
$name_date="date_paid0".($j+1);
}
else
{
$name_paid="amount_paid".($j+1);
$name_date="date_paid".($j+1);
}
if($row_payment[$name_date]!=0)
{
$row_paid_total = $row_paid_total + $row_payment[$name_paid];
$date_paid = $row_payment[$name_date];
}
}
$sql03 = "SELECT * FROM customers WHERE customerID=".$row_payment['customer_id'].";";
$result03 = mysql_query($sql03);
$row_customers = mysql_fetch_assoc($result03);
//===GET CUSTOMER UNIT FROM UNITS TABLE================================================================
$sql = "SELECT * FROM units;";
$result_units = mysql_query($sql);
$hold_unit = "";
$hold_unit_check = "";
while($row_unit = mysql_fetch_assoc($result_units))
{
if($row_unit['current_tenant01']==$customer_id || $row_unit['current_tenant02']==$customer_id || $row_unit['current_tenant03']==$customer_id || $row_unit['current_tenant04']==$customer_id || $row_unit['current_tenant05']==$customer_id)
{
if(!strpos($hold_unit,$row_unit['unit']))
{
if($hold_unit == "")
{
$hold_unit = $row_unit['unit'];
$hold_unit_check = $row_unit['unit'];
}
else
{}
// {$hold_unit = $hold_unit."/".$row_unit['unit'];}
}
}
}
$row_array02 = array($row_checks['check_id'],$row_checks['amount'],$date_paid,
$row_customers['last'],$row_customers['first'],
$hold_unit,$payment_id,$row_paid_total,
$row_payment['date_due'],$row_payment['schedule_type']);
array_push($field_data02,$row_array02);
$payment_count = $payment_count+1;
}//==end while $row_payment
}// end if payment exists
}//end for through all payments for a check
}// end if $check_date
}//===END WHILE CHECKS===
//===END WHILE THROUGH PAYMENTS=========================================================================
//===IMPLODE DATA FOR JAVASCRIPT========================================================================
$field_data02_out = Array();
$field_data02_hold = Array();
foreach($field_data02 as $row_field_data02)
{
$hold = implode(",",$row_field_data02);
if($hold!="")
{
array_push($field_data02_hold,$hold);
}
}
$field_data02_out = implode(";",$field_data02_hold);
mysql_close($db_handle);
}//end if db_found
}// if customer id exists
} //end if no length error
else
{header('Location: ./login_user.php');}//end if length error message
}// end if request post
?>
<!--===END PHP==================================================================-->
<!--============================================================================-->
<!--===START HTML===============================================================-->
<html>
<head>
<link rel="stylesheet" type="text/css" href="../style/style.css" />
<script type="text/javascript" src="../functions/report_table.js"></script>
<link href="../functions/calendar/calendar/calendar.css" rel="stylesheet" type="text/css" />
<script language="javascript" src="../functions/calendar/calendar/calendar.js"></script>
<title>Create Report for Time Period</title>
</head>
<body>
<div class='top'>
<font class='main'>
Create Report for Time Period
</font>
</div>
<?php include("../jackets/main_jacket.php");
?>
<div class="main">
<div class="text_in">
<div class="box_width">
<font class="box_head">Create Report</font></br>
<hr class="box_line">
<!--===START FORM===============================================================-->
<form name="customer_search_form" method="post" action="output_report_period01.php">
<table class="input">
<tr><td>Beginning Period</td>
<td>
<select name="month01">
<option></option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
</td>
<td>
<select name="year01">
<option></option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
</td>
</td>
<tr><td>Ending Period</td>
<td>
<select name="month02">
<option></option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
</td>
<td>
<select name="year02">
<option></option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
</td>
</tr>
<!--===SELECT PAYMENT TYPE TO VIEW==============================================-->
<tr><td>Select Payment Types:</td>
<td>
<select name="payment_type">
<option value="all" selected="selected">All</option>
<option value="rent">Rent</option>
<option value="deposit">Deposit</option>
<option value="onetime">Onetime</option>
<option value="key_deposit">Key Deposit</option>
<option value="parking_key_deposit">Parking Key Deposit</option>
<option value="parking_monthly">Parking, Monthly</option>
<option value="parking_prepay">Parking, Prepay</option>
<option value="utilities_overage">Utilities Overage</option>
</select>
</td>
</tr>
<!--===SELECT PAID OR UNPAID==============================================-->
<tr><td>Select Paid or Unpaid:</td>
<td>
<select name="paid_unpaid">
<option value="all" selected="selected">All</option>
<option value="paid">Paid</option>
<option value="unpaid">Unpaid</option>
</select>
</td>
</tr>
<!--===SELECT UNIT TO VIEW=========================================-->
<!--
<tr><td>Unit:</td>
<td>
<select name="unit">
<option value="all" selected="selected">All</option>
<option value="102">102</option>
<option value="103">103</option>
<option value="104">104</option>
<option value="105">105</option>
<option value="106">106</option>
<option value="107">107</option>
<option value="108">108</option>
<option value="109">109</option>
<option value="110">110</option>
<option value="111">111</option>
<option value="112">112</option>
<option value="113">113</option>
<option value="114">114</option>
<option value="115">115</option>
<option value="116">116</option>
<option value="117">117</option>
<option value="118">118</option>
<option value="202">202</option>
<option value="203">203</option>
<option value="204">204</option>
<option value="205">205</option>
<option value="206">206</option>
<option value="207">207</option>
<option value="208">208</option>
<option value="209">209</option>
<option value="210">210</option>
<option value="211">211</option>
<option value="212">212</option>
<option value="213">213</option>
<option value="214">214</option>
<option value="215">215</option>
<option value="216">216</option>
<option value="217">217</option>
<option value="218">218</option>
<option value="301">301</option>
<option value="302">302</option>
<option value="303">303</option>
<option value="304">304</option>
<option value="305">305</option>
<option value="306">306</option>
<option value="307">307</option>
<option value="308">308</option>
<option value="309">309</option>
<option value="310">310</option>
<option value="311">311</option>
<option value="312">312</option>
<option value="313">313</option>
<option value="314">314</option>
<option value="315">315</option>
<option value="316">316</option>
<option value="317">317</option>
<option value="318">318</option>
<option value="401">401</option>
<option value="402">402</option>
<option value="403">403</option>
<option value="404">404</option>
<option value="405">405</option>
<option value="406">406</option>
<option value="407">407</option>
<option value="408">408</option>
<option value="409">409</option>
<option value="410">410</option>
<option value="411">411</option>
<option value="412">412</option>
<option value="413">413</option>
<option value="414">414</option>
<option value="415">415</option>
<option value="416">416</option>
<option value="417">417</option>
<option value="418">418</option>
</select>
</tr>
-->
<!--===SUBMIT=====================================================================-->
<tr><td>
<input type="submit" value="View entries"/>
</td></tr>
</table>
</form>
</div>
<!--===END MAIN FORM==============================================================-->
<div class="box_width" id="build_table">
</div>
<!--===FORM FOR EXPORT TO EXCEL===================================================-->
<div class="box_width" id="choose_table">
<form method="post" action="../functions/excel_out_post.php" name="post_excel">
<input type="hidden" value="<?php echo($column_data_out); ?>" name="column_data_out" />
<input type="hidden" value="<?php echo($field_data_out); ?>" name="field_data_out" />
<input type="submit" value="Export Excel File" name="export_excel"/>
</form>
</div>
<div class="box_width" id="build_table02">
</div>
<!--===FORM FOR EXPORT TO EXCEL===================================================-->
<div class="box_width" id="choose_table02">
<form method="post" action="../functions/excel_out_post.php" name="post_excel">
<input type="hidden" value="<?php echo($column_data02_out); ?>" name="column_data02_out" />
<input type="hidden" value="<?php echo($field_data02_out); ?>" name="field_data02_out" />
<input type="submit" value="Export Excel File" name="export_excel"/>
</form>
</div>
<!--===CREATE TABLES===============================================================-->
<script type="text/javascript">
initial_table('<?php echo($column_data_out); ?>','<?php echo($field_data_out); ?>','<?php echo($header); ?>','<?php echo($total_amount); ?>','<?php echo($total_amount_paid); ?>');
</script>
<script type="text/javascript">
initial_table02('<?php echo($column_data02_out); ?>','<?php echo($field_data02_out); ?>','<?php echo($header02); ?>',100);
</script>
</body>
</html>
| slavenas/propman | output_xls/output_report_period01.php | PHP | gpl-2.0 | 30,403 |
<?php
/**
* The base configurations of the WordPress.
*
* This file has the following configurations: MySQL settings, Table Prefix,
* Secret Keys, and ABSPATH. You can find more information by visiting
* {@link http://codex.wordpress.org/Editing_wp-config.php Editing wp-config.php}
* Codex page. You can get the MySQL settings from your web host.
*
* This file is used by the wp-config.php creation script during the
* installation. You don't have to use the web site, you can just copy this file
* to "wp-config.php" and fill in the values.
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'wpDataSite');
/** MySQL database username */
define('DB_USER', 'root');
/** MySQL database password */
define('DB_PASSWORD', 'root');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define('AUTH_KEY', 'opO;*{[CXo[{(|[84u5=!>wOs|eIys+z=k@#8f8`ZiN1{ y~22qyE14oBzK$K[<C');
define('SECURE_AUTH_KEY', '!a*c3yG]5pdj4/,CvM(x(3jXp9(#P#Y_}zDLV+@2~-IrDp;20|tr(IXA}pIpcx-B');
define('LOGGED_IN_KEY', 'uO$pn~gd8=|S21ejYjY&NJOt$Xx-7Ge}xWIIQ-g+!{[DT(&)ME}iQ!qAbwo$G_(#');
define('NONCE_KEY', ':ZaZF55/~Sq>j/g9#Kl_dcA>9N.5O+oEPC>=G?166qvGGY=Hc>hUY#& )h@vm&d2');
define('AUTH_SALT', 'D_GwhV?&40#|z-.yq..-QwXColl5<:g#Bs;|{vlA O!D<3H&Gact-rb#rDQQmIcl');
define('SECURE_AUTH_SALT', ']@bW$iAH?d0y2DL0z@a]GOUz4NU5=^1K5dQFr?JADrcRauMN/,wEJ<+Q]9{zR-3r');
define('LOGGED_IN_SALT', 'Ffj:A|_+k;c}o@Q&i,h1nf?/rm5[E+h+>_IZ+BJJ$a-K]|d:q?^&[IovV@eTPUun');
define('NONCE_SALT', 'Y c-%Fg]Q+7W*O#A1^D)OmOKkiO7[Zyr!k|6{<rX=x$w^v)l6j-afXERiB!?{]l6');
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each a unique
* prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp_';
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*/
define('WP_DEBUG', false);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
| Anthonvg/Site-Wp | wp-config.php | PHP | gpl-2.0 | 3,009 |