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
/** * OWASP Benchmark Project v1.2beta * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest01687") public class BenchmarkTest01687 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String queryString = request.getQueryString(); String paramval = "vector"+"="; int paramLoc = -1; if (queryString != null) paramLoc = queryString.indexOf(paramval); if (paramLoc == -1) { response.getWriter().println("getQueryString() couldn't find expected parameter '" + "vector" + "' in query string."); return; } String param = queryString.substring(paramLoc + paramval.length()); // 1st assume "vector" param is last parameter in query string. // And then check to see if its in the middle of the query string and if so, trim off what comes after. int ampersandLoc = queryString.indexOf("&", paramLoc); if (ampersandLoc != -1) { param = queryString.substring(paramLoc + paramval.length(), ampersandLoc); } param = java.net.URLDecoder.decode(param, "UTF-8"); String bar = new Test().doSomething(param); try { java.security.MessageDigest md = java.security.MessageDigest.getInstance("SHA1", "SUN"); byte[] input = { (byte)'?' }; Object inputParam = bar; if (inputParam instanceof String) input = ((String) inputParam).getBytes(); if (inputParam instanceof java.io.InputStream) { byte[] strInput = new byte[1000]; int i = ((java.io.InputStream) inputParam).read(strInput); if (i == -1) { response.getWriter().println("This input source requires a POST, not a GET. Incompatible UI for the InputStream source."); return; } input = java.util.Arrays.copyOf(strInput, i); } md.update(input); byte[] result = md.digest(); java.io.File fileTarget = new java.io.File( new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir),"passwordFile.txt"); java.io.FileWriter fw = new java.io.FileWriter(fileTarget,true); //the true will append the new data fw.write("hash_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n"); fw.close(); response.getWriter().println("Sensitive value '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input)) + "' hashed and stored<br/>"); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("Problem executing hash - TestCase java.security.MessageDigest.getInstance(java.lang.String,java.lang.String)"); throw new ServletException(e); } catch (java.security.NoSuchProviderException e) { System.out.println("Problem executing hash - TestCase java.security.MessageDigest.getInstance(java.lang.String,java.lang.String)"); throw new ServletException(e); } response.getWriter().println("Hash Test java.security.MessageDigest.getInstance(java.lang.String,java.lang.String) executed"); } // end doPost private class Test { public String doSomething(String param) throws ServletException, IOException { String bar = ""; if (param != null) bar = param.split(" ")[0]; return bar; } } // end innerclass Test } // end DataflowThruInnerClass
andresriancho/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01687.java
Java
gpl-2.0
4,474
/** * ownCloud Android client application * * @author David A. Velasco * Copyright (C) 2016 ownCloud GmbH. * * 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.owncloud.android.ui.fragment; import android.content.Context; import android.support.v4.app.Fragment; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.files.services.FileDownloader; import com.owncloud.android.files.services.FileUploader; import com.owncloud.android.ui.activity.ComponentsGetter; /** * Common methods for {@link Fragment}s containing {@link OCFile}s */ public abstract class FileFragment extends Fragment { private OCFile mFile; protected ContainerActivity mContainerActivity; /** * Creates an empty fragment. * * It's necessary to keep a public constructor without parameters; the system uses it when * tries to reinstantiate a fragment automatically. */ public FileFragment() { mFile = null; } /** * Getter for the hold {@link OCFile} * * @return The {@link OCFile} hold */ public OCFile getFile() { return mFile; } protected void setFile(OCFile file) { mFile = file; } /** * {@inheritDoc} */ @Override public void onAttach(Context context) { super.onAttach(context); try { mContainerActivity = (ContainerActivity) context; } catch (ClassCastException e) { throw new ClassCastException(context.toString() + " must implement " + ContainerActivity.class.getSimpleName()); } } /** * {@inheritDoc} */ @Override public void onDetach() { mContainerActivity = null; super.onDetach(); } public void onSyncEvent(String syncEvent, boolean success, OCFile updatedFile) { if (syncEvent.equals(FileUploader.getUploadStartMessage())) { updateViewForSyncInProgress(); } else if (syncEvent.equals(FileUploader.getUploadFinishMessage())) { if (success) { if (updatedFile != null) { onFileMetadataChanged(updatedFile); } else { onFileMetadataChanged(); } } updateViewForSyncOff(); } else if (syncEvent.equals(FileDownloader.getDownloadAddedMessage())) { updateViewForSyncInProgress(); } else if (syncEvent.equals(FileDownloader.getDownloadFinishMessage())) { if (success) { if (updatedFile != null) { onFileMetadataChanged(updatedFile); } else { onFileMetadataChanged(); } onFileContentChanged(); } updateViewForSyncOff(); } } public abstract void updateViewForSyncInProgress(); public abstract void updateViewForSyncOff(); public abstract void onTransferServiceConnected(); public abstract void onFileMetadataChanged(OCFile updatedFile); public abstract void onFileMetadataChanged(); public abstract void onFileContentChanged(); /** * Interface to implement by any Activity that includes some instance of FileListFragment * Interface to implement by any Activity that includes some instance of FileFragment */ public interface ContainerActivity extends ComponentsGetter { /** * Request the parent activity to show the details of an {@link OCFile}. * * @param file File to show details */ public void showDetails(OCFile file); ///// TO UNIFY IN A SINGLE CALLBACK METHOD - EVENT NOTIFICATIONs -> something happened // inside the fragment, MAYBE activity is interested --> unify in notification method /** * Callback method invoked when a the user browsed into a different folder through the * list of files * * @param folder */ public void onBrowsedDownTo(OCFile folder); } }
PauloSantos13/android
src/com/owncloud/android/ui/fragment/FileFragment.java
Java
gpl-2.0
4,730
<?php die("Access Denied"); ?>#x#a:2:{s:6:"output";s:0:"";s:6:"result";s:3:"306";}
jolay/pesatec
cache/mod_vvisit_counter/860aea6b5aac75573e8d7d8ebc839c97-cache-mod_vvisit_counter-80dbc0d882054809874a199a075389cf.php
PHP
gpl-2.0
82
var azure = require("azure"); var Promise = require("bluebird"); var config = require("../config"); exports.set = function(container, id, name, path, size) { return new Promise(function(resolve, reject) { var service = azure.createBlobService(config.call(this, "storageName"), config.call(this, "storageKey")); service.createContainerIfNotExists(container, function (err) { if (err) reject(new Error("Error creating container: " + err)); else { service.createBlockBlobFromFile(container, id + "-" + name, path, function (err, result) { if (err) reject(new Error("Error while creating block blob from stream: " + err)); resolve({ container: result.container, id: id, name: name, file: result.blob, size: size }); }) } }); }); }; exports.get = function(container, name, stream) { return new Promise(function(resolve, reject) { var service = azure.createBlobService(config.call(this, "storageName"), config.call(this, "storageKey")); service.createContainerIfNotExists(container, function (err) { if (err) reject(new Error("Error creating container: " + err)); else { service.getBlobToStream(container, name, stream, function (err) { if (err) reject(new Error("Error while creating block blob from stream: " + err)); resolve(); }) } }); }); };
chrisharrington/Leaf
storage/storage.js
JavaScript
gpl-2.0
1,333
/*************************************************************************** qgsrendererrasterpropertieswidget.cpp --------------------- begin : May 2016 copyright : (C) 2016 by Nathan Woodrow email : woodrow dot nathan at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgsrendererrasterpropertieswidget.h" #include "qgis.h" #include "qgsmapcanvas.h" #include "qgsbrightnesscontrastfilter.h" #include "qgshuesaturationfilter.h" #include "qgsrasterlayer.h" #include "qgsrasterrendererwidget.h" #include "qgsrasterrendererregistry.h" #include "qgssinglebandgrayrendererwidget.h" #include "qgssinglebandpseudocolorrendererwidget.h" #include "qgsmultibandcolorrendererwidget.h" #include "qgspalettedrendererwidget.h" #include "qgshillshaderendererwidget.h" #include "qgsrasterresamplefilter.h" #include "qgsbilinearrasterresampler.h" #include "qgscubicrasterresampler.h" #include "qgsmultibandcolorrenderer.h" #include "qgssinglebandgrayrenderer.h" #include "qgsapplication.h" #include "qgsmessagelog.h" static void _initRendererWidgetFunctions() { static bool sInitialized = false; if ( sInitialized ) return; QgsApplication::rasterRendererRegistry()->insertWidgetFunction( QStringLiteral( "paletted" ), QgsPalettedRendererWidget::create ); QgsApplication::rasterRendererRegistry()->insertWidgetFunction( QStringLiteral( "multibandcolor" ), QgsMultiBandColorRendererWidget::create ); QgsApplication::rasterRendererRegistry()->insertWidgetFunction( QStringLiteral( "singlebandpseudocolor" ), QgsSingleBandPseudoColorRendererWidget::create ); QgsApplication::rasterRendererRegistry()->insertWidgetFunction( QStringLiteral( "singlebandgray" ), QgsSingleBandGrayRendererWidget::create ); QgsApplication::rasterRendererRegistry()->insertWidgetFunction( QStringLiteral( "hillshade" ), QgsHillshadeRendererWidget::create ); sInitialized = true; } QgsRendererRasterPropertiesWidget::QgsRendererRasterPropertiesWidget( QgsMapLayer *layer, QgsMapCanvas *canvas, QWidget *parent ) : QgsMapLayerConfigWidget( layer, canvas, parent ) { mRasterLayer = qobject_cast<QgsRasterLayer *>( layer ); if ( !mRasterLayer ) return; setupUi( this ); connect( mResetColorRenderingBtn, &QToolButton::clicked, this, &QgsRendererRasterPropertiesWidget::mResetColorRenderingBtn_clicked ); _initRendererWidgetFunctions(); mZoomedInResamplingComboBox->insertItem( 0, tr( "Nearest neighbour" ) ); mZoomedInResamplingComboBox->insertItem( 1, tr( "Bilinear" ) ); mZoomedInResamplingComboBox->insertItem( 2, tr( "Cubic" ) ); mZoomedOutResamplingComboBox->insertItem( 0, tr( "Nearest neighbour" ) ); mZoomedOutResamplingComboBox->insertItem( 1, tr( "Average" ) ); connect( cboRenderers, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsRendererRasterPropertiesWidget::rendererChanged ); connect( mSliderBrightness, &QAbstractSlider::valueChanged, mBrightnessSpinBox, &QSpinBox::setValue ); connect( mBrightnessSpinBox, static_cast < void ( QSpinBox::* )( int ) > ( &QSpinBox::valueChanged ), mSliderBrightness, &QAbstractSlider::setValue ); connect( mSliderContrast, &QAbstractSlider::valueChanged, mContrastSpinBox, &QSpinBox::setValue ); connect( mContrastSpinBox, static_cast < void ( QSpinBox::* )( int ) > ( &QSpinBox::valueChanged ), mSliderContrast, &QAbstractSlider::setValue ); // Connect saturation slider and spin box connect( sliderSaturation, &QAbstractSlider::valueChanged, spinBoxSaturation, &QSpinBox::setValue ); connect( spinBoxSaturation, static_cast < void ( QSpinBox::* )( int ) > ( &QSpinBox::valueChanged ), sliderSaturation, &QAbstractSlider::setValue ); // Connect colorize strength slider and spin box connect( sliderColorizeStrength, &QAbstractSlider::valueChanged, spinColorizeStrength, &QSpinBox::setValue ); connect( spinColorizeStrength, static_cast < void ( QSpinBox::* )( int ) > ( &QSpinBox::valueChanged ), sliderColorizeStrength, &QAbstractSlider::setValue ); // enable or disable saturation slider and spin box depending on grayscale combo choice connect( comboGrayscale, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsRendererRasterPropertiesWidget::toggleSaturationControls ); // enable or disable colorize colorbutton with colorize checkbox connect( mColorizeCheck, &QAbstractButton::toggled, this, &QgsRendererRasterPropertiesWidget::toggleColorizeControls ); // Just connect the spin boxes because the sliders update the spinners connect( mBrightnessSpinBox, static_cast < void ( QSpinBox::* )( int ) > ( &QSpinBox::valueChanged ), this, &QgsPanelWidget::widgetChanged ); connect( mContrastSpinBox, static_cast < void ( QSpinBox::* )( int ) > ( &QSpinBox::valueChanged ), this, &QgsPanelWidget::widgetChanged ); connect( spinBoxSaturation, static_cast < void ( QSpinBox::* )( int ) > ( &QSpinBox::valueChanged ), this, &QgsPanelWidget::widgetChanged ); connect( spinColorizeStrength, static_cast < void ( QSpinBox::* )( int ) > ( &QSpinBox::valueChanged ), this, &QgsPanelWidget::widgetChanged ); connect( btnColorizeColor, &QgsColorButton::colorChanged, this, &QgsPanelWidget::widgetChanged ); connect( mBlendModeComboBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsPanelWidget::widgetChanged ); connect( mZoomedInResamplingComboBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsPanelWidget::widgetChanged ); connect( mZoomedOutResamplingComboBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsPanelWidget::widgetChanged ); connect( mMaximumOversamplingSpinBox, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsPanelWidget::widgetChanged ); // finally sync to the layer - even though some actions may emit widgetChanged signal, // this is not a problem - nobody is listening to our signals yet syncToLayer( mRasterLayer ); connect( mRasterLayer, &QgsMapLayer::styleChanged, this, &QgsRendererRasterPropertiesWidget::refreshAfterStyleChanged ); } void QgsRendererRasterPropertiesWidget::setMapCanvas( QgsMapCanvas *canvas ) { mMapCanvas = canvas; } void QgsRendererRasterPropertiesWidget::rendererChanged() { QString rendererName = cboRenderers->currentData().toString(); setRendererWidget( rendererName ); emit widgetChanged(); } void QgsRendererRasterPropertiesWidget::apply() { if ( QgsBrightnessContrastFilter *brightnessFilter = mRasterLayer->brightnessFilter() ) { brightnessFilter->setBrightness( mSliderBrightness->value() ); brightnessFilter->setContrast( mSliderContrast->value() ); } if ( QgsRasterRendererWidget *rendererWidget = dynamic_cast<QgsRasterRendererWidget *>( stackedWidget->currentWidget() ) ) { rendererWidget->doComputations(); if ( QgsRasterRenderer *newRenderer = rendererWidget->renderer() ) { // there are transparency related data stored in renderer instances, but they // are not configured in the widget, so we need to copy them over from existing renderer if ( QgsRasterRenderer *oldRenderer = mRasterLayer->renderer() ) newRenderer->copyCommonProperties( oldRenderer, false ); mRasterLayer->setRenderer( newRenderer ); } } // Hue and saturation controls if ( QgsHueSaturationFilter *hueSaturationFilter = mRasterLayer->hueSaturationFilter() ) { hueSaturationFilter->setSaturation( sliderSaturation->value() ); hueSaturationFilter->setGrayscaleMode( ( QgsHueSaturationFilter::GrayscaleMode ) comboGrayscale->currentIndex() ); hueSaturationFilter->setColorizeOn( mColorizeCheck->checkState() ); hueSaturationFilter->setColorizeColor( btnColorizeColor->color() ); hueSaturationFilter->setColorizeStrength( sliderColorizeStrength->value() ); } if ( QgsRasterResampleFilter *resampleFilter = mRasterLayer->resampleFilter() ) { QgsRasterResampler *zoomedInResampler = nullptr; QString zoomedInResamplingMethod = mZoomedInResamplingComboBox->currentText(); if ( zoomedInResamplingMethod == tr( "Bilinear" ) ) { zoomedInResampler = new QgsBilinearRasterResampler(); } else if ( zoomedInResamplingMethod == tr( "Cubic" ) ) { zoomedInResampler = new QgsCubicRasterResampler(); } resampleFilter->setZoomedInResampler( zoomedInResampler ); //raster resampling QgsRasterResampler *zoomedOutResampler = nullptr; QString zoomedOutResamplingMethod = mZoomedOutResamplingComboBox->currentText(); if ( zoomedOutResamplingMethod == tr( "Average" ) ) { zoomedOutResampler = new QgsBilinearRasterResampler(); } resampleFilter->setZoomedOutResampler( zoomedOutResampler ); resampleFilter->setMaxOversampling( mMaximumOversamplingSpinBox->value() ); } mRasterLayer->setBlendMode( mBlendModeComboBox->blendMode() ); } void QgsRendererRasterPropertiesWidget::syncToLayer( QgsRasterLayer *layer ) { mRasterLayer = layer; cboRenderers->blockSignals( true ); cboRenderers->clear(); QgsRasterRendererRegistryEntry entry; const auto constRenderersList = QgsApplication::rasterRendererRegistry()->renderersList(); for ( const QString &name : constRenderersList ) { if ( QgsApplication::rasterRendererRegistry()->rendererData( name, entry ) ) { if ( ( mRasterLayer->rasterType() != QgsRasterLayer::ColorLayer && entry.name != QLatin1String( "singlebandcolordata" ) ) || ( mRasterLayer->rasterType() == QgsRasterLayer::ColorLayer && entry.name == QLatin1String( "singlebandcolordata" ) ) ) { cboRenderers->addItem( entry.icon(), entry.visibleName, entry.name ); } } } cboRenderers->setCurrentIndex( -1 ); cboRenderers->blockSignals( false ); if ( QgsRasterRenderer *renderer = mRasterLayer->renderer() ) { setRendererWidget( renderer->type() ); } if ( QgsBrightnessContrastFilter *brightnessFilter = mRasterLayer->brightnessFilter() ) { mSliderBrightness->setValue( brightnessFilter->brightness() ); mSliderContrast->setValue( brightnessFilter->contrast() ); } btnColorizeColor->setColorDialogTitle( tr( "Select Color" ) ); btnColorizeColor->setContext( QStringLiteral( "symbology" ) ); // Hue and saturation color control //set hue and saturation controls to current values if ( const QgsHueSaturationFilter *hueSaturationFilter = mRasterLayer->hueSaturationFilter() ) { sliderSaturation->setValue( hueSaturationFilter->saturation() ); comboGrayscale->setCurrentIndex( ( int ) hueSaturationFilter->grayscaleMode() ); // Set initial state of saturation controls based on grayscale mode choice toggleSaturationControls( static_cast<int>( hueSaturationFilter->grayscaleMode() ) ); // Set initial state of colorize controls mColorizeCheck->setChecked( hueSaturationFilter->colorizeOn() ); btnColorizeColor->setColor( hueSaturationFilter->colorizeColor() ); toggleColorizeControls( hueSaturationFilter->colorizeOn() ); sliderColorizeStrength->setValue( hueSaturationFilter->colorizeStrength() ); } //blend mode mBlendModeComboBox->setBlendMode( mRasterLayer->blendMode() ); //set combo boxes to current resampling types if ( const QgsRasterResampleFilter *resampleFilter = mRasterLayer->resampleFilter() ) { const QgsRasterResampler *zoomedInResampler = resampleFilter->zoomedInResampler(); if ( zoomedInResampler ) { if ( zoomedInResampler->type() == QLatin1String( "bilinear" ) ) { mZoomedInResamplingComboBox->setCurrentIndex( 1 ); } else if ( zoomedInResampler->type() == QLatin1String( "cubic" ) ) { mZoomedInResamplingComboBox->setCurrentIndex( 2 ); } } else { mZoomedInResamplingComboBox->setCurrentIndex( 0 ); } const QgsRasterResampler *zoomedOutResampler = resampleFilter->zoomedOutResampler(); if ( zoomedOutResampler ) { if ( zoomedOutResampler->type() == QLatin1String( "bilinear" ) ) //bilinear resampler does averaging when zooming out { mZoomedOutResamplingComboBox->setCurrentIndex( 1 ); } } else { mZoomedOutResamplingComboBox->setCurrentIndex( 0 ); } mMaximumOversamplingSpinBox->setValue( resampleFilter->maxOversampling() ); } } void QgsRendererRasterPropertiesWidget::mResetColorRenderingBtn_clicked() { mBlendModeComboBox->setBlendMode( QPainter::CompositionMode_SourceOver ); mSliderBrightness->setValue( 0 ); mSliderContrast->setValue( 0 ); sliderSaturation->setValue( 0 ); comboGrayscale->setCurrentIndex( ( int ) QgsHueSaturationFilter::GrayscaleOff ); mColorizeCheck->setChecked( false ); sliderColorizeStrength->setValue( 100 ); } void QgsRendererRasterPropertiesWidget::toggleSaturationControls( int grayscaleMode ) { // Enable or disable saturation controls based on choice of grayscale mode if ( grayscaleMode == 0 ) { sliderSaturation->setEnabled( true ); spinBoxSaturation->setEnabled( true ); } else { sliderSaturation->setEnabled( false ); spinBoxSaturation->setEnabled( false ); } emit widgetChanged(); } void QgsRendererRasterPropertiesWidget::toggleColorizeControls( bool colorizeEnabled ) { // Enable or disable colorize controls based on checkbox btnColorizeColor->setEnabled( colorizeEnabled ); sliderColorizeStrength->setEnabled( colorizeEnabled ); spinColorizeStrength->setEnabled( colorizeEnabled ); emit widgetChanged(); } void QgsRendererRasterPropertiesWidget::setRendererWidget( const QString &rendererName ) { QgsDebugMsg( "rendererName = " + rendererName ); QgsRasterRendererWidget *oldWidget = mRendererWidget; int alphaBand = -1; double opacity = 1; QColor nodataColor; if ( QgsRasterRenderer *oldRenderer = mRasterLayer->renderer() ) { // Retain alpha band and opacity when switching renderer alphaBand = oldRenderer->alphaBand(); opacity = oldRenderer->opacity(); nodataColor = oldRenderer->nodataColor(); } QgsRasterRendererRegistryEntry rendererEntry; if ( QgsApplication::rasterRendererRegistry()->rendererData( rendererName, rendererEntry ) ) { if ( rendererEntry.widgetCreateFunction ) // Single band color data renderer e.g. has no widget { QgsDebugMsg( QStringLiteral( "renderer has widgetCreateFunction" ) ); // Current canvas extent (used to calc min/max) in layer CRS QgsRectangle myExtent = mMapCanvas->mapSettings().outputExtentToLayerExtent( mRasterLayer, mMapCanvas->extent() ); if ( oldWidget ) { if ( rendererName == QLatin1String( "singlebandgray" ) ) { whileBlocking( mRasterLayer )->setRenderer( QgsApplication::rasterRendererRegistry()->defaultRendererForDrawingStyle( QgsRaster::SingleBandGray, mRasterLayer->dataProvider() ) ); whileBlocking( mRasterLayer )->setDefaultContrastEnhancement(); } else if ( rendererName == QLatin1String( "multibandcolor" ) ) { whileBlocking( mRasterLayer )->setRenderer( QgsApplication::rasterRendererRegistry()->defaultRendererForDrawingStyle( QgsRaster::MultiBandColor, mRasterLayer->dataProvider() ) ); whileBlocking( mRasterLayer )->setDefaultContrastEnhancement(); } } mRasterLayer->renderer()->setAlphaBand( alphaBand ); mRasterLayer->renderer()->setOpacity( opacity ); mRasterLayer->renderer()->setNodataColor( nodataColor ); mRendererWidget = rendererEntry.widgetCreateFunction( mRasterLayer, myExtent ); mRendererWidget->setMapCanvas( mMapCanvas ); connect( mRendererWidget, &QgsRasterRendererWidget::widgetChanged, this, &QgsPanelWidget::widgetChanged ); stackedWidget->addWidget( mRendererWidget ); stackedWidget->setCurrentWidget( mRendererWidget ); if ( oldWidget ) { // Compare used bands in new and old renderer and reset transparency dialog if different QgsRasterRenderer *oldRenderer = oldWidget->renderer(); QgsRasterRenderer *newRenderer = mRendererWidget->renderer(); #if 0 QList<int> oldBands = oldRenderer->usesBands(); QList<int> newBands = newRenderer->usesBands(); if ( oldBands != newBands ) { populateTransparencyTable( newRenderer ); } #endif delete oldRenderer; delete newRenderer; } } } if ( mRendererWidget != oldWidget ) delete oldWidget; int widgetIndex = cboRenderers->findData( rendererName ); if ( widgetIndex != -1 ) { whileBlocking( cboRenderers )->setCurrentIndex( widgetIndex ); } } void QgsRendererRasterPropertiesWidget::refreshAfterStyleChanged() { if ( mRendererWidget ) { QgsRasterRenderer *renderer = mRasterLayer->renderer(); if ( QgsMultiBandColorRenderer *mbcr = dynamic_cast<QgsMultiBandColorRenderer *>( renderer ) ) { const QgsContrastEnhancement *redCe = mbcr->redContrastEnhancement(); if ( redCe ) { mRendererWidget->setMin( QString::number( redCe->minimumValue() ), 0 ); mRendererWidget->setMax( QString::number( redCe->maximumValue() ), 0 ); } const QgsContrastEnhancement *greenCe = mbcr->greenContrastEnhancement(); if ( greenCe ) { mRendererWidget->setMin( QString::number( greenCe->minimumValue() ), 1 ); mRendererWidget->setMax( QString::number( greenCe->maximumValue() ), 1 ); } const QgsContrastEnhancement *blueCe = mbcr->blueContrastEnhancement(); if ( blueCe ) { mRendererWidget->setMin( QString::number( blueCe->minimumValue() ), 2 ); mRendererWidget->setMax( QString::number( blueCe->maximumValue() ), 2 ); } } else if ( QgsSingleBandGrayRenderer *sbgr = dynamic_cast<QgsSingleBandGrayRenderer *>( renderer ) ) { const QgsContrastEnhancement *ce = sbgr->contrastEnhancement(); if ( ce ) { mRendererWidget->setMin( QString::number( ce->minimumValue() ) ); mRendererWidget->setMax( QString::number( ce->maximumValue() ) ); } } } }
tudorbarascu/QGIS
src/gui/raster/qgsrendererrasterpropertieswidget.cpp
C++
gpl-2.0
18,787
#include "group_handler_base.h" #include "group_adapter_centralized.h" #include "../../messaging/message_string.h" #include "../worker.h" #include "../global.h" namespace networking { group_adapter_centralized::group_adapter_centralized( ACE_Reactor *r ) : group_adapter_base(r), _cgrp(NULL) { // TODO needs global config.h or from fxsettings _grp_id = net_conf()->get_value("net_centralized/server") + ':' + net_conf()->get_value("net_centralized/port"); ACE_DEBUG((LM_DEBUG, "group_adapter_centralized: group id: %s\n", _grp_id.c_str())); } group_adapter_centralized::~group_adapter_centralized() { } netcomgrp::group * group_adapter_centralized::create_group() { _cgrp = new netcomgrp::centralized::client::group; return _cgrp; } const std::string & group_adapter_centralized::join_group() { return _grp_id; } group_handler_base * group_adapter_centralized::create_handler(netcomgrp::group *g) { // return new group_handler_centralized(g, m); group_handler_base *h = new group_handler_base(g, message::ctz_group_base); h->notify(this); return h; } void group_adapter_centralized::group_error(int err, const char *desc) { ACE_DEBUG((LM_DEBUG, "group_adapter_centralized::group_error: " \ "received error (%d) %s\n", err, desc)); switch (err) { case netcomgrp::group::err_timeout_connect: case netcomgrp::group::err_connect: { message_string *m = new message_string( message::ctz_group_server_unreachable, _grp_id ); ACE_DEBUG((LM_DEBUG, "group_adapter_centralized: _grp_id %s, msg str: %s\n", _grp_id.c_str(), m->str().c_str())); gui_messenger()->send_msg(m); } break; } } } // ns networking
ajalkane/rvhouse
src/networking/impl/group_adapter_centralized.cpp
C++
gpl-2.0
1,919
#define H2D_REPORT_WARN #define H2D_REPORT_INFO #define H2D_REPORT_VERBOSE #define H2D_REPORT_FILE "application.log" #include "hermes2d.h" #include "function.h" // This example solves a simple version of the time-dependent // Richard's equation using the backward Euler method in time // combined with the Newton's method in each time step. // // PDE: C(h)dh/dt - div(K(h)grad(h)) - (dK/dh)*(dh/dy) = 0 // where K(h) = K_S*exp(alpha*h) for h < 0, // K(h) = K_S for h >= 0, // C(h) = alpha*(theta_s - theta_r)*exp(alpha*h) for h < 0, // C(h) = alpha*(theta_s - theta_r) for h >= 0. // // Domain: square (0, 100)^2. // // BC: Dirichlet, given by the initial condition. // IC: See the function init_cond(). // // The following parameters can be changed: // If this is defined, use van Genuchten's constitutive relations, otherwise use Gardner's. //#define CONSTITUTIVE_GENUCHTEN const int INIT_GLOB_REF_NUM = 1; // Number of initial uniform mesh refinements. const int INIT_BDY_REF_NUM = 0; // Number of initial refinements towards boundary. const int P_INIT = 5; // Initial polynomial degree. const double TAU = 1e-1; // Time step. const double T_FINAL = 10.0; // Time interval length. const double NEWTON_TOL = 1e-6; // Stopping criterion for the Newton's method. const int NEWTON_MAX_ITER = 100; // Maximum allowed number of Newton iterations. // For the definition of initial condition. int Y_POWER = 10; // Problem parameters. double K_S = 20.464; double ALPHA = 0.001; double THETA_R = 0; double THETA_S = 0.45; double H_R = -1000; double A = 100; double L = 100; double STORATIVITY = 0.0; double M = 0.6; double N = 2.5; #ifdef CONSTITUTIVE_GENUCHTEN #include "constitutive_genuchten.cpp" #else #include "constitutive_gardner.cpp" #endif // Initial condition. It will be projected on the FE mesh // to obtain initial coefficient vector for the Newton's method. double init_cond(double x, double y, double& dx, double& dy) { dx = (100 - 2*x)/2.5 * pow(y/100, Y_POWER); dy = x*(100 - x)/2.5 * pow(y/100, Y_POWER - 1) * 1./100; return x*(100 - x)/2.5 * pow(y/100, Y_POWER) - 1000; } // Boundary condition types. BCType bc_types(int marker) { return BC_ESSENTIAL; } // Essential (Dirichlet) boundary condition markers. scalar essential_bc_values(int ess_bdy_marker, double x, double y) { double dx, dy; return init_cond(x, y, dx, dy); } // Weak forms. #include "forms.cpp" int main(int argc, char* argv[]) { // Load the mesh. Mesh mesh; H2DReader mloader; mloader.load("square.mesh", &mesh); // Initial mesh refinements. for(int i = 0; i < INIT_GLOB_REF_NUM; i++) mesh.refine_all_elements(); mesh.refine_towards_boundary(1, INIT_BDY_REF_NUM); // Create an H1 space with default shapeset. H1Space space(&mesh, bc_types, essential_bc_values, P_INIT); // Solutions for the Newton's iteration and // time stepping. Solution u_prev_newton, u_prev_time; // Initialize the weak formulation. WeakForm wf; wf.add_matrix_form(jac, jac_ord, H2D_UNSYM, H2D_ANY, Tuple<MeshFunction*>(&u_prev_newton, &u_prev_time)); wf.add_vector_form(res, res_ord, H2D_ANY, Tuple<MeshFunction*>(&u_prev_newton, &u_prev_time)); // Initialize the nonlinear system. NonlinSystem nls(&wf, &space); // Project the function init_cond() on the FE space // to obtain initial coefficient vector for the Newton's method. info("Projecting initial condition to obtain initial vector for the Newton'w method."); u_prev_time.set_exact(&mesh, init_cond); // u_prev_time set equal to init_cond(). nls.project_global(init_cond, &u_prev_newton); // Initial vector calculated here. // Initialize views. ScalarView sview("Solution", 0, 0, 500, 400); OrderView oview("Mesh", 520, 0, 450, 400); oview.show(&space); sview.show(&u_prev_newton); //View::wait(H2DV_WAIT_KEYPRESS); // Time stepping loop: double current_time = 0.0; int t_step = 1; do { info("---- Time step %d, t = %g s.", t_step, current_time); t_step++; // Newton's method. info("Performing Newton's method."); bool verbose = true; // Default is false. if (!nls.solve_newton(&u_prev_newton, NEWTON_TOL, NEWTON_MAX_ITER, verbose)) error("Newton's method did not converge."); // Update previous time level solution. u_prev_time.copy(&u_prev_newton); // Update time. current_time += TAU; // Show the new time level solution. char title[100]; sprintf(title, "Solution, t = %g", current_time); sview.set_title(title); sview.show(&u_prev_time); } while (current_time < T_FINAL); // Wait for all views to be closed. View::wait(); return 0; }
davidquantum/hermes2d
examples/richards/main.cpp
C++
gpl-2.0
4,814
/*! { "name" : "HTML5 Audio Element", "property": "audio", "aliases" : [], "tags" : ["html5", "audio", "media"], "doc" : "/docs/#audio", "knownBugs": [], "authors" : [] } !*/ define(['Modernizr', 'createElement'], function( Modernizr, createElement ) { // This tests evaluates support of the audio element, as well as // testing what types of content it supports. // // We're using the Boolean constructor here, so that we can extend the value // e.g. Modernizr.audio // true // Modernizr.audio.ogg // 'probably' // // Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845 // thx to NielsLeenheer and zcorpan // Note: in some older browsers, "no" was a return value instead of empty string. // It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2 // It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5 Modernizr.addTest('audio', function() { /* jshint -W053 */ var elem = createElement('audio'); var bool = false; try { if ( bool = !!elem.canPlayType ) { bool = new Boolean(bool); bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,''); bool.mp3 = elem.canPlayType('audio/mpeg;') .replace(/^no$/,''); bool.opus = elem.canPlayType('audio/ogg; codecs="opus"') .replace(/^no$/,''); // Mimetypes accepted: // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements // bit.ly/iphoneoscodecs bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/,''); bool.m4a = ( elem.canPlayType('audio/x-m4a;') || elem.canPlayType('audio/aac;')) .replace(/^no$/,''); } } catch(e) { } return bool; }); });
tony-stratton/blueridgeartist.com
sites/all/libraries/modernizr/feature-detects/audio.js
JavaScript
gpl-2.0
1,850
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Base Site URL |-------------------------------------------------------------------------- | | URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash: | | http://example.com/ | | If this is not set then CodeIgniter will guess the protocol, domain and | path to your installation. | */ $config['base_url'] = 'http://localhost/thesickside2/'; //$config['base_url'] = 'http://192.168.1.105/thesickside2/'; //$config['base_url'] = 'http://92.56.64.99/thesickside2/'; /* |-------------------------------------------------------------------------- | Index File |-------------------------------------------------------------------------- | | Typically this will be your index.php file, unless you've renamed it to | something else. If you are using mod_rewrite to remove the page set this | variable so that it is blank. | */ $config['index_page'] = ''; /* |-------------------------------------------------------------------------- | URI PROTOCOL |-------------------------------------------------------------------------- | | This item determines which server global should be used to retrieve the | URI string. The default setting of 'AUTO' works for most servers. | If your links do not seem to work, try one of the other delicious flavors: | | 'AUTO' Default - auto detects | 'PATH_INFO' Uses the PATH_INFO | 'QUERY_STRING' Uses the QUERY_STRING | 'REQUEST_URI' Uses the REQUEST_URI | 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO | */ $config['uri_protocol'] = 'AUTO'; /* |-------------------------------------------------------------------------- | URL suffix |-------------------------------------------------------------------------- | | This option allows you to add a suffix to all URLs generated by CodeIgniter. | For more information please see the user guide: | | http://codeigniter.com/user_guide/general/urls.html */ $config['url_suffix'] = ''; /* |-------------------------------------------------------------------------- | Default Language |-------------------------------------------------------------------------- | | This determines which set of language files should be used. Make sure | there is an available translation if you intend to use something other | than english. | */ $config['language'] = 'cat'; /* |-------------------------------------------------------------------------- | Default Character Set |-------------------------------------------------------------------------- | | This determines which character set is used by default in various methods | that require a character set to be provided. | */ $config['charset'] = 'UTF-8'; /* |-------------------------------------------------------------------------- | Enable/Disable System Hooks |-------------------------------------------------------------------------- | | If you would like to use the 'hooks' feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = FALSE; /* |-------------------------------------------------------------------------- | Class Extension Prefix |-------------------------------------------------------------------------- | | This item allows you to set the filename/classname prefix when extending | native libraries. For more information please see the user guide: | | http://codeigniter.com/user_guide/general/core_classes.html | http://codeigniter.com/user_guide/general/creating_libraries.html | */ $config['subclass_prefix'] = 'MY_'; /* |-------------------------------------------------------------------------- | Allowed URL Characters |-------------------------------------------------------------------------- | | This lets you specify with a regular expression which characters are permitted | within your URLs. When someone tries to submit a URL with disallowed | characters they will get a warning message. | | As a security measure you are STRONGLY encouraged to restrict URLs to | as few characters as possible. By default only these are allowed: a-z 0-9~%.:_- | | Leave blank to allow all characters -- but only if you are insane. | | DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! | */ $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; /* |-------------------------------------------------------------------------- | Enable Query Strings |-------------------------------------------------------------------------- | | By default CodeIgniter uses search-engine friendly segment based URLs: | example.com/who/what/where/ | | By default CodeIgniter enables access to the $_GET array. If for some | reason you would like to disable it, set 'allow_get_array' to FALSE. | | You can optionally enable standard query string based URLs: | example.com?who=me&what=something&where=here | | Options are: TRUE or FALSE (boolean) | | The other items let you set the query string 'words' that will | invoke your controllers and its functions: | example.com/index.php?c=controller&m=function | | Please note that some of the helpers won't work as expected when | this feature is enabled, since CodeIgniter is designed primarily to | use segment based URLs. | */ $config['allow_get_array'] = TRUE; $config['enable_query_strings'] = FALSE; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; $config['directory_trigger'] = 'd'; // experimental not currently in use /* |-------------------------------------------------------------------------- | Error Logging Threshold |-------------------------------------------------------------------------- | | If you have enabled error logging, you can set an error threshold to | determine what gets logged. Threshold options are: | You can enable error logging by setting a threshold over zero. The | threshold determines what gets logged. Threshold options are: | | 0 = Disables logging, Error logging TURNED OFF | 1 = Error Messages (including PHP errors) | 2 = Debug Messages | 3 = Informational Messages | 4 = All Messages | | For a live site you'll usually only enable Errors (1) to be logged otherwise | your log files will fill up very fast. | */ $config['log_threshold'] = 0; /* |-------------------------------------------------------------------------- | Error Logging Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/logs/ folder. Use a full server path with trailing slash. | */ $config['log_path'] = ''; /* |-------------------------------------------------------------------------- | Date Format for Logs |-------------------------------------------------------------------------- | | Each item that is logged has an associated date. You can use PHP date | codes to set your own date formatting | */ $config['log_date_format'] = 'Y-m-d H:i:s'; /* |-------------------------------------------------------------------------- | Cache Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | system/cache/ folder. Use a full server path with trailing slash. | */ $config['cache_path'] = ''; /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | If you use the Encryption class or the Session class you | MUST set an encryption key. See the user guide for info. | */ $config['encryption_key'] = '9aR7owR=a2.19oP"al8eI298hJm2¬$2k(d*!'; /* |-------------------------------------------------------------------------- | Session Variables |-------------------------------------------------------------------------- | | 'sess_cookie_name' = the name you want for the cookie | 'sess_expiration' = the number of SECONDS you want the session to last. | by default sessions last 7200 seconds (two hours). Set to zero for no expiration. | 'sess_expire_on_close' = Whether to cause the session to expire automatically | when the browser window is closed | 'sess_encrypt_cookie' = Whether to encrypt the cookie | 'sess_use_database' = Whether to save the session data to a database | 'sess_table_name' = The name of the session database table | 'sess_match_ip' = Whether to match the user's IP address when reading the session data | 'sess_match_useragent' = Whether to match the User Agent when reading the session data | 'sess_time_to_update' = how many seconds between CI refreshing Session Information | */ $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_expire_on_close'] = FALSE; $config['sess_encrypt_cookie'] = FALSE; $config['sess_use_database'] = FALSE; $config['sess_table_name'] = 'ci_sessions'; $config['sess_match_ip'] = FALSE; $config['sess_match_useragent'] = TRUE; $config['sess_time_to_update'] = 300; /* |-------------------------------------------------------------------------- | Cookie Related Variables |-------------------------------------------------------------------------- | | 'cookie_prefix' = Set a prefix if you need to avoid collisions | 'cookie_domain' = Set to .your-domain.com for site-wide cookies | 'cookie_path' = Typically will be a forward slash | 'cookie_secure' = Cookies will only be set if a secure HTTPS connection exists. | */ $config['cookie_prefix'] = ""; $config['cookie_domain'] = ""; $config['cookie_path'] = "/"; $config['cookie_secure'] = FALSE; /* |-------------------------------------------------------------------------- | Global XSS Filtering |-------------------------------------------------------------------------- | | Determines whether the XSS filter is always active when GET, POST or | COOKIE data is encountered | */ $config['global_xss_filtering'] = TRUE; /* |-------------------------------------------------------------------------- | Cross Site Request Forgery |-------------------------------------------------------------------------- | Enables a CSRF cookie token to be set. When set to TRUE, token will be | checked on a submitted form. If you are accepting user data, it is strongly | recommended CSRF protection be enabled. | | 'csrf_token_name' = The token name | 'csrf_cookie_name' = The cookie name | 'csrf_expire' = The number in seconds the token should expire. */ $config['csrf_protection'] = TRUE; $config['csrf_token_name'] = 'csrf_security'; $config['csrf_cookie_name'] = 'csrf_security_cookie'; $config['csrf_expire'] = 7200; /* |-------------------------------------------------------------------------- | Output Compression |-------------------------------------------------------------------------- | | Enables Gzip output compression for faster page loads. When enabled, | the output class will test whether your server supports Gzip. | Even if it does, however, not all browsers support compression | so enable only if you are reasonably sure your visitors can handle it. | | VERY IMPORTANT: If you are getting a blank page when compression is enabled it | means you are prematurely outputting something to your browser. It could | even be a line of whitespace at the end of one of your scripts. For | compression to work, nothing can be sent before the output buffer is called | by the output class. Do not 'echo' any values with compression enabled. | */ $config['compress_output'] = TRUE; /* |-------------------------------------------------------------------------- | Master Time Reference |-------------------------------------------------------------------------- | | Options are 'local' or 'gmt'. This pref tells the system whether to use | your server's local time as the master 'now' reference, or convert it to | GMT. See the 'date helper' page of the user guide for information | regarding date handling. | */ $config['time_reference'] = 'local'; /* |-------------------------------------------------------------------------- | Rewrite PHP Short Tags |-------------------------------------------------------------------------- | | If your PHP installation does not have short tag support enabled CI | can rewrite the tags on-the-fly, enabling you to utilize that syntax | in your view files. Options are TRUE or FALSE (boolean) | */ $config['rewrite_short_tags'] = FALSE; /* |-------------------------------------------------------------------------- | Reverse Proxy IPs |-------------------------------------------------------------------------- | | If your server is behind a reverse proxy, you must whitelist the proxy IP | addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR | header in order to properly identify the visitor's IP address. | Comma-delimited, e.g. '10.0.1.200,10.0.1.201' | */ $config['proxy_ips'] = ''; /* End of file config.php */ /* Location: ./application/config/config.php */
blipi/TheSickSide
application/config/config.php
PHP
gpl-2.0
12,983
<?php defined('_JEXEC') or die; class Fw_fbpostViewToken extends JViewLegacy { public function display($tpl = null) { $component = JRequest::getVar('option','com_fw_fbpost'); $result = JComponentHelper::getComponent($option= $component); $app_id = $result->params->get('app_id'); $app_secrect = $result->params->get('app_secret'); ?> <style type="text/css"> #button { background: none repeat scroll 0 0 #555555; border: medium none; border-radius: 10px 10px 10px 10px; color: #FFFFFF; font-family: Tahoma; font-size: 25px; height: 60px; margin: 30px; width: 300px; } #button:hover{ background:none repeat scroll 0 0 #000; cursor:pointer; } </style> <form method="POST" name="f2" action="http://sms.futureworkz.com.sg/beta/home.php"> <h2 style="text-align:center;padding-top:50px;">FACEBOOK APP INFOMATION</h2> <table width="600" border="0" align="center" style="padding-top:50px;"> <tr> <td width="145">APP ID :<span style="color:red">(*)</span></td> <td width="445"><input type="text" name="app_id" class="app_id" value="<?php echo $app_id;?>" size="40" /></td> </tr> <tr> <td>APP SECRET :<span style="color:red">(*)</span></td> <td> <input type="text" name="app_secret" class="app_secret" value="<?php echo $app_secrect;?>" size="50" /></td> </tr> </table> <center> <input id="button" name="submit" value="Generate Access Token" type="submit"> </center> </form> <?php die; } }
bundocba/unitedworld
administrator/components/com_fw_fbpost/views/token/view.raw.php
PHP
gpl-2.0
1,465
//=============================================================================== // Copyright (c) 2005-2017 by Made to Order Software Corporation // // All Rights Reserved. // // The source code in this file ("Source Code") is provided by Made to Order Software Corporation // to you under the terms of the GNU General Public License, version 2.0 // ("GPL"). Terms of the GPL can be found in doc/GPL-license.txt in this distribution. // // By copying, modifying or distributing this software, you acknowledge // that you have read and understood your obligations described above, // and agree to abide by those obligations. // // ALL SOURCE CODE IN THIS DISTRIBUTION IS PROVIDED "AS IS." THE AUTHOR MAKES NO // WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, // COMPLETENESS OR PERFORMANCE. //=============================================================================== #ifdef MO_PRAGMA_INTERFACE #pragma implementation "mo/mo_memfile.h" #endif #include "mo/mo_memfile.h" namespace molib { /************************************************************ DOC: CLASS moMemFile NAME Contructors - create a new file object Destructor - ensure the memory used by this object is released SYNOPSIS moMemFile(void); virtual ~moMemFile(); DESCRIPTION The memory file object will be used whenever you don't have a really large file and the file is temporary. This file is based on the moIOStream and all the functions available in the moIOStream are functional with this file implementation. SEE ALSO moBuffer class */ moMemFile::moMemFile(void) { } moMemFile::~moMemFile() { } /************************************************************ DOC: CLASS moMemFile NAME RawRead - read bytes from the memory file RawWrite - writes bytes to the memory file SYNOPSIS virtual int RawRead(void *buffer, size_t length); virtual int RawWrite(const void *buffer, size_t length); DESCRIPTION The RawRead() function tries to read length bytes from the current input position. The number of bytes read is returned. The RawWrite() function writes length bytes to the current output position in this memory file. This can't fail (unless not enough memory can be allocated) and thus this function always returns length. RETURN VALUE Both functions return the number of bytes copied. */ int moMemFile::RawRead(void *buffer, size_t length) { void *data; unsigned long size; f_buffer.Get(data, size); if(f_input_position + static_cast<uint32_t>(length) > size) { // the result of this can be 0 length = size - f_input_position; } // length CAN be zero if(length > 0) { memcpy(buffer, reinterpret_cast<unsigned char *>(data) + f_input_position, length); /* Flawfinder: ignore */ f_input_position += static_cast<uint32_t>(length); } return static_cast<int>(length); } int moMemFile::RawWrite(const void *buffer, size_t length) { f_buffer.Copy(f_output_position, buffer, static_cast<unsigned long>(length)); f_output_position += static_cast<uint32_t>(length); return static_cast<int>(length); } /************************************************************ DOC: CLASS moMemFile NAME InputSize - the size of the memory files in bytes OutputSize - the size of the memory files in bytes SYNOPSIS virtual size_t InputSize(void) const; virtual size_t OutputSize(void) const; DESCRIPTION The InputSize() and OutputSize() functions both return the current size of the memory file in bytes. Whatever happens, the size of the input is always the same as the size of the output. RETURN VALUE the size of the memory file in bytes */ size_t moMemFile::InputSize(void) const { return (long) f_buffer; } size_t moMemFile::OutputSize(void) const { return (long) f_buffer; } } // namespace molib; // vim: ts=8
dooglio/turnwatcher
src/molib/src/memfile.cpp
C++
gpl-2.0
3,809
<?php $mts_options = get_option(MTS_THEME_NAME); if(is_array($mts_options['mts_homepage_layout'])){ $homepage_layout = $mts_options['mts_homepage_layout']['enabled']; }else if(empty($homepage_layout)) { $homepage_layout = array(); } ?> <?php $top_footer_num = (!empty($mts_options['mts_top_footer_num']) && $mts_options['mts_top_footer_num'] == 4) ? 4 : 3; $bottom_footer_num = (!empty($mts_options['mts_bottom_footer_num']) && $mts_options['mts_bottom_footer_num'] == 4) ? 4 : 3; ?> </div><!--#page--> </div><!--.main-container--> <?php if(!is_front_page() && is_singular() && !empty($mts_options['mts_twitter_single'])): ?> <section id="homepage-twitter" class="homepage-section homepage-twitter" style="background-image:url(<?php echo $mts_options['homepage_twitter_background_image']; ?>); background-color: <?php echo $mts_options['homepage_twitter_background_color']; ?>"> <div class="inside"> <?php if(empty($mts_options['homepage_twitter_api_key']) || empty($mts_options['homepage_twitter_api_secret']) || empty($mts_options['homepage_twitter_access_token']) || empty($mts_options['homepage_twitter_access_token_secret']) || empty($mts_options['homepage_twitter_username'])){ echo '<strong>'.__('The section is not configured correctly', 'mythemeshop').'</strong>'; } else { //check if cache needs update $mts_twitter_plugin_last_cache_time = get_option('mts_twitter_plugin_last_cache_time'); $diff = time() - $mts_twitter_plugin_last_cache_time; $crt =0* 3600; // yes, it needs update //require_once('functions/twitteroauth.php'); if($diff >= $crt || empty($mts_twitter_plugin_last_cache_time)){ if(!require_once('functions/twitteroauth.php')){ echo '<strong>Couldn\'t find twitteroauth.php!</strong>'; } $connection = mts_getConnectionWithhomepage_twitter_access_token($mts_options['homepage_twitter_api_key'], $mts_options['homepage_twitter_api_secret'], $mts_options['homepage_twitter_access_token'], $mts_options['homepage_twitter_access_token_secret']); $tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$mts_options['homepage_twitter_username']."&count=".$mts_options['homepage_twitter_tweet_count']) or die('Couldn\'t retrieve tweets! Wrong username?'); if(!empty($tweets->errors)){ if($tweets->errors[0]->message == 'Invalid or expired token'){ echo '<strong>'.$tweets->errors[0]->message.'!</strong><br />You\'ll need to regenerate it <a href="https://dev.twitter.com/apps" target="_blank">here</a>!'; }else{ echo '<strong>'.$tweets->errors[0]->message.'</strong>'; } return; } for($i = 0;$i <= count($tweets); $i++){ if(!empty($tweets[$i])){ $tweets_array[$i]['created_at'] = $tweets[$i]->created_at; $tweets_array[$i]['text'] = $tweets[$i]->text; $tweets_array[$i]['status_id'] = $tweets[$i]->id_str; } } //save tweets to wp option update_option('mts_twitter_plugin_tweets',serialize($tweets_array)); update_option('mts_twitter_plugin_last_cache_time',time()); echo '<!-- twitter cache has been updated! -->'; } $mts_twitter_plugin_tweets = maybe_unserialize(get_option('mts_twitter_plugin_tweets')); if(!empty($mts_twitter_plugin_tweets)){ print '<ul class="mts_recent_tweets tweets">'; $fctr = '1'; foreach($mts_twitter_plugin_tweets as $tweet){ if ($mts_options['homepage_twitter_slider'] == '0' && $fctr > 1) continue; print '<li><span>'.mts_convert_links($tweet['text']).'</span></li>'; $fctr++; } print '</ul> <a class="twitter_username" href="http://twitter.com/'.$mts_options['homepage_twitter_username'].'"><span class="fa fa-twitter"></span>'.__('Follow us on Twitter', 'mythemeshop').'</a>'; } } ?> </div> </section> <?php endif; ?> <footer id="footer"> <div class="container"> <div id="footer-nav"> <?php if ( has_nav_menu( 'footer-menu' ) ) { ?> <?php wp_nav_menu( array( 'theme_location' => 'footer-menu','menu_class' => 'footer-menu') ); ?> <?php } ?> </div> <div class="copyrights"> <span>&copy; <?php _e("Copyright","mythemeshop"); ?> <?php echo date("Y") ?>, <?php echo $mts_options['mts_copyrights']; ?></span> <div class="top">&nbsp;<a href="#top" class="toplink" rel="nofollow"><i class="fa fa-angle-up"></i></a></div> </div> </div><!--.container--> </footer><!--footer--> <?php mts_footer(); ?> <?php wp_footer(); ?> <?php if(array_key_exists('counter',$homepage_layout) || array_key_exists('slider',$homepage_layout) || array_key_exists('service',$homepage_layout) || array_key_exists('team',$homepage_layout) || array_key_exists('pricing',$homepage_layout) || array_key_exists('testimonial',$homepage_layout) || array_key_exists('clients',$homepage_layout) || array_key_exists('contact',$homepage_layout) || array_key_exists('twitter',$homepage_layout) || array_key_exists('feature',$homepage_layout) ): ?> <script type="text/javascript"> // Enable parralax images for different sections on homepage if(jQuery().parallax){ <?php if($mts_options['mts_homepage_counter_parallax'] && $mts_options['mts_homepage_counter_background_image'] != '' && array_key_exists('counter',$homepage_layout)): ?> jQuery('#homepage-counter').parallax("5%", 2750, -0.7, true); <?php endif; ?> <?php if($mts_options['mts_homepage_background_parallax'] && $mts_options['mts_homepage_background_image'] != '' && array_key_exists('slider',$homepage_layout)): ?> jQuery('#homepage-title-slider').parallax("5%", 2750, -0.7, true); <?php endif; ?> <?php if($mts_options['mts_homepage_service_parallax'] && $mts_options['mts_homepage_service_background_image'] != '' && array_key_exists('service',$homepage_layout)): ?> jQuery('#homepage-service').parallax("5%", 2750, -0.7, true); <?php endif; ?> <?php if($mts_options['mts_homepage_team_parallax'] && $mts_options['mts_homepage_team_background_image'] != '' && array_key_exists('team',$homepage_layout)): ?> jQuery('#homepage-team').parallax("5%", 2750, -0.7, true); <?php endif; ?> <?php if($mts_options['mts_homepage_pricing_parallax'] && $mts_options['mts_homepage_pricing_background_image'] != '' && array_key_exists('pricing',$homepage_layout)): ?> jQuery('#homepage-pricing').parallax("5%", 2750, -0.7, true); <?php endif; ?> <?php if($mts_options['mts_homepage_testimonials_parallax'] && $mts_options['mts_homepage_testimonials_background_image'] != '' && array_key_exists('testimonial',$homepage_layout)): ?> jQuery('#homepage-testimonials').parallax("5%", 2750, -0.7, true); <?php endif; ?> <?php if($mts_options['mts_homepage_client_parallax'] && $mts_options['mts_homepage_client_background_image'] != '' && array_key_exists('clients',$homepage_layout)): ?> jQuery('#homepage-clients').parallax("5%", 2750, -0.7, true); <?php endif; ?> <?php if($mts_options['mts_homepage_contact_parallax'] && $mts_options['mts_homepage_contact_background_image'] != '' && array_key_exists('contact',$homepage_layout)): ?> jQuery('#homepage-contact').parallax("5%", 2750, -0.7, true); <?php endif; ?> <?php if($mts_options['homepage_twitter_parallax'] && $mts_options['homepage_twitter_background_image'] != '' && array_key_exists('twitter',$homepage_layout)): ?> jQuery('#homepage-twitter').parallax("5%", 2750, -0.7, true); <?php endif; ?> <?php if($mts_options['mts_homepage_features_parallax'] && $mts_options['mts_homepage_features_background_image'] != '' && array_key_exists('feature',$homepage_layout)): ?> jQuery('#homepage-features').parallax("5%", 2750, -0.7, true); <?php endif; ?> <?php if($mts_options['mts_homepage_portfolio_parallax'] && $mts_options['mts_homepage_portfolio_background_image'] != '' && array_key_exists('portfolio',$homepage_layout)): ?> jQuery('#homepage-portfolio').parallax("5%", 2750, -0.7, true); <?php endif; ?> } </script> <?php endif; ?> <?php if($mts_options['mts_map_coordinates'] != '' && array_key_exists('contact',$homepage_layout) && is_front_page()): ?> <script type="text/javascript"> var mapLoaded = false; function initialize() { mapLoaded = true; var geocoder = new google.maps.Geocoder(); var lat=''; var lng='' geocoder.geocode( { 'address': '<?php echo addslashes($mts_options['mts_map_coordinates']); ?>'}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { lat = results[0].geometry.location.lat(); //getting the lat lng = results[0].geometry.location.lng(); //getting the lng map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } }); var latlng = new google.maps.LatLng(lat, lng); var mapOptions = { zoom: 18, center: latlng, scrollwheel: false, navigationControl: false, scaleControl: false, streetViewControl: false, draggable: true, panControl: false, mapTypeControl: false, zoomControl: false, mapTypeId: google.maps.MapTypeId.ROADMAP, // How you would like to style the map. // This is where you would paste any style found on Snazzy Maps. styles: [{featureType:"landscape",stylers:[{saturation:-100},{lightness:65},{visibility:"on"}]}] }; var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); } //google.maps.event.addDomListener(window, 'load', initialize); jQuery(window).load(function() { jQuery(window).scroll(function() { if (jQuery('.contact_map').isOnScreen() && !mapLoaded) { mapLoaded = true; jQuery('body').append('<script src="https://maps.googleapis.com/maps/api/js?sensor=false&v=3&callback=initialize"></'+'script>'); } }); }); </script> <?php endif ?> </div><!--.main-container-wrap--> </body> </html>
Qiaojianxun123/gongfuweb
wp-content/themes/onepage/footer.php
PHP
gpl-2.0
10,577
/* * Information about an output, not the value of the output itself (that is handled by manager) */ package wekimini.osc; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Random; import wekimini.util.Util; /** * XXX in future: need to know when to send: - whenever new feature received - * whenever new output gesture matched * * - send all as bundle vs send individual messages (one per output), or both * * @author rebecca */ public class OSCDtwOutput implements OSCOutput { private String name; public static final String PROP_NAME = "name"; private int numGestures; public static final String PROP_NUMGESTURES = "numGestures"; private String[] gestureNames; public static final String PROP_GESTURE_NAMES = "gestureNames"; private String[] gestureOscMessages; public static final String PROP_GESTURE_OSC_MESSAGES = "gestureOscMessages"; private String outputOscMessage; //Removed final for XML de-serialization support private transient PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this); public String getOutputOscMessage() { return outputOscMessage; } public void setOutputOscMessage(String m) { outputOscMessage = m; } public OSCDtwOutput(String name, int numGestures) { this.name = name; this.numGestures = numGestures; this.gestureNames = new String[numGestures]; this.gestureOscMessages = new String[numGestures]; populateNames(); this.outputOscMessage = name; populateOscMessagesFromNames(); } /** * Get the value of gestureOscMessages * * @return the value of gestureOscMessages */ public String[] getGestureOscMessages() { return gestureOscMessages; } /** * Set the value of gestureOscMessages * * @param gestureOscMessages new value of gestureOscMessages */ public void setGestureOscMessages(String[] gestureOscMessages) { String[] oldGestureOscMessages = this.gestureOscMessages; this.gestureOscMessages = gestureOscMessages; propertyChangeSupport.firePropertyChange(PROP_GESTURE_OSC_MESSAGES, oldGestureOscMessages, gestureOscMessages); } /** * Get the value of gestureOscMessages at specified index * * @param index the index of gestureOscMessages * @return the value of gestureOscMessages at specified index */ public String getGestureOscMessages(int index) { return this.gestureOscMessages[index]; } /** * Set the value of gestureOscMessages at specified index. * * @param index the index of gestureOscMessages * @param gestureOscMessages new value of gestureOscMessages at specified * index */ public void setGestureOscMessages(int index, String gestureOscMessages) { String oldGestureOscMessages = this.gestureOscMessages[index]; this.gestureOscMessages[index] = gestureOscMessages; propertyChangeSupport.fireIndexedPropertyChange(PROP_GESTURE_OSC_MESSAGES, index, oldGestureOscMessages, gestureOscMessages); } /** * Get the value of numGestures * * @return the value of numGestures */ public int getNumGestures() { return numGestures; } /** * Set the value of numGestures * * @param numGestures new value of numGestures */ public void setNumGestures(int numGestures) { int oldNumGestures = this.numGestures; this.numGestures = numGestures; propertyChangeSupport.firePropertyChange(PROP_NUMGESTURES, oldNumGestures, numGestures); } /** * Get the value of gestureNames * * @return the value of gestureNames */ public String[] getGestureNames() { return gestureNames; } /** * Set the value of gestureNames * * @param gestureNames new value of gestureNames */ public void setGestureNames(String[] gestureNames) { String[] oldGestureNames = this.gestureNames; this.gestureNames = gestureNames; propertyChangeSupport.firePropertyChange(PROP_GESTURE_NAMES, oldGestureNames, gestureNames); } /** * Get the value of gestureNames at specified index * * @param index the index of gestureNames * @return the value of gestureNames at specified index */ public String getGestureNames(int index) { return this.gestureNames[index]; } /** * Set the value of gestureNames at specified index. * * @param index the index of gestureNames * @param gestureNames new value of gestureNames at specified index */ public void setGestureNames(int index, String gestureNames) { String oldGestureNames = this.gestureNames[index]; this.gestureNames[index] = gestureNames; propertyChangeSupport.fireIndexedPropertyChange(PROP_GESTURE_NAMES, index, oldGestureNames, gestureNames); } /** * Get the value of name * * @return the value of name */ @Override public String getName() { return name; } /** * Set the value of name * * @param name new value of name */ public void setName(String name) { String oldName = this.name; this.name = name; propertyChangeSupport.firePropertyChange(PROP_NAME, oldName, name); } /** * Add PropertyChangeListener. * * @param listener */ public void addPropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.addPropertyChangeListener(listener); } /** * Remove PropertyChangeListener. * * @param listener */ public void removePropertyChangeListener(PropertyChangeListener listener) { propertyChangeSupport.removePropertyChangeListener(listener); } private void populateOscMessagesFromNames() { for (int i = 0; i < numGestures; i++) { gestureOscMessages[i] = "/" + gestureNames[i]; } } private void populateNames() { for (int i = 0; i < gestureNames.length; i++) { gestureNames[i] = name + "_" + (i + 1); } } @Override public String toString() { return Util.toXMLString(this, "OSCDtwOutput", OSCDtwOutput.class); } @Override public double generateRandomValue() { Random r = new Random(); int i = r.nextInt(numGestures+1); return i; } @Override public double getDefaultValue() { return 1; } @Override public boolean isLegalTrainingValue(double value) { return (value > 0 && value <= numGestures); } @Override public boolean isLegalOutputValue(double value) { if (value < 0 || value > numGestures) { //out of range return false; } return Util.isInteger(value); //is it really an int? } @Override public double forceLegalTrainingValue(double value) { //return forceLegalOutputValue(value); if (value <= 0) { return 1; } if (value > numGestures) { return numGestures; } return value; } @Override public double forceLegalOutputValue(double value) { int which = (int) value; if (which < 0) { which = 1; } if (which > numGestures) { which = numGestures; } return which; } private Object readResolve() { propertyChangeSupport = new PropertyChangeSupport(this); return this; } @Override public String toLogString() { StringBuilder sb = new StringBuilder(); sb.append("DTW,NAME=").append(name); sb.append(",NUM_GEST=").append(numGestures); sb.append(",GESTURE_NAMES="); for (int i = 0; i < numGestures; i++) { sb.append(gestureNames[i]).append(','); } return sb.toString(); } }
mzed/wekimini
src/wekimini/osc/OSCDtwOutput.java
Java
gpl-2.0
8,148
<?php /** * @version $Id: coolfeed.php 100 2012-04-14 17:42:51Z trung3388@gmail.com $ * @copyright JoomAvatar.com * @author Nguyen Quang Trung * @link http://joomavatar.com * @license License GNU General Public License version 2 or later * @package Avatar Dream Framework Template * @facebook http://www.facebook.com/pages/JoomAvatar/120705031368683 * @twitter https://twitter.com/#!/JoomAvatar * @support http://joomavatar.com/forum/ */ // No direct access defined('_JEXEC') or die; // Note. It is important to remove spaces between elements. ?> <ul class="menu clearfix <?php echo $class_sfx;?>"<?php $tag = ''; if ($params->get('tag_id')!=NULL) { $tag = $params->get('tag_id').''; echo ' id="'.$tag.'"'; } ?>> <?php foreach ($list as $i => &$item) : $class = 'item-'.$item->id; if ($item->id == $active_id) { $class .= ' current'; } if (in_array($item->id, $path)) { $class .= ' active'; } elseif ($item->type == 'alias') { $aliasToId = $item->params->get('aliasoptions'); if (count($path) > 0 && $aliasToId == $path[count($path)-1]) { $class .= ' active'; } elseif (in_array($aliasToId, $path)) { $class .= ' alias-parent-active'; } } if ($item->deeper) { $class .= ' deeper'; } if ($item->parent) { $class .= ' parent'; } if (!empty($class)) { $class = ' class="'.trim($class) .'"'; } echo '<li'.$class.'>'; // Render the menu item. switch ($item->type) : case 'separator': case 'url': case 'component': require JModuleHelper::getLayoutPath('mod_menu', 'default_'.$item->type); break; default: require JModuleHelper::getLayoutPath('mod_menu', 'default_url'); break; endswitch; // The next item is deeper. if ($item->deeper) { echo '<ul>'; } // The next item is shallower. elseif ($item->shallower) { echo '</li>'; echo str_repeat('</ul></li>', $item->level_diff); } // The next item is on the same level. else { echo '</li>'; } endforeach; ?></ul><div style="clear:both;"></div>
jbelborja/deportivo
templates/avatar_vincent/core/html/mod_menu/default.php
PHP
gpl-2.0
2,002
<?php /* * This file is part of the Mink package. * (c) Konstantin Kudryashov <ever.zet@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Behat\Mink\Element; /** * Document element. * * @author Konstantin Kudryashov <ever.zet@gmail.com> */ class DocumentElement extends TraversableElement { /** * Returns XPath for handled element. * * @return string */ public function getXpath() { return '//html'; } /** * Returns document content. * * @return string */ public function getContent() { return trim($this->getDriver()->getContent()); } /** * Check whether document has specified content. * * @param string $content * * @return boolean */ public function hasContent($content) { return $this->has('named', array('content', $content)); } }
maskedjellybean/tee-prop
vendor/behat/mink/src/Element/DocumentElement.php
PHP
gpl-2.0
995
/* * Copyright (C) 2012-2017 52°North Initiative for Geospatial Open Source * Software GmbH * * 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. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * 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. */ package org.n52.ows.service; import net.opengis.ows.x11.CodeType; import net.opengis.ows.x11.ServiceIdentificationDocument; import net.opengis.ows.x11.ServiceIdentificationDocument.ServiceIdentification; public class OxfServiceIdentification { private ServiceIdentification serviceIdentification; public OxfServiceIdentification(OxfServiceIdentificationBuilder builder) { this.serviceIdentification = ServiceIdentification.Factory.newInstance(); } public OxfServiceIdentification(ServiceIdentification serviceIdentification) { this.serviceIdentification = serviceIdentification; } public void setServiceIdentification(ServiceIdentification serviceIdentification) { this.serviceIdentification = serviceIdentification; } public ServiceIdentification getServiceIdentification() { return serviceIdentification; } public ServiceIdentificationDocument getServiceIdentificationAsDocument() { ServiceIdentificationDocument document = ServiceIdentificationDocument.Factory.newInstance(); document.setServiceIdentification(this.serviceIdentification); return document; } // public void setKeywords(String[] keywords) { // this.serviceIdentification.setKeywordsArray(keywords); // } public void setServiceType(String serviceType, String codeSpace) { CodeType codeType = CodeType.Factory.newInstance(); codeType.setStringValue(serviceType); codeType.setCodeSpace(codeSpace); this.serviceIdentification.setServiceType(codeType); } public void setServiceTypeVersion(String... serviceTypeVersion) { this.serviceIdentification.setServiceTypeVersionArray(serviceTypeVersion); } public void setProfiles(String[] profiles) { this.serviceIdentification.setProfileArray(profiles); } public void setFee(String fees) { this.serviceIdentification.setFees(fees); } public void setAccessConstraints(String[] accessConstraints) { this.serviceIdentification.setAccessConstraintsArray(accessConstraints); } }
EHJ-52n/OX-Framework
52n-oxf-ows-v110/src/main/java/org/n52/ows/service/OxfServiceIdentification.java
Java
gpl-2.0
3,418
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2010-2019 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2019 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.measurements.impl; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jrobin.core.RrdException; import org.opennms.netmgt.dao.api.ResourceDao; import org.opennms.netmgt.measurements.api.FetchResults; import org.opennms.netmgt.measurements.api.MeasurementFetchStrategy; import org.opennms.netmgt.measurements.model.QueryMetadata; import org.opennms.netmgt.measurements.model.QueryNode; import org.opennms.netmgt.measurements.model.QueryResource; import org.opennms.netmgt.measurements.model.Source; import org.opennms.netmgt.measurements.utils.Utils; import org.opennms.netmgt.model.OnmsNode; import org.opennms.netmgt.model.OnmsResource; import org.opennms.netmgt.model.ResourceId; import org.opennms.netmgt.model.ResourceTypeUtils; import org.opennms.netmgt.model.RrdGraphAttribute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.ObjectRetrievalFailureException; import com.google.common.base.Strings; import com.google.common.collect.Maps; /** * Used to fetch measurements from RRD files. * * @author Jesse White <jesse@opennms.org> */ public abstract class AbstractRrdBasedFetchStrategy implements MeasurementFetchStrategy { private static final Logger LOG = LoggerFactory.getLogger(AbstractRrdBasedFetchStrategy.class); @Autowired private ResourceDao m_resourceDao; /** * {@inheritDoc} */ @Override public FetchResults fetch(long start, long end, long step, int maxrows, Long interval, Long heartbeat, List<Source> sources, boolean relaxed) throws Exception { final Map<String, Object> constants = Maps.newHashMap(); final List<QueryResource> resources = new ArrayList<>(); final Map<Source, String> rrdsBySource = Maps.newHashMap(); final Map<ResourceId, OnmsResource> resourceCache = new HashMap<>(); for (final Source source : sources) { final ResourceId resourceId; try { resourceId = ResourceId.fromString(source.getResourceId()); } catch (final IllegalArgumentException ex) { if (relaxed) continue; LOG.error("Ill-formed resource id: {}", source.getResourceId(), ex); resources.add(null); return null; } // Grab the resource final OnmsResource resource = resourceCache.computeIfAbsent(resourceId, r -> m_resourceDao.getResourceById(r)); if (resource == null) { if (relaxed) continue; LOG.error("No resource with id: {}", source.getResourceId()); resources.add(null); return null; } final QueryResource resourceInfo = getResourceInfo(resource, source); resources.add(resourceInfo); // Grab the attribute RrdGraphAttribute rrdGraphAttribute = resource.getRrdGraphAttributes().get(source.getAttribute()); if (rrdGraphAttribute == null && !Strings.isNullOrEmpty(source.getFallbackAttribute())) { LOG.error("No attribute with name '{}', using fallback-attribute with name '{}'", source.getAttribute(), source.getFallbackAttribute()); source.setAttribute(source.getFallbackAttribute()); source.setFallbackAttribute(null); rrdGraphAttribute = resource.getRrdGraphAttributes().get(source.getAttribute()); } if (rrdGraphAttribute == null) { if (relaxed) continue; LOG.error("No attribute with name: {}", source.getAttribute()); return null; } // Gather the values from strings.properties Utils.convertStringAttributesToConstants(source.getLabel(), resource.getStringPropertyAttributes(), constants); // Build the path to the archive final String rrdFile = System.getProperty("rrd.base.dir") + File.separator + rrdGraphAttribute.getRrdRelativePath(); rrdsBySource.put(source, rrdFile); } // Fetch return fetchMeasurements(start, end, step, maxrows, rrdsBySource, constants, sources, new QueryMetadata(resources), relaxed); } /** * Performs the actual retrieval of the values from the RRD/JRB files. * * If relaxed is <code>true</code> an empty response will be generated if there * are no RRD/JRB files to query. * * If relaxed is <code>true</code> and one or more RRD/JRB files are present, * then {@link FetchResults} will be populated with {@link Double#NaN} for all missing entries. */ private FetchResults fetchMeasurements(long start, long end, long step, int maxrows, Map<Source, String> rrdsBySource, Map<String, Object> constants, List<Source> sources, QueryMetadata metadata, boolean relaxed) throws RrdException { // NMS-8665: Avoid making calls to XPORT with no definitions if (relaxed && rrdsBySource.isEmpty()) { return Utils.createEmtpyFetchResults(step, constants); } FetchResults fetchResults = fetchMeasurements(start, end, step, maxrows, rrdsBySource, constants, metadata); if (relaxed) { Utils.fillMissingValues(fetchResults, sources); } return fetchResults; } /** * Performs the actual retrieval of the values from the RRD/JRB files. */ protected abstract FetchResults fetchMeasurements(long start, long end, long step, int maxrows, Map<Source, String> rrdsBySource, Map<String, Object> constants, QueryMetadata metadata) throws RrdException; private static QueryResource getResourceInfo(final OnmsResource resource, final Source source) { if (resource == null) return null; OnmsNode node = null; try { node = ResourceTypeUtils.getNodeFromResourceRoot(resource); } catch (final ObjectRetrievalFailureException e) { LOG.warn("Failed to get node info from resource: {}", resource, e); } return new QueryResource( resource.getId().toString(), resource.getParent() == null? null : resource.getParent().getId().toString(), resource.getLabel(), resource.getName(), node == null? null : new QueryNode(node.getId(), node.getForeignSource(), node.getForeignId(), node.getLabel()) ); } }
jeffgdotorg/opennms
features/measurements/impl/src/main/java/org/opennms/netmgt/measurements/impl/AbstractRrdBasedFetchStrategy.java
Java
gpl-2.0
8,024
<?php /** * Loop Rating * * @author WooThemes * @package WooCommerce/Templates * @version 2.0.0 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $product; if ( get_option( 'woocommerce_enable_review_rating' ) === 'no' ) return; ?> <div class="rating"> <?php if ( $rating_html = $product->get_rating_html() ) { ?> <?php echo $rating_html; ?> <?php }else{ ?> <div class="star-rating"></div> <?php } ?> </div>
jimmitjoo/mnh
wp-content/themes/mix/woocommerce/loop/rating.php
PHP
gpl-2.0
457
#! /usr/bin/env python from hermes2d import Mesh, MeshView, H1Shapeset, PrecalcShapeset, H1Space, \ LinSystem, WeakForm, DummySolver, Solution, ScalarView from hermes2d.examples.c06 import set_bc, set_forms from hermes2d.examples import get_example_mesh mesh = Mesh() mesh.load(get_example_mesh()) #mesh.refine_element(0) #mesh.refine_all_elements() mesh.refine_towards_boundary(5, 3) shapeset = H1Shapeset() pss = PrecalcShapeset(shapeset) # create an H1 space space = H1Space(mesh, shapeset) space.set_uniform_order(5) set_bc(space) space.assign_dofs() xprev = Solution() yprev = Solution() # initialize the discrete problem wf = WeakForm(1) set_forms(wf) solver = DummySolver() sys = LinSystem(wf, solver) sys.set_spaces(space) sys.set_pss(pss) sln = Solution() sys.assemble() sys.solve_system(sln) view = ScalarView("Solution") view.show(sln, lib="mayavi") # view.wait() mview = MeshView("Hello world!", 100, 100, 500, 500) mview.show(mesh, lib="mpl", method="orders", notebook=False) mview.wait()
solin/hermes2d
python/examples/06.py
Python
gpl-2.0
1,022
/* * Firemox is a turn based strategy simulator * Copyright (C) 2003-2007 Fabrice Daugan * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package net.sf.firemox.expression; import java.io.IOException; import java.io.InputStream; import java.util.List; import net.sf.firemox.clickable.ability.Ability; import net.sf.firemox.clickable.target.Target; import net.sf.firemox.clickable.target.card.MCard; import net.sf.firemox.event.ArrangedZone; import net.sf.firemox.event.MEventListener; import net.sf.firemox.event.context.ContextEventListener; import net.sf.firemox.test.Test; import net.sf.firemox.test.TestOn; import net.sf.firemox.token.IdConst; import net.sf.firemox.token.IdZones; /** * @author <a href="mailto:fabdouglas@users.sourceforge.net">Fabrice Daugan </a> * @since 0.82 restriction zone supported to optimize the target processing. * @since 0.83 count-player option apply test on the players. * @since 0.85 objects may be counted */ public class Position extends Expression { /** * Creates a new instance of Counter <br> * <ul> * Structure of InputStream : Data[size] * <li>idTestOn [1] card to locate specified) * </ul> * * @param inputFile * file containing this action * @throws IOException * if error occurred during the reading process from the specified * input stream */ public Position(InputStream inputFile) throws IOException { super(); on = TestOn.deserialize(inputFile); } @Override public int getValue(Ability ability, Target tested, ContextEventListener context) { return on.getCard(ability, tested).getContainer().getRealIndexOf( on.getCard(ability, tested)).key; } @Override public void extractTriggeredEvents(List<MEventListener> res, MCard source, Test globalTest) { res .add(new ArrangedZone(IdZones.PLAY, globalTest, source, IdConst.NO_CARE)); } /** * Card to locate */ private TestOn on; }
JoeyLeeuwinga/Firemox
src/main/java/net/sf/firemox/expression/Position.java
Java
gpl-2.0
2,704
<?php namespace Drupal\webform\Tests; use Drupal\Component\Render\FormattableMarkup; use Drupal\Component\Utility\Unicode; use Drupal\Component\Utility\UrlHelper; use Drupal\Core\Config\FileStorage; use Drupal\Core\Serialization\Yaml; use Drupal\filter\Entity\FilterFormat; use Drupal\simpletest\WebTestBase; use Drupal\webform\WebformInterface; use Drupal\webform\Entity\Webform; use Drupal\webform\Entity\WebformSubmission; /** * Defines an abstract test base for webform tests. */ abstract class WebformTestBase extends WebTestBase { /** * Modules to enable. * * @var array */ protected static $modules = ['webform']; /** * Webforms to load. * * @var array */ protected static $testWebforms = []; /** * {@inheritdoc} */ public function setUp() { parent::setUp(); $this->loadWebforms(static::$testWebforms); } /** * {@inheritdoc} */ public function tearDown() { $this->purgeSubmissions(); parent::tearDown(); } /****************************************************************************/ // User. /****************************************************************************/ /** * A normal user to submit webforms. * * @var \Drupal\user\UserInterface */ protected $normalUser; /** * A webform administrator. * * @var \Drupal\user\UserInterface */ protected $adminWebformUser; /** * A webform submission administrator. * * @var \Drupal\user\UserInterface */ protected $adminSubmissionUser; /** * A webform own access. * * @var \Drupal\user\UserInterface */ protected $ownWebformUser; /** * A webform any access. * * @var \Drupal\user\UserInterface */ protected $anyWebformUser; /** * Create webform test users. */ protected function createUsers() { // Default user permissions. $default_user_permissions = []; $default_user_permissions[] = 'access user profiles'; if (in_array('webform_node', static::$modules)) { $default_user_permissions[] = 'access content'; } // Normal user. $normal_user_permissions = $default_user_permissions; $this->normalUser = $this->drupalCreateUser($normal_user_permissions); // Admin webform user. $admin_form_user_permissions = array_merge($default_user_permissions, [ 'administer webform', 'create webform', 'administer users', ]); if (in_array('block', static::$modules)) { $admin_form_user_permissions[] = 'administer blocks'; } if (in_array('webform_node', static::$modules)) { $admin_form_user_permissions[] = 'administer nodes'; } if (in_array('webform_test_translation', static::$modules)) { $admin_form_user_permissions[] = 'translate configuration'; } $this->adminWebformUser = $this->drupalCreateUser($admin_form_user_permissions); // Own webform user. $this->ownWebformUser = $this->drupalCreateUser(array_merge($default_user_permissions, [ 'access webform overview', 'create webform', 'edit own webform', 'delete own webform', ])); // Any webform user. $this->anyWebformUser = $this->drupalCreateUser(array_merge($default_user_permissions, [ 'access webform overview', 'create webform', 'edit any webform', 'delete any webform', ])); // Admin submission user. $this->adminSubmissionUser = $this->drupalCreateUser(array_merge($default_user_permissions, [ 'administer webform submission', ])); } /****************************************************************************/ // Block. /****************************************************************************/ /** * Place breadcrumb page, tasks, and actions. */ protected function placeBlocks() { $this->drupalPlaceBlock('system_breadcrumb_block'); $this->drupalPlaceBlock('page_title_block'); $this->drupalPlaceBlock('local_tasks_block'); $this->drupalPlaceBlock('local_actions_block'); } /****************************************************************************/ // Filter. /****************************************************************************/ /** * Basic HTML filter format. * * @var \Drupal\filter\FilterFormatInterface */ protected $basicHtmlFilter; /** * Full HTML filter format. * * @var \Drupal\filter\FilterFormatInterface */ protected $fullHtmlFilter; /** * Create basic HTML filter format. */ protected function createFilters() { $this->basicHtmlFilter = FilterFormat::create([ 'format' => 'basic_html', 'name' => 'Basic HTML', 'filters' => [ 'filter_html' => [ 'status' => 1, 'settings' => [ 'allowed_html' => '<p> <br> <strong> <a> <em>', ], ], ], ]); $this->basicHtmlFilter->save(); $this->fullHtmlFilter = FilterFormat::create([ 'format' => 'full_html', 'name' => 'Full HTML', ]); $this->fullHtmlFilter->save(); } /****************************************************************************/ // Nodes. /****************************************************************************/ /** * Get nodes keyed by nid. * * @return \Drupal\node\NodeInterface[] * Associative array of nodes keyed by nid. */ protected function getNodes() { if (empty($this->nodes)) { $this->drupalCreateContentType(['type' => 'page']); for ($i = 0; $i < 3; $i++) { $this->nodes[$i] = $this->drupalCreateNode(['type' => 'page', 'title' => 'Node ' . $i, 'status' => NODE_PUBLISHED]); $this->drupalGet('node/' . $this->nodes[$i]->id()); } } return $this->nodes; } /****************************************************************************/ // Webform. /****************************************************************************/ /** * Lazy load a test webforms. * * @param array $ids * Webform ids. */ protected function loadWebforms(array $ids) { foreach ($ids as $id) { $this->loadWebform($id); } $this->pass(new FormattableMarkup('Loaded webforms: %webforms.', [ '%webforms' => implode(', ', $ids), ])); } /** * Lazy load a test webform. * * @param string $id * Webform id. * * @return \Drupal\webform\WebformInterface|null * A webform. * * @see \Drupal\views\Tests\ViewTestData::createTestViews */ protected function loadWebform($id) { $storage = \Drupal::entityManager()->getStorage('webform'); if ($webform = $storage->load($id)) { return $webform; } else { $config_name = 'webform.webform.' . $id; if (strpos($id, 'test_') === 0) { $config_directory = drupal_get_path('module', 'webform') . '/tests/modules/webform_test/config/install'; } elseif (strpos($id, 'example_') === 0) { $config_directory = drupal_get_path('module', 'webform') . '/modules/webform_examples/config/install'; } elseif (strpos($id, 'template_') === 0) { $config_directory = drupal_get_path('module', 'webform') . '/modules/webform_templates/config/install'; } else { throw new \Exception("Webform $id not valid"); } if (!file_exists("$config_directory/$config_name.yml")) { throw new \Exception("Webform $id does not exist in $config_directory"); } $file_storage = new FileStorage($config_directory); $values = $file_storage->read($config_name); $webform = $storage->create($values); $webform->save(); return $webform; } } /** * Create a webform. * * @param array|null $elements * (optional) Array of elements. * @param array $settings * (optional) Webform settings. * * @return \Drupal\webform\WebformInterface * A webform. */ protected function createWebform(array $elements = [], array $settings = []) { // Create new webform. $id = $this->randomMachineName(8); $webform = Webform::create([ 'langcode' => 'en', 'status' => WebformInterface::STATUS_OPEN, 'id' => $id, 'title' => $id, 'elements' => Yaml::encode($elements), 'settings' => $settings + Webform::getDefaultSettings(), ]); $webform->save(); return $webform; } /** * Create a webform with submissions. * * @return array * Array containing the webform and submissions. */ protected function createWebformWithSubmissions() { // Load webform. $webform = $this->loadWebform('test_results'); // Load nodes. $nodes = $this->getNodes(); // Create some submissions. $names = [ [ 'George', 'Washington', 'Male', '1732-02-22', $nodes[0], ['white'], ['q1' => 1, 'q2' => 1, 'q3' => 1], ['address' => '{Address}', 'city' => '{City}', 'state_province' => 'New York', 'country' => 'United States', 'postal_code' => '11111-1111'], ], [ 'Abraham', 'Lincoln', 'Male', '1809-02-12', $nodes[1], ['red', 'white', 'blue'], ['q1' => 2, 'q2' => 2, 'q3' => 2], ['address' => '{Address}', 'city' => '{City}', 'state_province' => 'New York', 'country' => 'United States', 'postal_code' => '11111-1111'], ], [ 'Hillary', 'Clinton', 'Female', '1947-10-26', $nodes[2], ['red'], ['q1' => 2, 'q2' => 2, 'q3' => 2], ['address' => '{Address}', 'city' => '{City}', 'state_province' => 'New York', 'country' => 'United States', 'postal_code' => '11111-1111'], ], ]; $sids = []; foreach ($names as $name) { $edit = [ 'first_name' => $name[0], 'last_name' => $name[1], 'sex' => $name[2], 'dob' => $name[3], 'node' => $name[4]->label() . ' (' . $name[4]->id() . ')', ]; foreach ($name[5] as $color) { $edit["colors[$color]"] = $color; } foreach ($name[6] as $question => $answer) { $edit["likert[$question]"] = $answer; } foreach ($name[7] as $composite_key => $composite_value) { $edit["address[$composite_key]"] = $composite_value; } $sids[] = $this->postSubmission($webform, $edit); } // Change array keys to index instead of using entity ids. $submissions = array_values(WebformSubmission::loadMultiple($sids)); $this->assert($webform instanceof Webform, 'Webform was created'); $this->assertEqual(count($submissions), 3, 'WebformSubmissions were created.'); return [$webform, $submissions]; } /****************************************************************************/ // Submission. /****************************************************************************/ /** * Load the specified webform submission from the storage. * * @param int $sid * The submission identifier. * * @return \Drupal\webform\WebformSubmissionInterface * The loaded webform submission. */ protected function loadSubmission($sid) { /** @var \Drupal\webform\WebformSubmissionStorage $storage */ $storage = $this->container->get('entity.manager')->getStorage('webform_submission'); $storage->resetCache([$sid]); return $storage->load($sid); } /** * Purge all submission before the webform.module is uninstalled. */ protected function purgeSubmissions() { db_query('DELETE FROM {webform_submission}'); } /** * Post a new submission to a webform. * * @param \Drupal\webform\WebformInterface $webform * A webform. * @param array $edit * Submission values. * @param string $submit * Value of the submit button whose click is to be emulated. * * @return int * The created submission's sid. */ protected function postSubmission(WebformInterface $webform, array $edit = [], $submit = NULL) { $submit = $submit ?: $webform->getSetting('form_submit_label') ?: t('Submit'); $this->drupalPostForm('webform/' . $webform->id(), $edit, $submit); return $this->getLastSubmissionId($webform); } /** * Post a new test submission to a webform. * * @param \Drupal\webform\WebformInterface $webform * A webform. * @param array $edit * Submission values. * @param string $submit * Value of the submit button whose click is to be emulated. * * @return int * The created test submission's sid. */ protected function postSubmissionTest(WebformInterface $webform, array $edit = [], $submit = NULL) { $submit = $submit ?: $webform->getSetting('form_submit_label') ?: t('Submit'); $this->drupalPostForm('webform/' . $webform->id() . '/test', $edit, $submit); return $this->getLastSubmissionId($webform); } /** * Get the last submission id. * * @return int * The last submission id. */ protected function getLastSubmissionId($webform) { // Get submission sid. $url = UrlHelper::parse($this->getUrl()); if (isset($url['query']['sid'])) { return $url['query']['sid']; } else { $entity_ids = \Drupal::entityQuery('webform_submission') ->sort('sid', 'DESC') ->condition('webform_id', $webform->id()) ->execute(); return reset($entity_ids); } } /****************************************************************************/ // Export. /****************************************************************************/ /** * Request a webform results export CSV. * * @param \Drupal\webform\WebformInterface $webform * A webform. * @param array $options * An associative array of export options. */ protected function getExport(WebformInterface $webform, array $options = []) { /** @var \Drupal\webform\WebformSubmissionExporterInterface $exporter */ $exporter = \Drupal::service('webform_submission.exporter'); $options += $exporter->getDefaultExportOptions(); $this->drupalGet('admin/structure/webform/manage/' . $webform->id() . '/results/download', ['query' => $options]); } /** * Get webform export columns. * * @param \Drupal\webform\WebformInterface $webform * A webform. * * @return array * An array of exportable columns. */ protected function getExportColumns(WebformInterface $webform) { /** @var \Drupal\webform\WebformSubmissionStorageInterface $submission_storage */ $submission_storage = \Drupal::entityTypeManager()->getStorage('webform_submission'); $field_definitions = $submission_storage->getFieldDefinitions(); $field_definitions = $submission_storage->checkFieldDefinitionAccess($webform, $field_definitions); $elements = $webform->getElementsInitializedAndFlattened(); $columns = array_merge(array_keys($field_definitions), array_keys($elements)); return array_combine($columns, $columns); } /****************************************************************************/ // Email. /****************************************************************************/ /** * Gets that last email sent during the currently running test case. * * @return array * An array containing the last email message captured during the * current test. */ protected function getLastEmail() { $sent_emails = $this->drupalGetMails(); $sent_email = end($sent_emails); $this->debug($sent_email); return $sent_email; } /****************************************************************************/ // Assert. /****************************************************************************/ /** * Passes if the substring is contained within text, fails otherwise. */ protected function assertContains($haystack, $needle, $message = '', $group = 'Other') { if (!$message) { $t_args = [ '@haystack' => Unicode::truncate($haystack, 150, TRUE, TRUE), '@needle' => $needle, ]; $message = new FormattableMarkup('"@needle" found', $t_args); } $result = (strpos($haystack, $needle) !== FALSE); if (!$result) { $this->verbose($haystack); } return $this->assert($result, $message, $group); } /** * Passes if the substring is not contained within text, fails otherwise. */ protected function assertNotContains($haystack, $needle, $message = '', $group = 'Other') { if (!$message) { $t_args = [ '@haystack' => Unicode::truncate($haystack, 150, TRUE, TRUE), '@needle' => $needle, ]; $message = new FormattableMarkup('"@needle" not found', $t_args); } $result = (strpos($haystack, $needle) === FALSE); if (!$result) { $this->verbose($haystack); } return $this->assert($result, $message, $group); } /** * Passes if the CSS selector IS found on the loaded page, fail otherwise. */ protected function assertCssSelect($selector, $message = '') { $element = $this->cssSelect($selector); if (!$message) { $message = new FormattableMarkup('Found @selector', ['@selector' => $selector]); } $this->assertTrue(!empty($element), $message); } /** * Passes if the CSS selector IS NOT found on the loaded page, fail otherwise. */ protected function assertNoCssSelect($selector, $message = '') { $element = $this->cssSelect($selector); $this->assertTrue(empty($element), $message); } /****************************************************************************/ // Debug. /****************************************************************************/ /** * Logs verbose (debug) message in a text file. * * @param mixed $data * Data to be output. */ protected function debug($data) { $string = var_export($data, TRUE); $string = preg_replace('/=>\s*array\s*\(/', '=> array(', $string); $this->verbose('<pre>' . htmlentities($string) . '</pre>'); } }
rsathishkumar/edtx
modules/webform/src/Tests/WebformTestBase.php
PHP
gpl-2.0
17,969
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.tests.utils.package_tester import PackageTester PackageTester().run_all_tests_for_package('sanfrancisco')
christianurich/VIBe2UrbanSim
3rdparty/opus/src/sanfrancisco/tests/all_tests.py
Python
gpl-2.0
247
/***************************************************************************** Copyright (c) 1995, 2016, Oracle and/or its affiliates. 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; version 2 of the License. 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, Suite 500, Boston, MA 02110-1335 USA *****************************************************************************/ /******************************************************************//** @file fsp/fsp0fsp.cc File space management Created 11/29/1995 Heikki Tuuri ***********************************************************************/ #include "fsp0fsp.h" #ifdef UNIV_NONINL #include "fsp0fsp.ic" #endif #include "buf0buf.h" #include "fil0fil.h" #include "mtr0log.h" #include "ut0byte.h" #include "page0page.h" #include "page0zip.h" #ifdef UNIV_HOTBACKUP # include "fut0lst.h" #else /* UNIV_HOTBACKUP */ # include "sync0sync.h" # include "fut0fut.h" # include "srv0srv.h" # include "ibuf0ibuf.h" # include "btr0btr.h" # include "btr0sea.h" # include "dict0boot.h" # include "log0log.h" #endif /* UNIV_HOTBACKUP */ #include "dict0mem.h" #include "srv0start.h" #ifndef UNIV_HOTBACKUP /** Flag to indicate if we have printed the tablespace full error. */ static ibool fsp_tbs_full_error_printed = FALSE; /**********************************************************************//** Returns an extent to the free list of a space. */ static void fsp_free_extent( /*============*/ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint page, /*!< in: page offset in the extent */ mtr_t* mtr); /*!< in/out: mini-transaction */ /**********************************************************************//** Frees an extent of a segment to the space free list. */ static void fseg_free_extent( /*=============*/ fseg_inode_t* seg_inode, /*!< in: segment inode */ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint page, /*!< in: page offset in the extent */ mtr_t* mtr); /*!< in/out: mini-transaction */ /**********************************************************************//** Calculates the number of pages reserved by a segment, and how many pages are currently used. @return number of reserved pages */ static ulint fseg_n_reserved_pages_low( /*======================*/ fseg_inode_t* header, /*!< in: segment inode */ ulint* used, /*!< out: number of pages used (not more than reserved) */ mtr_t* mtr); /*!< in/out: mini-transaction */ /********************************************************************//** Marks a page used. The page must reside within the extents of the given segment. */ static MY_ATTRIBUTE((nonnull)) void fseg_mark_page_used( /*================*/ fseg_inode_t* seg_inode,/*!< in: segment inode */ ulint page, /*!< in: page offset */ xdes_t* descr, /*!< in: extent descriptor */ mtr_t* mtr); /*!< in/out: mini-transaction */ /**********************************************************************//** Returns the first extent descriptor for a segment. We think of the extent lists of the segment catenated in the order FSEG_FULL -> FSEG_NOT_FULL -> FSEG_FREE. @return the first extent descriptor, or NULL if none */ static xdes_t* fseg_get_first_extent( /*==================*/ fseg_inode_t* inode, /*!< in: segment inode */ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ mtr_t* mtr); /*!< in/out: mini-transaction */ /**********************************************************************//** Puts new extents to the free list if there are free extents above the free limit. If an extent happens to contain an extent descriptor page, the extent is put to the FSP_FREE_FRAG list with the page marked as used. */ static void fsp_fill_free_list( /*===============*/ ibool init_space, /*!< in: TRUE if this is a single-table tablespace and we are only initing the tablespace's first extent descriptor page and ibuf bitmap page; then we do not allocate more extents */ ulint space, /*!< in: space */ fsp_header_t* header, /*!< in/out: space header */ mtr_t* mtr) /*!< in/out: mini-transaction */ UNIV_COLD MY_ATTRIBUTE((nonnull)); /**********************************************************************//** Allocates a single free page from a segment. This function implements the intelligent allocation strategy which tries to minimize file space fragmentation. @retval NULL if no page could be allocated @retval block, rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded (init_mtr == mtr, or the page was not previously freed in mtr) @retval block (not allocated or initialized) otherwise */ static buf_block_t* fseg_alloc_free_page_low( /*=====================*/ ulint space, /*!< in: space */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ fseg_inode_t* seg_inode, /*!< in/out: segment inode */ ulint hint, /*!< in: hint of which page would be desirable */ byte direction, /*!< in: if the new page is needed because of an index page split, and records are inserted there in order, into which direction they go alphabetically: FSP_DOWN, FSP_UP, FSP_NO_DIR */ mtr_t* mtr, /*!< in/out: mini-transaction */ mtr_t* init_mtr)/*!< in/out: mtr or another mini-transaction in which the page should be initialized. If init_mtr!=mtr, but the page is already latched in mtr, do not initialize the page. */ MY_ATTRIBUTE((warn_unused_result, nonnull)); #endif /* !UNIV_HOTBACKUP */ /**********************************************************************//** Reads the file space size stored in the header page. @return tablespace size stored in the space header */ UNIV_INTERN ulint fsp_get_size_low( /*=============*/ page_t* page) /*!< in: header page (page 0 in the tablespace) */ { return(mach_read_from_4(page + FSP_HEADER_OFFSET + FSP_SIZE)); } #ifndef UNIV_HOTBACKUP /**********************************************************************//** Gets a pointer to the space header and x-locks its page. @return pointer to the space header, page x-locked */ UNIV_INLINE fsp_header_t* fsp_get_space_header( /*=================*/ ulint id, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ mtr_t* mtr) /*!< in/out: mini-transaction */ { buf_block_t* block; fsp_header_t* header; ut_ad(ut_is_2pow(zip_size)); ut_ad(zip_size <= UNIV_ZIP_SIZE_MAX); ut_ad(!zip_size || zip_size >= UNIV_ZIP_SIZE_MIN); ut_ad(id || !zip_size); block = buf_page_get(id, zip_size, 0, RW_X_LATCH, mtr); SRV_CORRUPT_TABLE_CHECK(block, return(0);); header = FSP_HEADER_OFFSET + buf_block_get_frame(block); buf_block_dbg_add_level(block, SYNC_FSP_PAGE); ut_ad(id == mach_read_from_4(FSP_SPACE_ID + header)); ut_ad(zip_size == fsp_flags_get_zip_size( mach_read_from_4(FSP_SPACE_FLAGS + header))); return(header); } /**********************************************************************//** Gets a descriptor bit of a page. @return TRUE if free */ UNIV_INLINE ibool xdes_mtr_get_bit( /*=============*/ const xdes_t* descr, /*!< in: descriptor */ ulint bit, /*!< in: XDES_FREE_BIT or XDES_CLEAN_BIT */ ulint offset, /*!< in: page offset within extent: 0 ... FSP_EXTENT_SIZE - 1 */ mtr_t* mtr) /*!< in: mini-transaction */ { ut_ad(mtr->state == MTR_ACTIVE); ut_ad(mtr_memo_contains_page(mtr, descr, MTR_MEMO_PAGE_X_FIX)); return(xdes_get_bit(descr, bit, offset)); } /**********************************************************************//** Sets a descriptor bit of a page. */ UNIV_INLINE void xdes_set_bit( /*=========*/ xdes_t* descr, /*!< in: descriptor */ ulint bit, /*!< in: XDES_FREE_BIT or XDES_CLEAN_BIT */ ulint offset, /*!< in: page offset within extent: 0 ... FSP_EXTENT_SIZE - 1 */ ibool val, /*!< in: bit value */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint index; ulint byte_index; ulint bit_index; ulint descr_byte; ut_ad(mtr_memo_contains_page(mtr, descr, MTR_MEMO_PAGE_X_FIX)); ut_ad((bit == XDES_FREE_BIT) || (bit == XDES_CLEAN_BIT)); ut_ad(offset < FSP_EXTENT_SIZE); index = bit + XDES_BITS_PER_PAGE * offset; byte_index = index / 8; bit_index = index % 8; descr_byte = mtr_read_ulint(descr + XDES_BITMAP + byte_index, MLOG_1BYTE, mtr); descr_byte = ut_bit_set_nth(descr_byte, bit_index, val); mlog_write_ulint(descr + XDES_BITMAP + byte_index, descr_byte, MLOG_1BYTE, mtr); } /**********************************************************************//** Looks for a descriptor bit having the desired value. Starts from hint and scans upward; at the end of the extent the search is wrapped to the start of the extent. @return bit index of the bit, ULINT_UNDEFINED if not found */ UNIV_INLINE ulint xdes_find_bit( /*==========*/ xdes_t* descr, /*!< in: descriptor */ ulint bit, /*!< in: XDES_FREE_BIT or XDES_CLEAN_BIT */ ibool val, /*!< in: desired bit value */ ulint hint, /*!< in: hint of which bit position would be desirable */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint i; ut_ad(descr && mtr); ut_ad(val <= TRUE); ut_ad(hint < FSP_EXTENT_SIZE); ut_ad(mtr_memo_contains_page(mtr, descr, MTR_MEMO_PAGE_X_FIX)); for (i = hint; i < FSP_EXTENT_SIZE; i++) { if (val == xdes_mtr_get_bit(descr, bit, i, mtr)) { return(i); } } for (i = 0; i < hint; i++) { if (val == xdes_mtr_get_bit(descr, bit, i, mtr)) { return(i); } } return(ULINT_UNDEFINED); } /**********************************************************************//** Returns the number of used pages in a descriptor. @return number of pages used */ UNIV_INLINE ulint xdes_get_n_used( /*============*/ const xdes_t* descr, /*!< in: descriptor */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint count = 0; ut_ad(descr && mtr); ut_ad(mtr_memo_contains_page(mtr, descr, MTR_MEMO_PAGE_X_FIX)); for (ulint i = 0; i < FSP_EXTENT_SIZE; ++i) { if (FALSE == xdes_mtr_get_bit(descr, XDES_FREE_BIT, i, mtr)) { count++; } } return(count); } /**********************************************************************//** Returns true if extent contains no used pages. @return TRUE if totally free */ UNIV_INLINE ibool xdes_is_free( /*=========*/ const xdes_t* descr, /*!< in: descriptor */ mtr_t* mtr) /*!< in/out: mini-transaction */ { if (0 == xdes_get_n_used(descr, mtr)) { return(TRUE); } return(FALSE); } /**********************************************************************//** Returns true if extent contains no free pages. @return TRUE if full */ UNIV_INLINE ibool xdes_is_full( /*=========*/ const xdes_t* descr, /*!< in: descriptor */ mtr_t* mtr) /*!< in/out: mini-transaction */ { if (FSP_EXTENT_SIZE == xdes_get_n_used(descr, mtr)) { return(TRUE); } return(FALSE); } /**********************************************************************//** Sets the state of an xdes. */ UNIV_INLINE void xdes_set_state( /*===========*/ xdes_t* descr, /*!< in/out: descriptor */ ulint state, /*!< in: state to set */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ut_ad(descr && mtr); ut_ad(state >= XDES_FREE); ut_ad(state <= XDES_FSEG); ut_ad(mtr_memo_contains_page(mtr, descr, MTR_MEMO_PAGE_X_FIX)); mlog_write_ulint(descr + XDES_STATE, state, MLOG_4BYTES, mtr); } /**********************************************************************//** Gets the state of an xdes. @return state */ UNIV_INLINE ulint xdes_get_state( /*===========*/ const xdes_t* descr, /*!< in: descriptor */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint state; ut_ad(descr && mtr); ut_ad(mtr_memo_contains_page(mtr, descr, MTR_MEMO_PAGE_X_FIX)); state = mtr_read_ulint(descr + XDES_STATE, MLOG_4BYTES, mtr); ut_ad(state - 1 < XDES_FSEG); return(state); } /**********************************************************************//** Inits an extent descriptor to the free and clean state. */ UNIV_INLINE void xdes_init( /*======*/ xdes_t* descr, /*!< in: descriptor */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint i; ut_ad(descr && mtr); ut_ad(mtr_memo_contains_page(mtr, descr, MTR_MEMO_PAGE_X_FIX)); ut_ad((XDES_SIZE - XDES_BITMAP) % 4 == 0); for (i = XDES_BITMAP; i < XDES_SIZE; i += 4) { mlog_write_ulint(descr + i, 0xFFFFFFFFUL, MLOG_4BYTES, mtr); } xdes_set_state(descr, XDES_FREE, mtr); } /********************************************************************//** Gets pointer to a the extent descriptor of a page. The page where the extent descriptor resides is x-locked. This function no longer extends the data file. @return pointer to the extent descriptor, NULL if the page does not exist in the space or if the offset is >= the free limit */ UNIV_INLINE MY_ATTRIBUTE((nonnull, warn_unused_result)) xdes_t* xdes_get_descriptor_with_space_hdr( /*===============================*/ fsp_header_t* sp_header, /*!< in/out: space header, x-latched in mtr */ ulint space, /*!< in: space id */ ulint offset, /*!< in: page offset; if equal to the free limit, we try to add new extents to the space free list */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint limit; ulint size; ulint zip_size; ulint descr_page_no; page_t* descr_page; ut_ad(mtr_memo_contains(mtr, fil_space_get_latch(space, NULL), MTR_MEMO_X_LOCK)); ut_ad(mtr_memo_contains_page(mtr, sp_header, MTR_MEMO_PAGE_X_FIX)); ut_ad(page_offset(sp_header) == FSP_HEADER_OFFSET); /* Read free limit and space size */ limit = mach_read_from_4(sp_header + FSP_FREE_LIMIT); size = mach_read_from_4(sp_header + FSP_SIZE); zip_size = fsp_flags_get_zip_size( mach_read_from_4(sp_header + FSP_SPACE_FLAGS)); if ((offset >= size) || (offset >= limit)) { return(NULL); } descr_page_no = xdes_calc_descriptor_page(zip_size, offset); if (descr_page_no == 0) { /* It is on the space header page */ descr_page = page_align(sp_header); } else { buf_block_t* block; block = buf_page_get(space, zip_size, descr_page_no, RW_X_LATCH, mtr); buf_block_dbg_add_level(block, SYNC_FSP_PAGE); descr_page = buf_block_get_frame(block); } return(descr_page + XDES_ARR_OFFSET + XDES_SIZE * xdes_calc_descriptor_index(zip_size, offset)); } /********************************************************************//** Gets pointer to a the extent descriptor of a page. The page where the extent descriptor resides is x-locked. This function no longer extends the data file. @return pointer to the extent descriptor, NULL if the page does not exist in the space or if the offset exceeds the free limit */ static MY_ATTRIBUTE((nonnull, warn_unused_result)) xdes_t* xdes_get_descriptor( /*================*/ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint offset, /*!< in: page offset; if equal to the free limit, we try to add new extents to the space free list */ mtr_t* mtr) /*!< in/out: mini-transaction */ { buf_block_t* block; fsp_header_t* sp_header; block = buf_page_get(space, zip_size, 0, RW_X_LATCH, mtr); SRV_CORRUPT_TABLE_CHECK(block, return(0);); buf_block_dbg_add_level(block, SYNC_FSP_PAGE); sp_header = FSP_HEADER_OFFSET + buf_block_get_frame(block); return(xdes_get_descriptor_with_space_hdr(sp_header, space, offset, mtr)); } /********************************************************************//** Gets pointer to a the extent descriptor if the file address of the descriptor list node is known. The page where the extent descriptor resides is x-locked. @return pointer to the extent descriptor */ UNIV_INLINE xdes_t* xdes_lst_get_descriptor( /*====================*/ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ fil_addr_t lst_node,/*!< in: file address of the list node contained in the descriptor */ mtr_t* mtr) /*!< in/out: mini-transaction */ { xdes_t* descr; ut_ad(mtr); ut_ad(mtr_memo_contains(mtr, fil_space_get_latch(space, NULL), MTR_MEMO_X_LOCK)); descr = fut_get_ptr(space, zip_size, lst_node, RW_X_LATCH, mtr) - XDES_FLST_NODE; return(descr); } /********************************************************************//** Returns page offset of the first page in extent described by a descriptor. @return offset of the first page in extent */ UNIV_INLINE ulint xdes_get_offset( /*============*/ const xdes_t* descr) /*!< in: extent descriptor */ { ut_ad(descr); return(page_get_page_no(page_align(descr)) + ((page_offset(descr) - XDES_ARR_OFFSET) / XDES_SIZE) * FSP_EXTENT_SIZE); } #endif /* !UNIV_HOTBACKUP */ /***********************************************************//** Inits a file page whose prior contents should be ignored. */ static void fsp_init_file_page_low( /*===================*/ buf_block_t* block) /*!< in: pointer to a page */ { page_t* page = buf_block_get_frame(block); page_zip_des_t* page_zip= buf_block_get_page_zip(block); #ifndef UNIV_HOTBACKUP block->check_index_page_at_flush = FALSE; #endif /* !UNIV_HOTBACKUP */ if (page_zip) { memset(page, 0, UNIV_PAGE_SIZE); memset(page_zip->data, 0, page_zip_get_size(page_zip)); mach_write_to_4(page + FIL_PAGE_OFFSET, buf_block_get_page_no(block)); mach_write_to_4(page + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID, buf_block_get_space(block)); memcpy(page_zip->data + FIL_PAGE_OFFSET, page + FIL_PAGE_OFFSET, 4); memcpy(page_zip->data + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID, page + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID, 4); return; } memset(page, 0, UNIV_PAGE_SIZE); mach_write_to_4(page + FIL_PAGE_OFFSET, buf_block_get_page_no(block)); mach_write_to_4(page + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID, buf_block_get_space(block)); } #ifndef UNIV_HOTBACKUP /***********************************************************//** Inits a file page whose prior contents should be ignored. */ static void fsp_init_file_page( /*===============*/ buf_block_t* block, /*!< in: pointer to a page */ mtr_t* mtr) /*!< in/out: mini-transaction */ { fsp_init_file_page_low(block); mlog_write_initial_log_record(buf_block_get_frame(block), MLOG_INIT_FILE_PAGE, mtr); } #endif /* !UNIV_HOTBACKUP */ /***********************************************************//** Parses a redo log record of a file page init. @return end of log record or NULL */ UNIV_INTERN byte* fsp_parse_init_file_page( /*=====================*/ byte* ptr, /*!< in: buffer */ byte* end_ptr MY_ATTRIBUTE((unused)), /*!< in: buffer end */ buf_block_t* block) /*!< in: block or NULL */ { ut_ad(ptr && end_ptr); if (block) { fsp_init_file_page_low(block); } return(ptr); } /**********************************************************************//** Initializes the fsp system. */ UNIV_INTERN void fsp_init(void) /*==========*/ { /* FSP_EXTENT_SIZE must be a multiple of page & zip size */ ut_a(0 == (UNIV_PAGE_SIZE % FSP_EXTENT_SIZE)); ut_a(UNIV_PAGE_SIZE); #if UNIV_PAGE_SIZE_MAX % FSP_EXTENT_SIZE_MAX # error "UNIV_PAGE_SIZE_MAX % FSP_EXTENT_SIZE_MAX != 0" #endif #if UNIV_ZIP_SIZE_MIN % FSP_EXTENT_SIZE_MIN # error "UNIV_ZIP_SIZE_MIN % FSP_EXTENT_SIZE_MIN != 0" #endif /* Does nothing at the moment */ } /**********************************************************************//** Writes the space id and flags to a tablespace header. The flags contain row type, physical/compressed page size, and logical/uncompressed page size of the tablespace. */ UNIV_INTERN void fsp_header_init_fields( /*===================*/ page_t* page, /*!< in/out: first page in the space */ ulint space_id, /*!< in: space id */ ulint flags) /*!< in: tablespace flags (FSP_SPACE_FLAGS) */ { ut_a(fsp_flags_is_valid(flags)); mach_write_to_4(FSP_HEADER_OFFSET + FSP_SPACE_ID + page, space_id); mach_write_to_4(FSP_HEADER_OFFSET + FSP_SPACE_FLAGS + page, flags); } #ifndef UNIV_HOTBACKUP /**********************************************************************//** Initializes the space header of a new created space and creates also the insert buffer tree root if space == 0. */ UNIV_INTERN void fsp_header_init( /*============*/ ulint space, /*!< in: space id */ ulint size, /*!< in: current size in blocks */ mtr_t* mtr) /*!< in/out: mini-transaction */ { fsp_header_t* header; buf_block_t* block; page_t* page; ulint flags; ulint zip_size; ut_ad(mtr); mtr_x_lock(fil_space_get_latch(space, &flags), mtr); zip_size = fsp_flags_get_zip_size(flags); block = buf_page_create(space, 0, zip_size, mtr); buf_page_get(space, zip_size, 0, RW_X_LATCH, mtr); buf_block_dbg_add_level(block, SYNC_FSP_PAGE); /* The prior contents of the file page should be ignored */ fsp_init_file_page(block, mtr); page = buf_block_get_frame(block); mlog_write_ulint(page + FIL_PAGE_TYPE, FIL_PAGE_TYPE_FSP_HDR, MLOG_2BYTES, mtr); header = FSP_HEADER_OFFSET + page; mlog_write_ulint(header + FSP_SPACE_ID, space, MLOG_4BYTES, mtr); mlog_write_ulint(header + FSP_NOT_USED, 0, MLOG_4BYTES, mtr); mlog_write_ulint(header + FSP_SIZE, size, MLOG_4BYTES, mtr); mlog_write_ulint(header + FSP_FREE_LIMIT, 0, MLOG_4BYTES, mtr); mlog_write_ulint(header + FSP_SPACE_FLAGS, flags, MLOG_4BYTES, mtr); mlog_write_ulint(header + FSP_FRAG_N_USED, 0, MLOG_4BYTES, mtr); flst_init(header + FSP_FREE, mtr); flst_init(header + FSP_FREE_FRAG, mtr); flst_init(header + FSP_FULL_FRAG, mtr); flst_init(header + FSP_SEG_INODES_FULL, mtr); flst_init(header + FSP_SEG_INODES_FREE, mtr); mlog_write_ull(header + FSP_SEG_ID, 1, mtr); if (space == 0) { fsp_fill_free_list(FALSE, space, header, mtr); btr_create(DICT_CLUSTERED | DICT_UNIVERSAL | DICT_IBUF, 0, 0, DICT_IBUF_ID_MIN + space, dict_ind_redundant, mtr); } else { fsp_fill_free_list(TRUE, space, header, mtr); } } #endif /* !UNIV_HOTBACKUP */ /**********************************************************************//** Reads the space id from the first page of a tablespace. @return space id, ULINT UNDEFINED if error */ UNIV_INTERN ulint fsp_header_get_space_id( /*====================*/ const page_t* page) /*!< in: first page of a tablespace */ { ulint fsp_id; ulint id; fsp_id = mach_read_from_4(FSP_HEADER_OFFSET + page + FSP_SPACE_ID); id = mach_read_from_4(page + FIL_PAGE_ARCH_LOG_NO_OR_SPACE_ID); DBUG_EXECUTE_IF("fsp_header_get_space_id_failure", id = ULINT_UNDEFINED;); if (id != fsp_id) { ib_logf(IB_LOG_LEVEL_ERROR, "Space id in fsp header %lu,but in the page header " "%lu", fsp_id, id); return(ULINT_UNDEFINED); } return(id); } /**********************************************************************//** Reads the space flags from the first page of a tablespace. @return flags */ UNIV_INTERN ulint fsp_header_get_flags( /*=================*/ const page_t* page) /*!< in: first page of a tablespace */ { ut_ad(!page_offset(page)); return(mach_read_from_4(FSP_HEADER_OFFSET + FSP_SPACE_FLAGS + page)); } /**********************************************************************//** Reads the compressed page size from the first page of a tablespace. @return compressed page size in bytes, or 0 if uncompressed */ UNIV_INTERN ulint fsp_header_get_zip_size( /*====================*/ const page_t* page) /*!< in: first page of a tablespace */ { ulint flags = fsp_header_get_flags(page); return(fsp_flags_get_zip_size(flags)); } #ifndef UNIV_HOTBACKUP /**********************************************************************//** Increases the space size field of a space. */ UNIV_INTERN void fsp_header_inc_size( /*================*/ ulint space, /*!< in: space id */ ulint size_inc, /*!< in: size increment in pages */ mtr_t* mtr) /*!< in/out: mini-transaction */ { fsp_header_t* header; ulint size; ulint flags; ut_ad(mtr); mtr_x_lock(fil_space_get_latch(space, &flags), mtr); header = fsp_get_space_header(space, fsp_flags_get_zip_size(flags), mtr); size = mtr_read_ulint(header + FSP_SIZE, MLOG_4BYTES, mtr); mlog_write_ulint(header + FSP_SIZE, size + size_inc, MLOG_4BYTES, mtr); } /**********************************************************************//** Gets the size of the system tablespace from the tablespace header. If we do not have an auto-extending data file, this should be equal to the size of the data files. If there is an auto-extending data file, this can be smaller. @return size in pages */ UNIV_INTERN ulint fsp_header_get_tablespace_size(void) /*================================*/ { fsp_header_t* header; ulint size; mtr_t mtr; mtr_start(&mtr); mtr_x_lock(fil_space_get_latch(0, NULL), &mtr); header = fsp_get_space_header(0, 0, &mtr); size = mtr_read_ulint(header + FSP_SIZE, MLOG_4BYTES, &mtr); mtr_commit(&mtr); return(size); } /***********************************************************************//** Tries to extend a single-table tablespace so that a page would fit in the data file. @return TRUE if success */ static UNIV_COLD MY_ATTRIBUTE((nonnull, warn_unused_result)) ibool fsp_try_extend_data_file_with_pages( /*================================*/ ulint space, /*!< in: space */ ulint page_no, /*!< in: page number */ fsp_header_t* header, /*!< in/out: space header */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ibool success; ulint actual_size; ulint size; ut_a(space != 0); size = mtr_read_ulint(header + FSP_SIZE, MLOG_4BYTES, mtr); ut_a(page_no >= size); success = fil_extend_space_to_desired_size(&actual_size, space, page_no + 1); /* actual_size now has the space size in pages; it may be less than we wanted if we ran out of disk space */ mlog_write_ulint(header + FSP_SIZE, actual_size, MLOG_4BYTES, mtr); return(success); } /***********************************************************************//** Tries to extend the last data file of a tablespace if it is auto-extending. @return FALSE if not auto-extending */ static UNIV_COLD MY_ATTRIBUTE((nonnull)) ibool fsp_try_extend_data_file( /*=====================*/ ulint* actual_increase,/*!< out: actual increase in pages, where we measure the tablespace size from what the header field says; it may be the actual file size rounded down to megabyte */ ulint space, /*!< in: space */ fsp_header_t* header, /*!< in/out: space header */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint size; ulint zip_size; ulint new_size; ulint old_size; ulint size_increase; ulint actual_size; ibool success; *actual_increase = 0; if (space == 0 && !srv_auto_extend_last_data_file) { /* We print the error message only once to avoid spamming the error log. Note that we don't need to reset the flag to FALSE as dealing with this error requires server restart. */ if (fsp_tbs_full_error_printed == FALSE) { fprintf(stderr, "InnoDB: Error: Data file(s) ran" " out of space.\n" "Please add another data file or" " use \'autoextend\' for the last" " data file.\n"); fsp_tbs_full_error_printed = TRUE; } return(FALSE); } size = mtr_read_ulint(header + FSP_SIZE, MLOG_4BYTES, mtr); zip_size = fsp_flags_get_zip_size( mach_read_from_4(header + FSP_SPACE_FLAGS)); old_size = size; if (space == 0) { if (!srv_last_file_size_max) { size_increase = SRV_AUTO_EXTEND_INCREMENT; } else { if (srv_last_file_size_max < srv_data_file_sizes[srv_n_data_files - 1]) { fprintf(stderr, "InnoDB: Error: Last data file size" " is %lu, max size allowed %lu\n", (ulong) srv_data_file_sizes[ srv_n_data_files - 1], (ulong) srv_last_file_size_max); } size_increase = srv_last_file_size_max - srv_data_file_sizes[srv_n_data_files - 1]; if (size_increase > SRV_AUTO_EXTEND_INCREMENT) { size_increase = SRV_AUTO_EXTEND_INCREMENT; } } } else { /* We extend single-table tablespaces first one extent at a time, but 4 at a time for bigger tablespaces. It is not enough to extend always by one extent, because we need to add at least one extent to FSP_FREE. A single extent descriptor page will track many extents. And the extent that uses its extent descriptor page is put onto the FSP_FREE_FRAG list. Extents that do not use their extent descriptor page are added to FSP_FREE. The physical page size is used to determine how many extents are tracked on one extent descriptor page. */ ulint extent_size; /*!< one megabyte, in pages */ ulint threshold; /*!< The size of the tablespace (in number of pages) where we start allocating more than one extent at a time. */ if (!zip_size) { extent_size = FSP_EXTENT_SIZE; } else { extent_size = FSP_EXTENT_SIZE * UNIV_PAGE_SIZE / zip_size; } /* Threshold is set at 32mb except when the page size is small enough that it must be done sooner. For page size less than 4k, we may reach the extent contains extent descriptor page before 32 mb. */ threshold = ut_min((32 * extent_size), (zip_size ? zip_size : UNIV_PAGE_SIZE)); if (size < extent_size) { /* Let us first extend the file to extent_size */ success = fsp_try_extend_data_file_with_pages( space, extent_size - 1, header, mtr); if (!success) { new_size = mtr_read_ulint(header + FSP_SIZE, MLOG_4BYTES, mtr); *actual_increase = new_size - old_size; return(FALSE); } size = extent_size; } if (size < threshold) { size_increase = extent_size; } else { /* Below in fsp_fill_free_list() we assume that we add at most FSP_FREE_ADD extents at a time */ size_increase = FSP_FREE_ADD * extent_size; } } if (size_increase == 0) { return(TRUE); } success = fil_extend_space_to_desired_size(&actual_size, space, size + size_increase); if (!success) { return(false); } /* We ignore any fragments of a full megabyte when storing the size to the space header */ if (!zip_size) { new_size = ut_calc_align_down(actual_size, (1024 * 1024) / UNIV_PAGE_SIZE); } else { new_size = ut_calc_align_down(actual_size, (1024 * 1024) / zip_size); } mlog_write_ulint(header + FSP_SIZE, new_size, MLOG_4BYTES, mtr); *actual_increase = new_size - old_size; return(TRUE); } /**********************************************************************//** Puts new extents to the free list if there are free extents above the free limit. If an extent happens to contain an extent descriptor page, the extent is put to the FSP_FREE_FRAG list with the page marked as used. */ static void fsp_fill_free_list( /*===============*/ ibool init_space, /*!< in: TRUE if this is a single-table tablespace and we are only initing the tablespace's first extent descriptor page and ibuf bitmap page; then we do not allocate more extents */ ulint space, /*!< in: space */ fsp_header_t* header, /*!< in/out: space header */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint limit; ulint size; ulint zip_size; xdes_t* descr; ulint count = 0; ulint frag_n_used; ulint actual_increase; ulint i; mtr_t ibuf_mtr; ut_ad(header != NULL); ut_ad(mtr != NULL); ut_ad(page_offset(header) == FSP_HEADER_OFFSET); /* Check if we can fill free list from above the free list limit */ size = mtr_read_ulint(header + FSP_SIZE, MLOG_4BYTES, mtr); limit = mtr_read_ulint(header + FSP_FREE_LIMIT, MLOG_4BYTES, mtr); zip_size = fsp_flags_get_zip_size( mach_read_from_4(FSP_SPACE_FLAGS + header)); ut_a(ut_is_2pow(zip_size)); ut_a(zip_size <= UNIV_ZIP_SIZE_MAX); ut_a(!zip_size || zip_size >= UNIV_ZIP_SIZE_MIN); if (space == 0 && srv_auto_extend_last_data_file && size < limit + FSP_EXTENT_SIZE * FSP_FREE_ADD) { /* Try to increase the last data file size */ fsp_try_extend_data_file(&actual_increase, space, header, mtr); size = mtr_read_ulint(header + FSP_SIZE, MLOG_4BYTES, mtr); } if (space != 0 && !init_space && size < limit + FSP_EXTENT_SIZE * FSP_FREE_ADD) { /* Try to increase the .ibd file size */ fsp_try_extend_data_file(&actual_increase, space, header, mtr); size = mtr_read_ulint(header + FSP_SIZE, MLOG_4BYTES, mtr); } i = limit; while ((init_space && i < 1) || ((i + FSP_EXTENT_SIZE <= size) && (count < FSP_FREE_ADD))) { ibool init_xdes; if (zip_size) { init_xdes = ut_2pow_remainder(i, zip_size) == 0; } else { init_xdes = ut_2pow_remainder(i, UNIV_PAGE_SIZE) == 0; } mlog_write_ulint(header + FSP_FREE_LIMIT, i + FSP_EXTENT_SIZE, MLOG_4BYTES, mtr); if (UNIV_UNLIKELY(init_xdes)) { buf_block_t* block; /* We are going to initialize a new descriptor page and a new ibuf bitmap page: the prior contents of the pages should be ignored. */ if (i > 0) { block = buf_page_create( space, i, zip_size, mtr); buf_page_get(space, zip_size, i, RW_X_LATCH, mtr); buf_block_dbg_add_level(block, SYNC_FSP_PAGE); fsp_init_file_page(block, mtr); mlog_write_ulint(buf_block_get_frame(block) + FIL_PAGE_TYPE, FIL_PAGE_TYPE_XDES, MLOG_2BYTES, mtr); } /* Initialize the ibuf bitmap page in a separate mini-transaction because it is low in the latching order, and we must be able to release its latch before returning from the fsp routine */ mtr_start(&ibuf_mtr); block = buf_page_create(space, i + FSP_IBUF_BITMAP_OFFSET, zip_size, &ibuf_mtr); buf_page_get(space, zip_size, i + FSP_IBUF_BITMAP_OFFSET, RW_X_LATCH, &ibuf_mtr); buf_block_dbg_add_level(block, SYNC_FSP_PAGE); fsp_init_file_page(block, &ibuf_mtr); ibuf_bitmap_page_init(block, &ibuf_mtr); mtr_commit(&ibuf_mtr); } descr = xdes_get_descriptor_with_space_hdr(header, space, i, mtr); xdes_init(descr, mtr); if (UNIV_UNLIKELY(init_xdes)) { /* The first page in the extent is a descriptor page and the second is an ibuf bitmap page: mark them used */ xdes_set_bit(descr, XDES_FREE_BIT, 0, FALSE, mtr); xdes_set_bit(descr, XDES_FREE_BIT, FSP_IBUF_BITMAP_OFFSET, FALSE, mtr); xdes_set_state(descr, XDES_FREE_FRAG, mtr); flst_add_last(header + FSP_FREE_FRAG, descr + XDES_FLST_NODE, mtr); frag_n_used = mtr_read_ulint(header + FSP_FRAG_N_USED, MLOG_4BYTES, mtr); mlog_write_ulint(header + FSP_FRAG_N_USED, frag_n_used + 2, MLOG_4BYTES, mtr); } else { flst_add_last(header + FSP_FREE, descr + XDES_FLST_NODE, mtr); count++; } i += FSP_EXTENT_SIZE; } } /**********************************************************************//** Allocates a new free extent. @return extent descriptor, NULL if cannot be allocated */ static xdes_t* fsp_alloc_free_extent( /*==================*/ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint hint, /*!< in: hint of which extent would be desirable: any page offset in the extent goes; the hint must not be > FSP_FREE_LIMIT */ mtr_t* mtr) /*!< in/out: mini-transaction */ { fsp_header_t* header; fil_addr_t first; xdes_t* descr; ut_ad(mtr); header = fsp_get_space_header(space, zip_size, mtr); descr = xdes_get_descriptor_with_space_hdr(header, space, hint, mtr); if (descr && (xdes_get_state(descr, mtr) == XDES_FREE)) { /* Ok, we can take this extent */ } else { /* Take the first extent in the free list */ first = flst_get_first(header + FSP_FREE, mtr); if (fil_addr_is_null(first)) { fsp_fill_free_list(FALSE, space, header, mtr); first = flst_get_first(header + FSP_FREE, mtr); } if (fil_addr_is_null(first)) { return(NULL); /* No free extents left */ } descr = xdes_lst_get_descriptor(space, zip_size, first, mtr); } flst_remove(header + FSP_FREE, descr + XDES_FLST_NODE, mtr); return(descr); } /**********************************************************************//** Allocates a single free page from a space. */ static MY_ATTRIBUTE((nonnull)) void fsp_alloc_from_free_frag( /*=====================*/ fsp_header_t* header, /*!< in/out: tablespace header */ xdes_t* descr, /*!< in/out: extent descriptor */ ulint bit, /*!< in: slot to allocate in the extent */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint frag_n_used; ut_ad(xdes_get_state(descr, mtr) == XDES_FREE_FRAG); ut_a(xdes_mtr_get_bit(descr, XDES_FREE_BIT, bit, mtr)); xdes_set_bit(descr, XDES_FREE_BIT, bit, FALSE, mtr); /* Update the FRAG_N_USED field */ frag_n_used = mtr_read_ulint(header + FSP_FRAG_N_USED, MLOG_4BYTES, mtr); frag_n_used++; mlog_write_ulint(header + FSP_FRAG_N_USED, frag_n_used, MLOG_4BYTES, mtr); if (xdes_is_full(descr, mtr)) { /* The fragment is full: move it to another list */ flst_remove(header + FSP_FREE_FRAG, descr + XDES_FLST_NODE, mtr); xdes_set_state(descr, XDES_FULL_FRAG, mtr); flst_add_last(header + FSP_FULL_FRAG, descr + XDES_FLST_NODE, mtr); mlog_write_ulint(header + FSP_FRAG_N_USED, frag_n_used - FSP_EXTENT_SIZE, MLOG_4BYTES, mtr); } } /**********************************************************************//** Gets a buffer block for an allocated page. NOTE: If init_mtr != mtr, the block will only be initialized if it was not previously x-latched. It is assumed that the block has been x-latched only by mtr, and freed in mtr in that case. @return block, initialized if init_mtr==mtr or rw_lock_x_lock_count(&block->lock) == 1 */ static buf_block_t* fsp_page_create( /*============*/ ulint space, /*!< in: space id of the allocated page */ ulint zip_size, /*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint page_no, /*!< in: page number of the allocated page */ mtr_t* mtr, /*!< in: mini-transaction of the allocation */ mtr_t* init_mtr) /*!< in: mini-transaction for initializing the page */ { buf_block_t* block = buf_page_create(space, page_no, zip_size, init_mtr); #ifdef UNIV_SYNC_DEBUG ut_ad(mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX) == rw_lock_own(&block->lock, RW_LOCK_EX)); #endif /* UNIV_SYNC_DEBUG */ /* Mimic buf_page_get(), but avoid the buf_pool->page_hash lookup. */ rw_lock_x_lock(&block->lock); mutex_enter(&block->mutex); buf_block_buf_fix_inc(block, __FILE__, __LINE__); mutex_exit(&block->mutex); mtr_memo_push(init_mtr, block, MTR_MEMO_PAGE_X_FIX); if (init_mtr == mtr || rw_lock_get_x_lock_count(&block->lock) == 1) { /* Initialize the page, unless it was already X-latched in mtr. (In this case, we would want to allocate another page that has not been freed in mtr.) */ ut_ad(init_mtr == mtr || !mtr_memo_contains(mtr, block, MTR_MEMO_PAGE_X_FIX)); fsp_init_file_page(block, init_mtr); } return(block); } /**********************************************************************//** Allocates a single free page from a space. The page is marked as used. @retval NULL if no page could be allocated @retval block, rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded (init_mtr == mtr, or the page was not previously freed in mtr) @retval block (not allocated or initialized) otherwise */ static MY_ATTRIBUTE((nonnull, warn_unused_result)) buf_block_t* fsp_alloc_free_page( /*================*/ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint hint, /*!< in: hint of which page would be desirable */ mtr_t* mtr, /*!< in/out: mini-transaction */ mtr_t* init_mtr)/*!< in/out: mini-transaction in which the page should be initialized (may be the same as mtr) */ { fsp_header_t* header; fil_addr_t first; xdes_t* descr; ulint free; ulint page_no; ulint space_size; ut_ad(mtr); ut_ad(init_mtr); header = fsp_get_space_header(space, zip_size, mtr); /* Get the hinted descriptor */ descr = xdes_get_descriptor_with_space_hdr(header, space, hint, mtr); if (descr && (xdes_get_state(descr, mtr) == XDES_FREE_FRAG)) { /* Ok, we can take this extent */ } else { /* Else take the first extent in free_frag list */ first = flst_get_first(header + FSP_FREE_FRAG, mtr); if (fil_addr_is_null(first)) { /* There are no partially full fragments: allocate a free extent and add it to the FREE_FRAG list. NOTE that the allocation may have as a side-effect that an extent containing a descriptor page is added to the FREE_FRAG list. But we will allocate our page from the the free extent anyway. */ descr = fsp_alloc_free_extent(space, zip_size, hint, mtr); if (descr == NULL) { /* No free space left */ return(NULL); } xdes_set_state(descr, XDES_FREE_FRAG, mtr); flst_add_last(header + FSP_FREE_FRAG, descr + XDES_FLST_NODE, mtr); } else { descr = xdes_lst_get_descriptor(space, zip_size, first, mtr); } /* Reset the hint */ hint = 0; } /* Now we have in descr an extent with at least one free page. Look for a free page in the extent. */ free = xdes_find_bit(descr, XDES_FREE_BIT, TRUE, hint % FSP_EXTENT_SIZE, mtr); if (free == ULINT_UNDEFINED) { ut_print_buf(stderr, ((byte*) descr) - 500, 1000); putc('\n', stderr); ut_error; } page_no = xdes_get_offset(descr) + free; space_size = mtr_read_ulint(header + FSP_SIZE, MLOG_4BYTES, mtr); if (space_size <= page_no) { /* It must be that we are extending a single-table tablespace whose size is still < 64 pages */ ut_a(space != 0); if (page_no >= FSP_EXTENT_SIZE) { fprintf(stderr, "InnoDB: Error: trying to extend a" " single-table tablespace %lu\n" "InnoDB: by single page(s) though the" " space size %lu. Page no %lu.\n", (ulong) space, (ulong) space_size, (ulong) page_no); return(NULL); } if (!fsp_try_extend_data_file_with_pages(space, page_no, header, mtr)) { /* No disk space left */ return(NULL); } } fsp_alloc_from_free_frag(header, descr, free, mtr); return(fsp_page_create(space, zip_size, page_no, mtr, init_mtr)); } /**********************************************************************//** Frees a single page of a space. The page is marked as free and clean. */ static void fsp_free_page( /*==========*/ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint page, /*!< in: page offset */ mtr_t* mtr) /*!< in/out: mini-transaction */ { fsp_header_t* header; xdes_t* descr; ulint state; ulint frag_n_used; ut_ad(mtr); /* fprintf(stderr, "Freeing page %lu in space %lu\n", page, space); */ header = fsp_get_space_header(space, zip_size, mtr); descr = xdes_get_descriptor_with_space_hdr(header, space, page, mtr); state = xdes_get_state(descr, mtr); if (state != XDES_FREE_FRAG && state != XDES_FULL_FRAG) { fprintf(stderr, "InnoDB: Error: File space extent descriptor" " of page %lu has state %lu\n", (ulong) page, (ulong) state); fputs("InnoDB: Dump of descriptor: ", stderr); ut_print_buf(stderr, ((byte*) descr) - 50, 200); putc('\n', stderr); /* Crash in debug version, so that we get a core dump of this corruption. */ ut_ad(0); if (state == XDES_FREE) { /* We put here some fault tolerance: if the page is already free, return without doing anything! */ return; } ut_error; } if (xdes_mtr_get_bit(descr, XDES_FREE_BIT, page % FSP_EXTENT_SIZE, mtr)) { fprintf(stderr, "InnoDB: Error: File space extent descriptor" " of page %lu says it is free\n" "InnoDB: Dump of descriptor: ", (ulong) page); ut_print_buf(stderr, ((byte*) descr) - 50, 200); putc('\n', stderr); /* Crash in debug version, so that we get a core dump of this corruption. */ ut_ad(0); /* We put here some fault tolerance: if the page is already free, return without doing anything! */ return; } xdes_set_bit(descr, XDES_FREE_BIT, page % FSP_EXTENT_SIZE, TRUE, mtr); xdes_set_bit(descr, XDES_CLEAN_BIT, page % FSP_EXTENT_SIZE, TRUE, mtr); frag_n_used = mtr_read_ulint(header + FSP_FRAG_N_USED, MLOG_4BYTES, mtr); if (state == XDES_FULL_FRAG) { /* The fragment was full: move it to another list */ flst_remove(header + FSP_FULL_FRAG, descr + XDES_FLST_NODE, mtr); xdes_set_state(descr, XDES_FREE_FRAG, mtr); flst_add_last(header + FSP_FREE_FRAG, descr + XDES_FLST_NODE, mtr); mlog_write_ulint(header + FSP_FRAG_N_USED, frag_n_used + FSP_EXTENT_SIZE - 1, MLOG_4BYTES, mtr); } else { ut_a(frag_n_used > 0); mlog_write_ulint(header + FSP_FRAG_N_USED, frag_n_used - 1, MLOG_4BYTES, mtr); } if (xdes_is_free(descr, mtr)) { /* The extent has become free: move it to another list */ flst_remove(header + FSP_FREE_FRAG, descr + XDES_FLST_NODE, mtr); fsp_free_extent(space, zip_size, page, mtr); } mtr->n_freed_pages++; } /**********************************************************************//** Returns an extent to the free list of a space. */ static void fsp_free_extent( /*============*/ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint page, /*!< in: page offset in the extent */ mtr_t* mtr) /*!< in/out: mini-transaction */ { fsp_header_t* header; xdes_t* descr; ut_ad(mtr); header = fsp_get_space_header(space, zip_size, mtr); descr = xdes_get_descriptor_with_space_hdr(header, space, page, mtr); if (xdes_get_state(descr, mtr) == XDES_FREE) { ut_print_buf(stderr, (byte*) descr - 500, 1000); putc('\n', stderr); ut_error; } xdes_init(descr, mtr); flst_add_last(header + FSP_FREE, descr + XDES_FLST_NODE, mtr); } /**********************************************************************//** Returns the nth inode slot on an inode page. @return segment inode */ UNIV_INLINE fseg_inode_t* fsp_seg_inode_page_get_nth_inode( /*=============================*/ page_t* page, /*!< in: segment inode page */ ulint i, /*!< in: inode index on page */ ulint zip_size MY_ATTRIBUTE((unused)), /*!< in: compressed page size, or 0 */ mtr_t* mtr MY_ATTRIBUTE((unused))) /*!< in/out: mini-transaction */ { ut_ad(i < FSP_SEG_INODES_PER_PAGE(zip_size)); ut_ad(mtr_memo_contains_page(mtr, page, MTR_MEMO_PAGE_X_FIX)); return(page + FSEG_ARR_OFFSET + FSEG_INODE_SIZE * i); } /**********************************************************************//** Looks for a used segment inode on a segment inode page. @return segment inode index, or ULINT_UNDEFINED if not found */ static ulint fsp_seg_inode_page_find_used( /*=========================*/ page_t* page, /*!< in: segment inode page */ ulint zip_size,/*!< in: compressed page size, or 0 */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint i; fseg_inode_t* inode; for (i = 0; i < FSP_SEG_INODES_PER_PAGE(zip_size); i++) { inode = fsp_seg_inode_page_get_nth_inode( page, i, zip_size, mtr); if (mach_read_from_8(inode + FSEG_ID)) { /* This is used */ ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); return(i); } } return(ULINT_UNDEFINED); } /**********************************************************************//** Looks for an unused segment inode on a segment inode page. @return segment inode index, or ULINT_UNDEFINED if not found */ static ulint fsp_seg_inode_page_find_free( /*=========================*/ page_t* page, /*!< in: segment inode page */ ulint i, /*!< in: search forward starting from this index */ ulint zip_size,/*!< in: compressed page size, or 0 */ mtr_t* mtr) /*!< in/out: mini-transaction */ { SRV_CORRUPT_TABLE_CHECK(page, return(ULINT_UNDEFINED);); for (; i < FSP_SEG_INODES_PER_PAGE(zip_size); i++) { fseg_inode_t* inode; inode = fsp_seg_inode_page_get_nth_inode( page, i, zip_size, mtr); if (!mach_read_from_8(inode + FSEG_ID)) { /* This is unused */ return(i); } ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); } return(ULINT_UNDEFINED); } /**********************************************************************//** Allocates a new file segment inode page. @return TRUE if could be allocated */ static ibool fsp_alloc_seg_inode_page( /*=====================*/ fsp_header_t* space_header, /*!< in: space header */ mtr_t* mtr) /*!< in/out: mini-transaction */ { fseg_inode_t* inode; buf_block_t* block; page_t* page; ulint space; ulint zip_size; ut_ad(page_offset(space_header) == FSP_HEADER_OFFSET); space = page_get_space_id(page_align(space_header)); zip_size = fsp_flags_get_zip_size( mach_read_from_4(FSP_SPACE_FLAGS + space_header)); block = fsp_alloc_free_page(space, zip_size, 0, mtr, mtr); if (block == NULL) { return(FALSE); } buf_block_dbg_add_level(block, SYNC_FSP_PAGE); ut_ad(rw_lock_get_x_lock_count(&block->lock) == 1); block->check_index_page_at_flush = FALSE; page = buf_block_get_frame(block); mlog_write_ulint(page + FIL_PAGE_TYPE, FIL_PAGE_INODE, MLOG_2BYTES, mtr); for (ulint i = 0; i < FSP_SEG_INODES_PER_PAGE(zip_size); i++) { inode = fsp_seg_inode_page_get_nth_inode( page, i, zip_size, mtr); mlog_write_ull(inode + FSEG_ID, 0, mtr); } flst_add_last( space_header + FSP_SEG_INODES_FREE, page + FSEG_INODE_PAGE_NODE, mtr); return(TRUE); } /**********************************************************************//** Allocates a new file segment inode. @return segment inode, or NULL if not enough space */ static fseg_inode_t* fsp_alloc_seg_inode( /*================*/ fsp_header_t* space_header, /*!< in: space header */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint page_no; buf_block_t* block; page_t* page; fseg_inode_t* inode; ibool success; ulint zip_size; ulint n; ut_ad(page_offset(space_header) == FSP_HEADER_OFFSET); if (flst_get_len(space_header + FSP_SEG_INODES_FREE, mtr) == 0) { /* Allocate a new segment inode page */ success = fsp_alloc_seg_inode_page(space_header, mtr); if (!success) { return(NULL); } } page_no = flst_get_first(space_header + FSP_SEG_INODES_FREE, mtr).page; zip_size = fsp_flags_get_zip_size( mach_read_from_4(FSP_SPACE_FLAGS + space_header)); block = buf_page_get(page_get_space_id(page_align(space_header)), zip_size, page_no, RW_X_LATCH, mtr); buf_block_dbg_add_level(block, SYNC_FSP_PAGE); page = buf_block_get_frame(block); SRV_CORRUPT_TABLE_CHECK(page, return(0);); n = fsp_seg_inode_page_find_free(page, 0, zip_size, mtr); ut_a(n != ULINT_UNDEFINED); inode = fsp_seg_inode_page_get_nth_inode(page, n, zip_size, mtr); if (ULINT_UNDEFINED == fsp_seg_inode_page_find_free(page, n + 1, zip_size, mtr)) { /* There are no other unused headers left on the page: move it to another list */ flst_remove(space_header + FSP_SEG_INODES_FREE, page + FSEG_INODE_PAGE_NODE, mtr); flst_add_last(space_header + FSP_SEG_INODES_FULL, page + FSEG_INODE_PAGE_NODE, mtr); } ut_ad(!mach_read_from_8(inode + FSEG_ID) || mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); return(inode); } /**********************************************************************//** Frees a file segment inode. */ static void fsp_free_seg_inode( /*===============*/ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ fseg_inode_t* inode, /*!< in: segment inode */ mtr_t* mtr) /*!< in/out: mini-transaction */ { page_t* page; fsp_header_t* space_header; page = page_align(inode); space_header = fsp_get_space_header(space, zip_size, mtr); ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); if (ULINT_UNDEFINED == fsp_seg_inode_page_find_free(page, 0, zip_size, mtr)) { /* Move the page to another list */ flst_remove(space_header + FSP_SEG_INODES_FULL, page + FSEG_INODE_PAGE_NODE, mtr); flst_add_last(space_header + FSP_SEG_INODES_FREE, page + FSEG_INODE_PAGE_NODE, mtr); } mlog_write_ull(inode + FSEG_ID, 0, mtr); mlog_write_ulint(inode + FSEG_MAGIC_N, 0xfa051ce3, MLOG_4BYTES, mtr); if (ULINT_UNDEFINED == fsp_seg_inode_page_find_used(page, zip_size, mtr)) { /* There are no other used headers left on the page: free it */ flst_remove(space_header + FSP_SEG_INODES_FREE, page + FSEG_INODE_PAGE_NODE, mtr); fsp_free_page(space, zip_size, page_get_page_no(page), mtr); } } /**********************************************************************//** Returns the file segment inode, page x-latched. @return segment inode, page x-latched; NULL if the inode is free */ static fseg_inode_t* fseg_inode_try_get( /*===============*/ fseg_header_t* header, /*!< in: segment header */ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ mtr_t* mtr) /*!< in/out: mini-transaction */ { fil_addr_t inode_addr; fseg_inode_t* inode; inode_addr.page = mach_read_from_4(header + FSEG_HDR_PAGE_NO); inode_addr.boffset = mach_read_from_2(header + FSEG_HDR_OFFSET); ut_ad(space == mach_read_from_4(header + FSEG_HDR_SPACE)); inode = fut_get_ptr(space, zip_size, inode_addr, RW_X_LATCH, mtr); SRV_CORRUPT_TABLE_CHECK(inode, return(0);); if (UNIV_UNLIKELY(!mach_read_from_8(inode + FSEG_ID))) { inode = NULL; } else { ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); } return(inode); } /**********************************************************************//** Returns the file segment inode, page x-latched. @return segment inode, page x-latched */ static fseg_inode_t* fseg_inode_get( /*===========*/ fseg_header_t* header, /*!< in: segment header */ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ mtr_t* mtr) /*!< in/out: mini-transaction */ { fseg_inode_t* inode = fseg_inode_try_get(header, space, zip_size, mtr); SRV_CORRUPT_TABLE_CHECK(inode, ; /* do nothing */); return(inode); } /**********************************************************************//** Gets the page number from the nth fragment page slot. @return page number, FIL_NULL if not in use */ UNIV_INLINE ulint fseg_get_nth_frag_page_no( /*======================*/ fseg_inode_t* inode, /*!< in: segment inode */ ulint n, /*!< in: slot index */ mtr_t* mtr MY_ATTRIBUTE((unused))) /*!< in/out: mini-transaction */ { ut_ad(inode && mtr); ut_ad(n < FSEG_FRAG_ARR_N_SLOTS); ut_ad(mtr_memo_contains_page(mtr, inode, MTR_MEMO_PAGE_X_FIX)); ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); return(mach_read_from_4(inode + FSEG_FRAG_ARR + n * FSEG_FRAG_SLOT_SIZE)); } /**********************************************************************//** Sets the page number in the nth fragment page slot. */ UNIV_INLINE void fseg_set_nth_frag_page_no( /*======================*/ fseg_inode_t* inode, /*!< in: segment inode */ ulint n, /*!< in: slot index */ ulint page_no,/*!< in: page number to set */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ut_ad(inode && mtr); ut_ad(n < FSEG_FRAG_ARR_N_SLOTS); ut_ad(mtr_memo_contains_page(mtr, inode, MTR_MEMO_PAGE_X_FIX)); ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); mlog_write_ulint(inode + FSEG_FRAG_ARR + n * FSEG_FRAG_SLOT_SIZE, page_no, MLOG_4BYTES, mtr); } /**********************************************************************//** Finds a fragment page slot which is free. @return slot index; ULINT_UNDEFINED if none found */ static ulint fseg_find_free_frag_page_slot( /*==========================*/ fseg_inode_t* inode, /*!< in: segment inode */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint i; ulint page_no; ut_ad(inode && mtr); for (i = 0; i < FSEG_FRAG_ARR_N_SLOTS; i++) { page_no = fseg_get_nth_frag_page_no(inode, i, mtr); if (page_no == FIL_NULL) { return(i); } } return(ULINT_UNDEFINED); } /**********************************************************************//** Finds a fragment page slot which is used and last in the array. @return slot index; ULINT_UNDEFINED if none found */ static ulint fseg_find_last_used_frag_page_slot( /*===============================*/ fseg_inode_t* inode, /*!< in: segment inode */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint i; ulint page_no; ut_ad(inode && mtr); for (i = 0; i < FSEG_FRAG_ARR_N_SLOTS; i++) { page_no = fseg_get_nth_frag_page_no( inode, FSEG_FRAG_ARR_N_SLOTS - i - 1, mtr); if (page_no != FIL_NULL) { return(FSEG_FRAG_ARR_N_SLOTS - i - 1); } } return(ULINT_UNDEFINED); } /**********************************************************************//** Calculates reserved fragment page slots. @return number of fragment pages */ static ulint fseg_get_n_frag_pages( /*==================*/ fseg_inode_t* inode, /*!< in: segment inode */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint i; ulint count = 0; ut_ad(inode && mtr); for (i = 0; i < FSEG_FRAG_ARR_N_SLOTS; i++) { if (FIL_NULL != fseg_get_nth_frag_page_no(inode, i, mtr)) { count++; } } return(count); } /**********************************************************************//** Creates a new segment. @return the block where the segment header is placed, x-latched, NULL if could not create segment because of lack of space */ UNIV_INTERN buf_block_t* fseg_create_general( /*================*/ ulint space, /*!< in: space id */ ulint page, /*!< in: page where the segment header is placed: if this is != 0, the page must belong to another segment, if this is 0, a new page will be allocated and it will belong to the created segment */ ulint byte_offset, /*!< in: byte offset of the created segment header on the page */ ibool has_done_reservation, /*!< in: TRUE if the caller has already done the reservation for the pages with fsp_reserve_free_extents (at least 2 extents: one for the inode and the other for the segment) then there is no need to do the check for this individual operation */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint flags; ulint zip_size; fsp_header_t* space_header; fseg_inode_t* inode; ib_id_t seg_id; buf_block_t* block = 0; /* remove warning */ fseg_header_t* header = 0; /* remove warning */ prio_rw_lock_t* latch; ibool success; ulint n_reserved; ulint i; ut_ad(mtr); ut_ad(byte_offset + FSEG_HEADER_SIZE <= UNIV_PAGE_SIZE - FIL_PAGE_DATA_END); latch = fil_space_get_latch(space, &flags); zip_size = fsp_flags_get_zip_size(flags); if (page != 0) { block = buf_page_get(space, zip_size, page, RW_X_LATCH, mtr); header = byte_offset + buf_block_get_frame(block); } mtr_x_lock(latch, mtr); if (rw_lock_get_x_lock_count(latch) == 1) { /* This thread did not own the latch before this call: free excess pages from the insert buffer free list */ if (space == IBUF_SPACE_ID) { ibuf_free_excess_pages(); } } if (!has_done_reservation) { success = fsp_reserve_free_extents(&n_reserved, space, 2, FSP_NORMAL, mtr); if (!success) { return(NULL); } } space_header = fsp_get_space_header(space, zip_size, mtr); inode = fsp_alloc_seg_inode(space_header, mtr); if (inode == NULL) { goto funct_exit; } /* Read the next segment id from space header and increment the value in space header */ seg_id = mach_read_from_8(space_header + FSP_SEG_ID); mlog_write_ull(space_header + FSP_SEG_ID, seg_id + 1, mtr); mlog_write_ull(inode + FSEG_ID, seg_id, mtr); mlog_write_ulint(inode + FSEG_NOT_FULL_N_USED, 0, MLOG_4BYTES, mtr); flst_init(inode + FSEG_FREE, mtr); flst_init(inode + FSEG_NOT_FULL, mtr); flst_init(inode + FSEG_FULL, mtr); mlog_write_ulint(inode + FSEG_MAGIC_N, FSEG_MAGIC_N_VALUE, MLOG_4BYTES, mtr); for (i = 0; i < FSEG_FRAG_ARR_N_SLOTS; i++) { fseg_set_nth_frag_page_no(inode, i, FIL_NULL, mtr); } if (page == 0) { block = fseg_alloc_free_page_low(space, zip_size, inode, 0, FSP_UP, mtr, mtr); if (block == NULL) { fsp_free_seg_inode(space, zip_size, inode, mtr); goto funct_exit; } ut_ad(rw_lock_get_x_lock_count(&block->lock) == 1); header = byte_offset + buf_block_get_frame(block); mlog_write_ulint(buf_block_get_frame(block) + FIL_PAGE_TYPE, FIL_PAGE_TYPE_SYS, MLOG_2BYTES, mtr); } mlog_write_ulint(header + FSEG_HDR_OFFSET, page_offset(inode), MLOG_2BYTES, mtr); mlog_write_ulint(header + FSEG_HDR_PAGE_NO, page_get_page_no(page_align(inode)), MLOG_4BYTES, mtr); mlog_write_ulint(header + FSEG_HDR_SPACE, space, MLOG_4BYTES, mtr); funct_exit: if (!has_done_reservation) { fil_space_release_free_extents(space, n_reserved); } return(block); } /**********************************************************************//** Creates a new segment. @return the block where the segment header is placed, x-latched, NULL if could not create segment because of lack of space */ UNIV_INTERN buf_block_t* fseg_create( /*========*/ ulint space, /*!< in: space id */ ulint page, /*!< in: page where the segment header is placed: if this is != 0, the page must belong to another segment, if this is 0, a new page will be allocated and it will belong to the created segment */ ulint byte_offset, /*!< in: byte offset of the created segment header on the page */ mtr_t* mtr) /*!< in/out: mini-transaction */ { return(fseg_create_general(space, page, byte_offset, FALSE, mtr)); } /**********************************************************************//** Calculates the number of pages reserved by a segment, and how many pages are currently used. @return number of reserved pages */ static ulint fseg_n_reserved_pages_low( /*======================*/ fseg_inode_t* inode, /*!< in: segment inode */ ulint* used, /*!< out: number of pages used (not more than reserved) */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint ret; ut_ad(inode && used && mtr); ut_ad(mtr_memo_contains_page(mtr, inode, MTR_MEMO_PAGE_X_FIX)); *used = mtr_read_ulint(inode + FSEG_NOT_FULL_N_USED, MLOG_4BYTES, mtr) + FSP_EXTENT_SIZE * flst_get_len(inode + FSEG_FULL, mtr) + fseg_get_n_frag_pages(inode, mtr); ret = fseg_get_n_frag_pages(inode, mtr) + FSP_EXTENT_SIZE * flst_get_len(inode + FSEG_FREE, mtr) + FSP_EXTENT_SIZE * flst_get_len(inode + FSEG_NOT_FULL, mtr) + FSP_EXTENT_SIZE * flst_get_len(inode + FSEG_FULL, mtr); return(ret); } /**********************************************************************//** Calculates the number of pages reserved by a segment, and how many pages are currently used. @return number of reserved pages */ UNIV_INTERN ulint fseg_n_reserved_pages( /*==================*/ fseg_header_t* header, /*!< in: segment header */ ulint* used, /*!< out: number of pages used (<= reserved) */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint ret; fseg_inode_t* inode; ulint space; ulint flags; ulint zip_size; prio_rw_lock_t* latch; space = page_get_space_id(page_align(header)); latch = fil_space_get_latch(space, &flags); zip_size = fsp_flags_get_zip_size(flags); mtr_x_lock(latch, mtr); inode = fseg_inode_get(header, space, zip_size, mtr); ret = fseg_n_reserved_pages_low(inode, used, mtr); return(ret); } /*********************************************************************//** Tries to fill the free list of a segment with consecutive free extents. This happens if the segment is big enough to allow extents in the free list, the free list is empty, and the extents can be allocated consecutively from the hint onward. */ static void fseg_fill_free_list( /*================*/ fseg_inode_t* inode, /*!< in: segment inode */ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint hint, /*!< in: hint which extent would be good as the first extent */ mtr_t* mtr) /*!< in/out: mini-transaction */ { xdes_t* descr; ulint i; ib_id_t seg_id; ulint reserved; ulint used; ut_ad(inode && mtr); ut_ad(!((page_offset(inode) - FSEG_ARR_OFFSET) % FSEG_INODE_SIZE)); reserved = fseg_n_reserved_pages_low(inode, &used, mtr); if (reserved < FSEG_FREE_LIST_LIMIT * FSP_EXTENT_SIZE) { /* The segment is too small to allow extents in free list */ return; } if (flst_get_len(inode + FSEG_FREE, mtr) > 0) { /* Free list is not empty */ return; } for (i = 0; i < FSEG_FREE_LIST_MAX_LEN; i++) { descr = xdes_get_descriptor(space, zip_size, hint, mtr); if ((descr == NULL) || (XDES_FREE != xdes_get_state(descr, mtr))) { /* We cannot allocate the desired extent: stop */ return; } descr = fsp_alloc_free_extent(space, zip_size, hint, mtr); xdes_set_state(descr, XDES_FSEG, mtr); seg_id = mach_read_from_8(inode + FSEG_ID); ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); mlog_write_ull(descr + XDES_ID, seg_id, mtr); flst_add_last(inode + FSEG_FREE, descr + XDES_FLST_NODE, mtr); hint += FSP_EXTENT_SIZE; } } /*********************************************************************//** Allocates a free extent for the segment: looks first in the free list of the segment, then tries to allocate from the space free list. NOTE that the extent returned still resides in the segment free list, it is not yet taken off it! @retval NULL if no page could be allocated @retval block, rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded (init_mtr == mtr, or the page was not previously freed in mtr) @retval block (not allocated or initialized) otherwise */ static xdes_t* fseg_alloc_free_extent( /*===================*/ fseg_inode_t* inode, /*!< in: segment inode */ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ mtr_t* mtr) /*!< in/out: mini-transaction */ { xdes_t* descr; ib_id_t seg_id; fil_addr_t first; ut_ad(!((page_offset(inode) - FSEG_ARR_OFFSET) % FSEG_INODE_SIZE)); ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); if (flst_get_len(inode + FSEG_FREE, mtr) > 0) { /* Segment free list is not empty, allocate from it */ first = flst_get_first(inode + FSEG_FREE, mtr); descr = xdes_lst_get_descriptor(space, zip_size, first, mtr); } else { /* Segment free list was empty, allocate from space */ descr = fsp_alloc_free_extent(space, zip_size, 0, mtr); if (descr == NULL) { return(NULL); } seg_id = mach_read_from_8(inode + FSEG_ID); xdes_set_state(descr, XDES_FSEG, mtr); mlog_write_ull(descr + XDES_ID, seg_id, mtr); flst_add_last(inode + FSEG_FREE, descr + XDES_FLST_NODE, mtr); /* Try to fill the segment free list */ fseg_fill_free_list(inode, space, zip_size, xdes_get_offset(descr) + FSP_EXTENT_SIZE, mtr); } return(descr); } /**********************************************************************//** Allocates a single free page from a segment. This function implements the intelligent allocation strategy which tries to minimize file space fragmentation. @retval NULL if no page could be allocated @retval block, rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded (init_mtr == mtr, or the page was not previously freed in mtr) @retval block (not allocated or initialized) otherwise */ static buf_block_t* fseg_alloc_free_page_low( /*=====================*/ ulint space, /*!< in: space */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ fseg_inode_t* seg_inode, /*!< in/out: segment inode */ ulint hint, /*!< in: hint of which page would be desirable */ byte direction, /*!< in: if the new page is needed because of an index page split, and records are inserted there in order, into which direction they go alphabetically: FSP_DOWN, FSP_UP, FSP_NO_DIR */ mtr_t* mtr, /*!< in/out: mini-transaction */ mtr_t* init_mtr)/*!< in/out: mtr or another mini-transaction in which the page should be initialized. If init_mtr!=mtr, but the page is already latched in mtr, do not initialize the page. */ { fsp_header_t* space_header; ulint space_size; ib_id_t seg_id; ulint used; ulint reserved; xdes_t* descr; /*!< extent of the hinted page */ ulint ret_page; /*!< the allocated page offset, FIL_NULL if could not be allocated */ xdes_t* ret_descr; /*!< the extent of the allocated page */ ibool success; ulint n; ut_ad(mtr); ut_ad((direction >= FSP_UP) && (direction <= FSP_NO_DIR)); ut_ad(mach_read_from_4(seg_inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); ut_ad(!((page_offset(seg_inode) - FSEG_ARR_OFFSET) % FSEG_INODE_SIZE)); seg_id = mach_read_from_8(seg_inode + FSEG_ID); ut_ad(seg_id); reserved = fseg_n_reserved_pages_low(seg_inode, &used, mtr); space_header = fsp_get_space_header(space, zip_size, mtr); descr = xdes_get_descriptor_with_space_hdr(space_header, space, hint, mtr); if (descr == NULL) { /* Hint outside space or too high above free limit: reset hint */ /* The file space header page is always allocated. */ hint = 0; descr = xdes_get_descriptor(space, zip_size, hint, mtr); } /* In the big if-else below we look for ret_page and ret_descr */ /*-------------------------------------------------------------*/ if ((xdes_get_state(descr, mtr) == XDES_FSEG) && mach_read_from_8(descr + XDES_ID) == seg_id && (xdes_mtr_get_bit(descr, XDES_FREE_BIT, hint % FSP_EXTENT_SIZE, mtr) == TRUE)) { take_hinted_page: /* 1. We can take the hinted page =================================*/ ret_descr = descr; ret_page = hint; /* Skip the check for extending the tablespace. If the page hint were not within the size of the tablespace, we would have got (descr == NULL) above and reset the hint. */ goto got_hinted_page; /*-----------------------------------------------------------*/ } else if (xdes_get_state(descr, mtr) == XDES_FREE && reserved - used < reserved / FSEG_FILLFACTOR && used >= FSEG_FRAG_LIMIT) { /* 2. We allocate the free extent from space and can take ========================================================= the hinted page ===============*/ ret_descr = fsp_alloc_free_extent(space, zip_size, hint, mtr); ut_a(ret_descr == descr); xdes_set_state(ret_descr, XDES_FSEG, mtr); mlog_write_ull(ret_descr + XDES_ID, seg_id, mtr); flst_add_last(seg_inode + FSEG_FREE, ret_descr + XDES_FLST_NODE, mtr); /* Try to fill the segment free list */ fseg_fill_free_list(seg_inode, space, zip_size, hint + FSP_EXTENT_SIZE, mtr); goto take_hinted_page; /*-----------------------------------------------------------*/ } else if ((direction != FSP_NO_DIR) && ((reserved - used) < reserved / FSEG_FILLFACTOR) && (used >= FSEG_FRAG_LIMIT) && (!!(ret_descr = fseg_alloc_free_extent(seg_inode, space, zip_size, mtr)))) { /* 3. We take any free extent (which was already assigned above =============================================================== in the if-condition to ret_descr) and take the lowest or ======================================================== highest page in it, depending on the direction ==============================================*/ ret_page = xdes_get_offset(ret_descr); if (direction == FSP_DOWN) { ret_page += FSP_EXTENT_SIZE - 1; } /*-----------------------------------------------------------*/ } else if ((xdes_get_state(descr, mtr) == XDES_FSEG) && mach_read_from_8(descr + XDES_ID) == seg_id && (!xdes_is_full(descr, mtr))) { /* 4. We can take the page from the same extent as the ====================================================== hinted page (and the extent already belongs to the ================================================== segment) ========*/ ret_descr = descr; ret_page = xdes_get_offset(ret_descr) + xdes_find_bit(ret_descr, XDES_FREE_BIT, TRUE, hint % FSP_EXTENT_SIZE, mtr); /*-----------------------------------------------------------*/ } else if (reserved - used > 0) { /* 5. We take any unused page from the segment ==============================================*/ fil_addr_t first; if (flst_get_len(seg_inode + FSEG_NOT_FULL, mtr) > 0) { first = flst_get_first(seg_inode + FSEG_NOT_FULL, mtr); } else if (flst_get_len(seg_inode + FSEG_FREE, mtr) > 0) { first = flst_get_first(seg_inode + FSEG_FREE, mtr); } else { ut_error; return(NULL); } ret_descr = xdes_lst_get_descriptor(space, zip_size, first, mtr); ret_page = xdes_get_offset(ret_descr) + xdes_find_bit(ret_descr, XDES_FREE_BIT, TRUE, 0, mtr); /*-----------------------------------------------------------*/ } else if (used < FSEG_FRAG_LIMIT) { /* 6. We allocate an individual page from the space ===================================================*/ buf_block_t* block = fsp_alloc_free_page( space, zip_size, hint, mtr, init_mtr); if (block != NULL) { /* Put the page in the fragment page array of the segment */ n = fseg_find_free_frag_page_slot(seg_inode, mtr); ut_a(n != ULINT_UNDEFINED); fseg_set_nth_frag_page_no( seg_inode, n, buf_block_get_page_no(block), mtr); } /* fsp_alloc_free_page() invoked fsp_init_file_page() already. */ return(block); /*-----------------------------------------------------------*/ } else { /* 7. We allocate a new extent and take its first page ======================================================*/ ret_descr = fseg_alloc_free_extent(seg_inode, space, zip_size, mtr); if (ret_descr == NULL) { ret_page = FIL_NULL; } else { ret_page = xdes_get_offset(ret_descr); } } if (ret_page == FIL_NULL) { /* Page could not be allocated */ return(NULL); } if (space != 0) { space_size = fil_space_get_size(space); if (space_size <= ret_page) { /* It must be that we are extending a single-table tablespace whose size is still < 64 pages */ if (ret_page >= FSP_EXTENT_SIZE) { fprintf(stderr, "InnoDB: Error (2): trying to extend" " a single-table tablespace %lu\n" "InnoDB: by single page(s) though" " the space size %lu. Page no %lu.\n", (ulong) space, (ulong) space_size, (ulong) ret_page); return(NULL); } success = fsp_try_extend_data_file_with_pages( space, ret_page, space_header, mtr); if (!success) { /* No disk space left */ return(NULL); } } } got_hinted_page: /* ret_descr == NULL if the block was allocated from free_frag (XDES_FREE_FRAG) */ if (ret_descr != NULL) { /* At this point we know the extent and the page offset. The extent is still in the appropriate list (FSEG_NOT_FULL or FSEG_FREE), and the page is not yet marked as used. */ ut_ad(xdes_get_descriptor(space, zip_size, ret_page, mtr) == ret_descr); ut_ad(xdes_mtr_get_bit( ret_descr, XDES_FREE_BIT, ret_page % FSP_EXTENT_SIZE, mtr)); fseg_mark_page_used(seg_inode, ret_page, ret_descr, mtr); } return(fsp_page_create( space, fsp_flags_get_zip_size( mach_read_from_4(FSP_SPACE_FLAGS + space_header)), ret_page, mtr, init_mtr)); } /**********************************************************************//** Allocates a single free page from a segment. This function implements the intelligent allocation strategy which tries to minimize file space fragmentation. @retval NULL if no page could be allocated @retval block, rw_lock_x_lock_count(&block->lock) == 1 if allocation succeeded (init_mtr == mtr, or the page was not previously freed in mtr) @retval block (not allocated or initialized) otherwise */ UNIV_INTERN buf_block_t* fseg_alloc_free_page_general( /*=========================*/ fseg_header_t* seg_header,/*!< in/out: segment header */ ulint hint, /*!< in: hint of which page would be desirable */ byte direction,/*!< in: if the new page is needed because of an index page split, and records are inserted there in order, into which direction they go alphabetically: FSP_DOWN, FSP_UP, FSP_NO_DIR */ ibool has_done_reservation, /*!< in: TRUE if the caller has already done the reservation for the page with fsp_reserve_free_extents, then there is no need to do the check for this individual page */ mtr_t* mtr, /*!< in/out: mini-transaction */ mtr_t* init_mtr)/*!< in/out: mtr or another mini-transaction in which the page should be initialized. If init_mtr!=mtr, but the page is already latched in mtr, do not initialize the page. */ { fseg_inode_t* inode; ulint space; ulint flags; ulint zip_size; prio_rw_lock_t* latch; buf_block_t* block; ulint n_reserved; space = page_get_space_id(page_align(seg_header)); latch = fil_space_get_latch(space, &flags); zip_size = fsp_flags_get_zip_size(flags); mtr_x_lock(latch, mtr); if (rw_lock_get_x_lock_count(latch) == 1) { /* This thread did not own the latch before this call: free excess pages from the insert buffer free list */ if (space == IBUF_SPACE_ID) { ibuf_free_excess_pages(); } } inode = fseg_inode_get(seg_header, space, zip_size, mtr); if (!has_done_reservation && !fsp_reserve_free_extents(&n_reserved, space, 2, FSP_NORMAL, mtr)) { return(NULL); } block = fseg_alloc_free_page_low(space, zip_size, inode, hint, direction, mtr, init_mtr); if (!has_done_reservation) { fil_space_release_free_extents(space, n_reserved); } return(block); } /**********************************************************************//** Checks that we have at least 2 frag pages free in the first extent of a single-table tablespace, and they are also physically initialized to the data file. That is we have already extended the data file so that those pages are inside the data file. If not, this function extends the tablespace with pages. @return TRUE if there were >= 3 free pages, or we were able to extend */ static ibool fsp_reserve_free_pages( /*===================*/ ulint space, /*!< in: space id, must be != 0 */ fsp_header_t* space_header, /*!< in: header of that space, x-latched */ ulint size, /*!< in: size of the tablespace in pages, must be < FSP_EXTENT_SIZE */ mtr_t* mtr) /*!< in/out: mini-transaction */ { xdes_t* descr; ulint n_used; ut_a(space != 0); ut_a(size < FSP_EXTENT_SIZE); descr = xdes_get_descriptor_with_space_hdr(space_header, space, 0, mtr); n_used = xdes_get_n_used(descr, mtr); ut_a(n_used <= size); if (size >= n_used + 2) { return(TRUE); } return(fsp_try_extend_data_file_with_pages(space, n_used + 1, space_header, mtr)); } /**********************************************************************//** Reserves free pages from a tablespace. All mini-transactions which may use several pages from the tablespace should call this function beforehand and reserve enough free extents so that they certainly will be able to do their operation, like a B-tree page split, fully. Reservations must be released with function fil_space_release_free_extents! The alloc_type below has the following meaning: FSP_NORMAL means an operation which will probably result in more space usage, like an insert in a B-tree; FSP_UNDO means allocation to undo logs: if we are deleting rows, then this allocation will in the long run result in less space usage (after a purge); FSP_CLEANING means allocation done in a physical record delete (like in a purge) or other cleaning operation which will result in less space usage in the long run. We prefer the latter two types of allocation: when space is scarce, FSP_NORMAL allocations will not succeed, but the latter two allocations will succeed, if possible. The purpose is to avoid dead end where the database is full but the user cannot free any space because these freeing operations temporarily reserve some space. Single-table tablespaces whose size is < 32 pages are a special case. In this function we would liberally reserve several 64 page extents for every page split or merge in a B-tree. But we do not want to waste disk space if the table only occupies < 32 pages. That is why we apply different rules in that special case, just ensuring that there are 3 free pages available. @return TRUE if we were able to make the reservation */ UNIV_INTERN ibool fsp_reserve_free_extents( /*=====================*/ ulint* n_reserved,/*!< out: number of extents actually reserved; if we return TRUE and the tablespace size is < 64 pages, then this can be 0, otherwise it is n_ext */ ulint space, /*!< in: space id */ ulint n_ext, /*!< in: number of extents to reserve */ ulint alloc_type,/*!< in: FSP_NORMAL, FSP_UNDO, or FSP_CLEANING */ mtr_t* mtr) /*!< in/out: mini-transaction */ { fsp_header_t* space_header; prio_rw_lock_t* latch; ulint n_free_list_ext; ulint free_limit; ulint size; ulint flags; ulint zip_size; ulint n_free; ulint n_free_up; ulint reserve; ibool success; ulint n_pages_added; size_t total_reserved = 0; ulint rounds = 0; ut_ad(mtr); *n_reserved = n_ext; latch = fil_space_get_latch(space, &flags); zip_size = fsp_flags_get_zip_size(flags); mtr_x_lock(latch, mtr); space_header = fsp_get_space_header(space, zip_size, mtr); try_again: size = mtr_read_ulint(space_header + FSP_SIZE, MLOG_4BYTES, mtr); if (size < FSP_EXTENT_SIZE / 2) { /* Use different rules for small single-table tablespaces */ *n_reserved = 0; return(fsp_reserve_free_pages(space, space_header, size, mtr)); } n_free_list_ext = flst_get_len(space_header + FSP_FREE, mtr); free_limit = mtr_read_ulint(space_header + FSP_FREE_LIMIT, MLOG_4BYTES, mtr); /* Below we play safe when counting free extents above the free limit: some of them will contain extent descriptor pages, and therefore will not be free extents */ n_free_up = (size - free_limit) / FSP_EXTENT_SIZE; if (n_free_up > 0) { n_free_up--; if (!zip_size) { n_free_up -= n_free_up / (UNIV_PAGE_SIZE / FSP_EXTENT_SIZE); } else { n_free_up -= n_free_up / (zip_size / FSP_EXTENT_SIZE); } } n_free = n_free_list_ext + n_free_up; if (alloc_type == FSP_NORMAL) { /* We reserve 1 extent + 0.5 % of the space size to undo logs and 1 extent + 0.5 % to cleaning operations; NOTE: this source code is duplicated in the function below! */ reserve = 2 + ((size / FSP_EXTENT_SIZE) * 2) / 200; if (n_free <= reserve + n_ext) { goto try_to_extend; } } else if (alloc_type == FSP_UNDO) { /* We reserve 0.5 % of the space size to cleaning operations */ reserve = 1 + ((size / FSP_EXTENT_SIZE) * 1) / 200; if (n_free <= reserve + n_ext) { goto try_to_extend; } } else { ut_a(alloc_type == FSP_CLEANING); } success = fil_space_reserve_free_extents(space, n_free, n_ext); *n_reserved = n_ext; if (success) { return(TRUE); } try_to_extend: success = fsp_try_extend_data_file(&n_pages_added, space, space_header, mtr); if (success && n_pages_added > 0) { rounds++; total_reserved += n_pages_added; if (rounds > 50) { ib_logf(IB_LOG_LEVEL_INFO, "Space id %lu trying to reserve %lu extents actually reserved %lu " " reserve %lu free %lu size %lu rounds %lu total_reserved %llu", space, n_ext, n_pages_added, reserve, n_free, size, rounds, (ullint) total_reserved); } goto try_again; } return(FALSE); } /**********************************************************************//** This function should be used to get information on how much we still will be able to insert new data to the database without running out the tablespace. Only free extents are taken into account and we also subtract the safety margin required by the above function fsp_reserve_free_extents. @return available space in kB */ UNIV_INTERN ullint fsp_get_available_space_in_free_extents( /*====================================*/ ulint space) /*!< in: space id */ { fsp_header_t* space_header; ulint n_free_list_ext; ulint free_limit; ulint size; ulint flags; ulint zip_size; ulint n_free; ulint n_free_up; ulint reserve; prio_rw_lock_t* latch; mtr_t mtr; /* The convoluted mutex acquire is to overcome latching order issues: The problem is that the fil_mutex is at a lower level than the tablespace latch and the buffer pool mutexes. We have to first prevent any operations on the file system by acquiring the dictionary mutex. Then acquire the tablespace latch to obey the latching order and then release the dictionary mutex. That way we ensure that the tablespace instance can't be freed while we are examining its contents (see fil_space_free()). However, there is one further complication, we release the fil_mutex when we need to invalidate the the pages in the buffer pool and we reacquire the fil_mutex when deleting and freeing the tablespace instance in fil0fil.cc. Here we need to account for that situation too. */ mutex_enter(&dict_sys->mutex); /* At this stage there is no guarantee that the tablespace even exists in the cache. */ if (fil_tablespace_deleted_or_being_deleted_in_mem(space, -1)) { mutex_exit(&dict_sys->mutex); return(ULLINT_UNDEFINED); } mtr_start(&mtr); latch = fil_space_get_latch(space, &flags); /* This should ensure that the tablespace instance can't be freed by another thread. However, the tablespace pages can still be freed from the buffer pool. We need to check for that again. */ zip_size = fsp_flags_get_zip_size(flags); mtr_x_lock(latch, &mtr); mutex_exit(&dict_sys->mutex); /* At this point it is possible for the tablespace to be deleted and its pages removed from the buffer pool. We need to check for that situation. However, the tablespace instance can't be deleted because our latching above should ensure that. */ if (fil_tablespace_is_being_deleted(space)) { mtr_commit(&mtr); return(ULLINT_UNDEFINED); } /* From here on even if the user has dropped the tablespace, the pages _must_ still exist in the buffer pool and the tablespace instance _must_ be in the file system hash table. */ space_header = fsp_get_space_header(space, zip_size, &mtr); size = mtr_read_ulint(space_header + FSP_SIZE, MLOG_4BYTES, &mtr); n_free_list_ext = flst_get_len(space_header + FSP_FREE, &mtr); free_limit = mtr_read_ulint(space_header + FSP_FREE_LIMIT, MLOG_4BYTES, &mtr); mtr_commit(&mtr); if (size < FSP_EXTENT_SIZE) { ut_a(space != 0); /* This must be a single-table tablespace */ return(0); /* TODO: count free frag pages and return a value based on that */ } /* Below we play safe when counting free extents above the free limit: some of them will contain extent descriptor pages, and therefore will not be free extents */ n_free_up = (size - free_limit) / FSP_EXTENT_SIZE; if (n_free_up > 0) { n_free_up--; if (!zip_size) { n_free_up -= n_free_up / (UNIV_PAGE_SIZE / FSP_EXTENT_SIZE); } else { n_free_up -= n_free_up / (zip_size / FSP_EXTENT_SIZE); } } n_free = n_free_list_ext + n_free_up; /* We reserve 1 extent + 0.5 % of the space size to undo logs and 1 extent + 0.5 % to cleaning operations; NOTE: this source code is duplicated in the function above! */ reserve = 2 + ((size / FSP_EXTENT_SIZE) * 2) / 200; if (reserve > n_free) { return(0); } if (!zip_size) { return((ullint) (n_free - reserve) * FSP_EXTENT_SIZE * (UNIV_PAGE_SIZE / 1024)); } else { return((ullint) (n_free - reserve) * FSP_EXTENT_SIZE * (zip_size / 1024)); } } /********************************************************************//** Marks a page used. The page must reside within the extents of the given segment. */ static MY_ATTRIBUTE((nonnull)) void fseg_mark_page_used( /*================*/ fseg_inode_t* seg_inode,/*!< in: segment inode */ ulint page, /*!< in: page offset */ xdes_t* descr, /*!< in: extent descriptor */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint not_full_n_used; ut_ad(!((page_offset(seg_inode) - FSEG_ARR_OFFSET) % FSEG_INODE_SIZE)); ut_ad(mach_read_from_4(seg_inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); ut_ad(mtr_read_ulint(seg_inode + FSEG_ID, MLOG_4BYTES, mtr) == mtr_read_ulint(descr + XDES_ID, MLOG_4BYTES, mtr)); if (xdes_is_free(descr, mtr)) { /* We move the extent from the free list to the NOT_FULL list */ flst_remove(seg_inode + FSEG_FREE, descr + XDES_FLST_NODE, mtr); flst_add_last(seg_inode + FSEG_NOT_FULL, descr + XDES_FLST_NODE, mtr); } ut_ad(xdes_mtr_get_bit( descr, XDES_FREE_BIT, page % FSP_EXTENT_SIZE, mtr)); /* We mark the page as used */ xdes_set_bit(descr, XDES_FREE_BIT, page % FSP_EXTENT_SIZE, FALSE, mtr); not_full_n_used = mtr_read_ulint(seg_inode + FSEG_NOT_FULL_N_USED, MLOG_4BYTES, mtr); not_full_n_used++; mlog_write_ulint(seg_inode + FSEG_NOT_FULL_N_USED, not_full_n_used, MLOG_4BYTES, mtr); if (xdes_is_full(descr, mtr)) { /* We move the extent from the NOT_FULL list to the FULL list */ flst_remove(seg_inode + FSEG_NOT_FULL, descr + XDES_FLST_NODE, mtr); flst_add_last(seg_inode + FSEG_FULL, descr + XDES_FLST_NODE, mtr); mlog_write_ulint(seg_inode + FSEG_NOT_FULL_N_USED, not_full_n_used - FSP_EXTENT_SIZE, MLOG_4BYTES, mtr); } } /**********************************************************************//** Frees a single page of a segment. */ static void fseg_free_page_low( /*===============*/ fseg_inode_t* seg_inode, /*!< in: segment inode */ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint page, /*!< in: page offset */ mtr_t* mtr) /*!< in/out: mini-transaction */ { xdes_t* descr; ulint not_full_n_used; ulint state; ib_id_t descr_id; ib_id_t seg_id; ulint i; ut_ad(seg_inode != NULL); ut_ad(mtr != NULL); ut_ad(mach_read_from_4(seg_inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); ut_ad(!((page_offset(seg_inode) - FSEG_ARR_OFFSET) % FSEG_INODE_SIZE)); /* Drop search system page hash index if the page is found in the pool and is hashed */ btr_search_drop_page_hash_when_freed(space, zip_size, page); descr = xdes_get_descriptor(space, zip_size, page, mtr); SRV_CORRUPT_TABLE_CHECK(descr, { /* The page may be corrupt. pass it. */ return; }); if (xdes_mtr_get_bit(descr, XDES_FREE_BIT, page % FSP_EXTENT_SIZE, mtr)) { fputs("InnoDB: Dump of the tablespace extent descriptor: ", stderr); ut_print_buf(stderr, descr, 40); fprintf(stderr, "\n" "InnoDB: Serious error! InnoDB is trying to" " free page %lu\n" "InnoDB: though it is already marked as free" " in the tablespace!\n" "InnoDB: The tablespace free space info is corrupt.\n" "InnoDB: You may need to dump your" " InnoDB tables and recreate the whole\n" "InnoDB: database!\n", (ulong) page); crash: fputs("InnoDB: Please refer to\n" "InnoDB: " REFMAN "forcing-innodb-recovery.html\n" "InnoDB: about forcing recovery.\n", stderr); ut_error; } state = xdes_get_state(descr, mtr); if (state != XDES_FSEG) { /* The page is in the fragment pages of the segment */ for (i = 0;; i++) { if (fseg_get_nth_frag_page_no(seg_inode, i, mtr) == page) { fseg_set_nth_frag_page_no(seg_inode, i, FIL_NULL, mtr); break; } } fsp_free_page(space, zip_size, page, mtr); return; } /* If we get here, the page is in some extent of the segment */ descr_id = mach_read_from_8(descr + XDES_ID); seg_id = mach_read_from_8(seg_inode + FSEG_ID); #if 0 fprintf(stderr, "InnoDB: InnoDB is freeing space %lu page %lu,\n" "InnoDB: which belongs to descr seg %llu\n" "InnoDB: segment %llu.\n", (ulong) space, (ulong) page, (ullint) descr_id, (ullint) seg_id); #endif /* 0 */ if (UNIV_UNLIKELY(descr_id != seg_id)) { fputs("InnoDB: Dump of the tablespace extent descriptor: ", stderr); ut_print_buf(stderr, descr, 40); fputs("\nInnoDB: Dump of the segment inode: ", stderr); ut_print_buf(stderr, seg_inode, 40); putc('\n', stderr); fprintf(stderr, "InnoDB: Serious error: InnoDB is trying to" " free space %lu page %lu,\n" "InnoDB: which does not belong to" " segment %llu but belongs\n" "InnoDB: to segment %llu.\n", (ulong) space, (ulong) page, (ullint) descr_id, (ullint) seg_id); goto crash; } not_full_n_used = mtr_read_ulint(seg_inode + FSEG_NOT_FULL_N_USED, MLOG_4BYTES, mtr); if (xdes_is_full(descr, mtr)) { /* The fragment is full: move it to another list */ flst_remove(seg_inode + FSEG_FULL, descr + XDES_FLST_NODE, mtr); flst_add_last(seg_inode + FSEG_NOT_FULL, descr + XDES_FLST_NODE, mtr); mlog_write_ulint(seg_inode + FSEG_NOT_FULL_N_USED, not_full_n_used + FSP_EXTENT_SIZE - 1, MLOG_4BYTES, mtr); } else { ut_a(not_full_n_used > 0); mlog_write_ulint(seg_inode + FSEG_NOT_FULL_N_USED, not_full_n_used - 1, MLOG_4BYTES, mtr); } xdes_set_bit(descr, XDES_FREE_BIT, page % FSP_EXTENT_SIZE, TRUE, mtr); xdes_set_bit(descr, XDES_CLEAN_BIT, page % FSP_EXTENT_SIZE, TRUE, mtr); if (xdes_is_free(descr, mtr)) { /* The extent has become free: free it to space */ flst_remove(seg_inode + FSEG_NOT_FULL, descr + XDES_FLST_NODE, mtr); fsp_free_extent(space, zip_size, page, mtr); } mtr->n_freed_pages++; } /**********************************************************************//** Frees a single page of a segment. */ UNIV_INTERN void fseg_free_page( /*===========*/ fseg_header_t* seg_header, /*!< in: segment header */ ulint space, /*!< in: space id */ ulint page, /*!< in: page offset */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint flags; ulint zip_size; fseg_inode_t* seg_inode; prio_rw_lock_t* latch; latch = fil_space_get_latch(space, &flags); zip_size = fsp_flags_get_zip_size(flags); mtr_x_lock(latch, mtr); seg_inode = fseg_inode_get(seg_header, space, zip_size, mtr); fseg_free_page_low(seg_inode, space, zip_size, page, mtr); #if defined UNIV_DEBUG_FILE_ACCESSES || defined UNIV_DEBUG buf_page_set_file_page_was_freed(space, page); #endif /* UNIV_DEBUG_FILE_ACCESSES || UNIV_DEBUG */ } /**********************************************************************//** Checks if a single page of a segment is free. @return true if free */ UNIV_INTERN bool fseg_page_is_free( /*==============*/ fseg_header_t* seg_header, /*!< in: segment header */ ulint space, /*!< in: space id */ ulint page) /*!< in: page offset */ { mtr_t mtr; ibool is_free; ulint flags; prio_rw_lock_t* latch; xdes_t* descr; ulint zip_size; fseg_inode_t* seg_inode; latch = fil_space_get_latch(space, &flags); zip_size = dict_tf_get_zip_size(flags); mtr_start(&mtr); mtr_x_lock(latch, &mtr); seg_inode = fseg_inode_get(seg_header, space, zip_size, &mtr); ut_a(seg_inode); ut_ad(mach_read_from_4(seg_inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); ut_ad(!((page_offset(seg_inode) - FSEG_ARR_OFFSET) % FSEG_INODE_SIZE)); descr = xdes_get_descriptor(space, zip_size, page, &mtr); ut_a(descr); is_free = xdes_mtr_get_bit( descr, XDES_FREE_BIT, page % FSP_EXTENT_SIZE, &mtr); mtr_commit(&mtr); return(is_free); } /**********************************************************************//** Frees an extent of a segment to the space free list. */ static void fseg_free_extent( /*=============*/ fseg_inode_t* seg_inode, /*!< in: segment inode */ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ ulint page, /*!< in: a page in the extent */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint first_page_in_extent; xdes_t* descr; ulint not_full_n_used; ulint descr_n_used; ulint i; ut_ad(seg_inode != NULL); ut_ad(mtr != NULL); descr = xdes_get_descriptor(space, zip_size, page, mtr); ut_a(xdes_get_state(descr, mtr) == XDES_FSEG); ut_a(!memcmp(descr + XDES_ID, seg_inode + FSEG_ID, 8)); ut_ad(mach_read_from_4(seg_inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); first_page_in_extent = page - (page % FSP_EXTENT_SIZE); for (i = 0; i < FSP_EXTENT_SIZE; i++) { if (!xdes_mtr_get_bit(descr, XDES_FREE_BIT, i, mtr)) { /* Drop search system page hash index if the page is found in the pool and is hashed */ btr_search_drop_page_hash_when_freed( space, zip_size, first_page_in_extent + i); } } if (xdes_is_full(descr, mtr)) { flst_remove(seg_inode + FSEG_FULL, descr + XDES_FLST_NODE, mtr); } else if (xdes_is_free(descr, mtr)) { flst_remove(seg_inode + FSEG_FREE, descr + XDES_FLST_NODE, mtr); } else { flst_remove(seg_inode + FSEG_NOT_FULL, descr + XDES_FLST_NODE, mtr); not_full_n_used = mtr_read_ulint( seg_inode + FSEG_NOT_FULL_N_USED, MLOG_4BYTES, mtr); descr_n_used = xdes_get_n_used(descr, mtr); ut_a(not_full_n_used >= descr_n_used); mlog_write_ulint(seg_inode + FSEG_NOT_FULL_N_USED, not_full_n_used - descr_n_used, MLOG_4BYTES, mtr); } fsp_free_extent(space, zip_size, page, mtr); #if defined UNIV_DEBUG_FILE_ACCESSES || defined UNIV_DEBUG for (i = 0; i < FSP_EXTENT_SIZE; i++) { buf_page_set_file_page_was_freed(space, first_page_in_extent + i); } #endif /* UNIV_DEBUG_FILE_ACCESSES || UNIV_DEBUG */ } /**********************************************************************//** Frees part of a segment. This function can be used to free a segment by repeatedly calling this function in different mini-transactions. Doing the freeing in a single mini-transaction might result in too big a mini-transaction. @return TRUE if freeing completed */ UNIV_INTERN ibool fseg_free_step( /*===========*/ fseg_header_t* header, /*!< in, own: segment header; NOTE: if the header resides on the first page of the frag list of the segment, this pointer becomes obsolete after the last freeing step */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint n; ulint page; xdes_t* descr; fseg_inode_t* inode; ulint space; ulint flags; ulint zip_size; ulint header_page; prio_rw_lock_t* latch; space = page_get_space_id(page_align(header)); header_page = page_get_page_no(page_align(header)); latch = fil_space_get_latch(space, &flags); zip_size = fsp_flags_get_zip_size(flags); mtr_x_lock(latch, mtr); descr = xdes_get_descriptor(space, zip_size, header_page, mtr); SRV_CORRUPT_TABLE_CHECK(descr, { /* The page may be corrupt. pass it. */ return(TRUE); }); /* Check that the header resides on a page which has not been freed yet */ ut_a(xdes_mtr_get_bit(descr, XDES_FREE_BIT, header_page % FSP_EXTENT_SIZE, mtr) == FALSE); inode = fseg_inode_try_get(header, space, zip_size, mtr); if (UNIV_UNLIKELY(inode == NULL)) { fprintf(stderr, "double free of inode from %u:%u\n", (unsigned) space, (unsigned) header_page); return(TRUE); } descr = fseg_get_first_extent(inode, space, zip_size, mtr); if (descr != NULL) { /* Free the extent held by the segment */ page = xdes_get_offset(descr); fseg_free_extent(inode, space, zip_size, page, mtr); return(FALSE); } /* Free a frag page */ n = fseg_find_last_used_frag_page_slot(inode, mtr); if (n == ULINT_UNDEFINED) { /* Freeing completed: free the segment inode */ fsp_free_seg_inode(space, zip_size, inode, mtr); return(TRUE); } fseg_free_page_low(inode, space, zip_size, fseg_get_nth_frag_page_no(inode, n, mtr), mtr); n = fseg_find_last_used_frag_page_slot(inode, mtr); if (n == ULINT_UNDEFINED) { /* Freeing completed: free the segment inode */ fsp_free_seg_inode(space, zip_size, inode, mtr); return(TRUE); } return(FALSE); } /**********************************************************************//** Frees part of a segment. Differs from fseg_free_step because this function leaves the header page unfreed. @return TRUE if freeing completed, except the header page */ UNIV_INTERN ibool fseg_free_step_not_header( /*======================*/ fseg_header_t* header, /*!< in: segment header which must reside on the first fragment page of the segment */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint n; ulint page; xdes_t* descr; fseg_inode_t* inode; ulint space; ulint flags; ulint zip_size; ulint page_no; prio_rw_lock_t* latch; space = page_get_space_id(page_align(header)); latch = fil_space_get_latch(space, &flags); zip_size = fsp_flags_get_zip_size(flags); mtr_x_lock(latch, mtr); inode = fseg_inode_get(header, space, zip_size, mtr); SRV_CORRUPT_TABLE_CHECK(inode, { /* ignore the corruption */ return(TRUE); }); descr = fseg_get_first_extent(inode, space, zip_size, mtr); if (descr != NULL) { /* Free the extent held by the segment */ page = xdes_get_offset(descr); fseg_free_extent(inode, space, zip_size, page, mtr); return(FALSE); } /* Free a frag page */ n = fseg_find_last_used_frag_page_slot(inode, mtr); if (n == ULINT_UNDEFINED) { ut_error; } page_no = fseg_get_nth_frag_page_no(inode, n, mtr); if (page_no == page_get_page_no(page_align(header))) { return(TRUE); } fseg_free_page_low(inode, space, zip_size, page_no, mtr); return(FALSE); } /**********************************************************************//** Returns the first extent descriptor for a segment. We think of the extent lists of the segment catenated in the order FSEG_FULL -> FSEG_NOT_FULL -> FSEG_FREE. @return the first extent descriptor, or NULL if none */ static xdes_t* fseg_get_first_extent( /*==================*/ fseg_inode_t* inode, /*!< in: segment inode */ ulint space, /*!< in: space id */ ulint zip_size,/*!< in: compressed page size in bytes or 0 for uncompressed pages */ mtr_t* mtr) /*!< in/out: mini-transaction */ { fil_addr_t first; xdes_t* descr; ut_ad(inode && mtr); ut_ad(space == page_get_space_id(page_align(inode))); ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); first = fil_addr_null; if (flst_get_len(inode + FSEG_FULL, mtr) > 0) { first = flst_get_first(inode + FSEG_FULL, mtr); } else if (flst_get_len(inode + FSEG_NOT_FULL, mtr) > 0) { first = flst_get_first(inode + FSEG_NOT_FULL, mtr); } else if (flst_get_len(inode + FSEG_FREE, mtr) > 0) { first = flst_get_first(inode + FSEG_FREE, mtr); } if (first.page == FIL_NULL) { return(NULL); } descr = xdes_lst_get_descriptor(space, zip_size, first, mtr); return(descr); } /*******************************************************************//** Validates a segment. @return TRUE if ok */ static ibool fseg_validate_low( /*==============*/ fseg_inode_t* inode, /*!< in: segment inode */ mtr_t* mtr2) /*!< in/out: mini-transaction */ { ulint space; ib_id_t seg_id; mtr_t mtr; xdes_t* descr; fil_addr_t node_addr; ulint n_used = 0; ulint n_used2 = 0; ut_ad(mtr_memo_contains_page(mtr2, inode, MTR_MEMO_PAGE_X_FIX)); ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); space = page_get_space_id(page_align(inode)); seg_id = mach_read_from_8(inode + FSEG_ID); n_used = mtr_read_ulint(inode + FSEG_NOT_FULL_N_USED, MLOG_4BYTES, mtr2); flst_validate(inode + FSEG_FREE, mtr2); flst_validate(inode + FSEG_NOT_FULL, mtr2); flst_validate(inode + FSEG_FULL, mtr2); /* Validate FSEG_FREE list */ node_addr = flst_get_first(inode + FSEG_FREE, mtr2); while (!fil_addr_is_null(node_addr)) { ulint flags; ulint zip_size; mtr_start(&mtr); mtr_x_lock(fil_space_get_latch(space, &flags), &mtr); zip_size = fsp_flags_get_zip_size(flags); descr = xdes_lst_get_descriptor(space, zip_size, node_addr, &mtr); ut_a(xdes_get_n_used(descr, &mtr) == 0); ut_a(xdes_get_state(descr, &mtr) == XDES_FSEG); ut_a(mach_read_from_8(descr + XDES_ID) == seg_id); node_addr = flst_get_next_addr(descr + XDES_FLST_NODE, &mtr); mtr_commit(&mtr); } /* Validate FSEG_NOT_FULL list */ node_addr = flst_get_first(inode + FSEG_NOT_FULL, mtr2); while (!fil_addr_is_null(node_addr)) { ulint flags; ulint zip_size; mtr_start(&mtr); mtr_x_lock(fil_space_get_latch(space, &flags), &mtr); zip_size = fsp_flags_get_zip_size(flags); descr = xdes_lst_get_descriptor(space, zip_size, node_addr, &mtr); ut_a(xdes_get_n_used(descr, &mtr) > 0); ut_a(xdes_get_n_used(descr, &mtr) < FSP_EXTENT_SIZE); ut_a(xdes_get_state(descr, &mtr) == XDES_FSEG); ut_a(mach_read_from_8(descr + XDES_ID) == seg_id); n_used2 += xdes_get_n_used(descr, &mtr); node_addr = flst_get_next_addr(descr + XDES_FLST_NODE, &mtr); mtr_commit(&mtr); } /* Validate FSEG_FULL list */ node_addr = flst_get_first(inode + FSEG_FULL, mtr2); while (!fil_addr_is_null(node_addr)) { ulint flags; ulint zip_size; mtr_start(&mtr); mtr_x_lock(fil_space_get_latch(space, &flags), &mtr); zip_size = fsp_flags_get_zip_size(flags); descr = xdes_lst_get_descriptor(space, zip_size, node_addr, &mtr); ut_a(xdes_get_n_used(descr, &mtr) == FSP_EXTENT_SIZE); ut_a(xdes_get_state(descr, &mtr) == XDES_FSEG); ut_a(mach_read_from_8(descr + XDES_ID) == seg_id); node_addr = flst_get_next_addr(descr + XDES_FLST_NODE, &mtr); mtr_commit(&mtr); } ut_a(n_used == n_used2); return(TRUE); } #ifdef UNIV_DEBUG /*******************************************************************//** Validates a segment. @return TRUE if ok */ UNIV_INTERN ibool fseg_validate( /*==========*/ fseg_header_t* header, /*!< in: segment header */ mtr_t* mtr) /*!< in/out: mini-transaction */ { fseg_inode_t* inode; ibool ret; ulint space; ulint flags; ulint zip_size; space = page_get_space_id(page_align(header)); mtr_x_lock(fil_space_get_latch(space, &flags), mtr); zip_size = fsp_flags_get_zip_size(flags); inode = fseg_inode_get(header, space, zip_size, mtr); ret = fseg_validate_low(inode, mtr); return(ret); } #endif /* UNIV_DEBUG */ /*******************************************************************//** Writes info of a segment. */ static void fseg_print_low( /*===========*/ fseg_inode_t* inode, /*!< in: segment inode */ mtr_t* mtr) /*!< in/out: mini-transaction */ { ulint space; ulint n_used; ulint n_frag; ulint n_free; ulint n_not_full; ulint n_full; ulint reserved; ulint used; ulint page_no; ib_id_t seg_id; ut_ad(mtr_memo_contains_page(mtr, inode, MTR_MEMO_PAGE_X_FIX)); space = page_get_space_id(page_align(inode)); page_no = page_get_page_no(page_align(inode)); reserved = fseg_n_reserved_pages_low(inode, &used, mtr); seg_id = mach_read_from_8(inode + FSEG_ID); n_used = mtr_read_ulint(inode + FSEG_NOT_FULL_N_USED, MLOG_4BYTES, mtr); n_frag = fseg_get_n_frag_pages(inode, mtr); n_free = flst_get_len(inode + FSEG_FREE, mtr); n_not_full = flst_get_len(inode + FSEG_NOT_FULL, mtr); n_full = flst_get_len(inode + FSEG_FULL, mtr); fprintf(stderr, "SEGMENT id %llu space %lu; page %lu;" " res %lu used %lu; full ext %lu\n" "fragm pages %lu; free extents %lu;" " not full extents %lu: pages %lu\n", (ullint) seg_id, (ulong) space, (ulong) page_no, (ulong) reserved, (ulong) used, (ulong) n_full, (ulong) n_frag, (ulong) n_free, (ulong) n_not_full, (ulong) n_used); ut_ad(mach_read_from_4(inode + FSEG_MAGIC_N) == FSEG_MAGIC_N_VALUE); } #ifdef UNIV_BTR_PRINT /*******************************************************************//** Writes info of a segment. */ UNIV_INTERN void fseg_print( /*=======*/ fseg_header_t* header, /*!< in: segment header */ mtr_t* mtr) /*!< in/out: mini-transaction */ { fseg_inode_t* inode; ulint space; ulint flags; ulint zip_size; space = page_get_space_id(page_align(header)); mtr_x_lock(fil_space_get_latch(space, &flags), mtr); zip_size = fsp_flags_get_zip_size(flags); inode = fseg_inode_get(header, space, zip_size, mtr); fseg_print_low(inode, mtr); } #endif /* UNIV_BTR_PRINT */ /*******************************************************************//** Validates the file space system and its segments. @return TRUE if ok */ UNIV_INTERN ibool fsp_validate( /*=========*/ ulint space) /*!< in: space id */ { fsp_header_t* header; fseg_inode_t* seg_inode; page_t* seg_inode_page; prio_rw_lock_t* latch; ulint size; ulint flags; ulint zip_size; ulint free_limit; ulint frag_n_used; mtr_t mtr; mtr_t mtr2; xdes_t* descr; fil_addr_t node_addr; fil_addr_t next_node_addr; ulint descr_count = 0; ulint n_used = 0; ulint n_used2 = 0; ulint n_full_frag_pages; ulint n; ulint seg_inode_len_free; ulint seg_inode_len_full; latch = fil_space_get_latch(space, &flags); zip_size = fsp_flags_get_zip_size(flags); ut_a(ut_is_2pow(zip_size)); ut_a(zip_size <= UNIV_ZIP_SIZE_MAX); ut_a(!zip_size || zip_size >= UNIV_ZIP_SIZE_MIN); /* Start first a mini-transaction mtr2 to lock out all other threads from the fsp system */ mtr_start(&mtr2); mtr_x_lock(latch, &mtr2); mtr_start(&mtr); mtr_x_lock(latch, &mtr); header = fsp_get_space_header(space, zip_size, &mtr); size = mtr_read_ulint(header + FSP_SIZE, MLOG_4BYTES, &mtr); free_limit = mtr_read_ulint(header + FSP_FREE_LIMIT, MLOG_4BYTES, &mtr); frag_n_used = mtr_read_ulint(header + FSP_FRAG_N_USED, MLOG_4BYTES, &mtr); n_full_frag_pages = FSP_EXTENT_SIZE * flst_get_len(header + FSP_FULL_FRAG, &mtr); if (UNIV_UNLIKELY(free_limit > size)) { ut_a(space != 0); ut_a(size < FSP_EXTENT_SIZE); } flst_validate(header + FSP_FREE, &mtr); flst_validate(header + FSP_FREE_FRAG, &mtr); flst_validate(header + FSP_FULL_FRAG, &mtr); mtr_commit(&mtr); /* Validate FSP_FREE list */ mtr_start(&mtr); mtr_x_lock(latch, &mtr); header = fsp_get_space_header(space, zip_size, &mtr); node_addr = flst_get_first(header + FSP_FREE, &mtr); mtr_commit(&mtr); while (!fil_addr_is_null(node_addr)) { mtr_start(&mtr); mtr_x_lock(latch, &mtr); descr_count++; descr = xdes_lst_get_descriptor(space, zip_size, node_addr, &mtr); ut_a(xdes_get_n_used(descr, &mtr) == 0); ut_a(xdes_get_state(descr, &mtr) == XDES_FREE); node_addr = flst_get_next_addr(descr + XDES_FLST_NODE, &mtr); mtr_commit(&mtr); } /* Validate FSP_FREE_FRAG list */ mtr_start(&mtr); mtr_x_lock(latch, &mtr); header = fsp_get_space_header(space, zip_size, &mtr); node_addr = flst_get_first(header + FSP_FREE_FRAG, &mtr); mtr_commit(&mtr); while (!fil_addr_is_null(node_addr)) { mtr_start(&mtr); mtr_x_lock(latch, &mtr); descr_count++; descr = xdes_lst_get_descriptor(space, zip_size, node_addr, &mtr); ut_a(xdes_get_n_used(descr, &mtr) > 0); ut_a(xdes_get_n_used(descr, &mtr) < FSP_EXTENT_SIZE); ut_a(xdes_get_state(descr, &mtr) == XDES_FREE_FRAG); n_used += xdes_get_n_used(descr, &mtr); node_addr = flst_get_next_addr(descr + XDES_FLST_NODE, &mtr); mtr_commit(&mtr); } /* Validate FSP_FULL_FRAG list */ mtr_start(&mtr); mtr_x_lock(latch, &mtr); header = fsp_get_space_header(space, zip_size, &mtr); node_addr = flst_get_first(header + FSP_FULL_FRAG, &mtr); mtr_commit(&mtr); while (!fil_addr_is_null(node_addr)) { mtr_start(&mtr); mtr_x_lock(latch, &mtr); descr_count++; descr = xdes_lst_get_descriptor(space, zip_size, node_addr, &mtr); ut_a(xdes_get_n_used(descr, &mtr) == FSP_EXTENT_SIZE); ut_a(xdes_get_state(descr, &mtr) == XDES_FULL_FRAG); node_addr = flst_get_next_addr(descr + XDES_FLST_NODE, &mtr); mtr_commit(&mtr); } /* Validate segments */ mtr_start(&mtr); mtr_x_lock(latch, &mtr); header = fsp_get_space_header(space, zip_size, &mtr); node_addr = flst_get_first(header + FSP_SEG_INODES_FULL, &mtr); seg_inode_len_full = flst_get_len(header + FSP_SEG_INODES_FULL, &mtr); mtr_commit(&mtr); while (!fil_addr_is_null(node_addr)) { n = 0; do { mtr_start(&mtr); mtr_x_lock(latch, &mtr); seg_inode_page = fut_get_ptr( space, zip_size, node_addr, RW_X_LATCH, &mtr) - FSEG_INODE_PAGE_NODE; seg_inode = fsp_seg_inode_page_get_nth_inode( seg_inode_page, n, zip_size, &mtr); ut_a(mach_read_from_8(seg_inode + FSEG_ID) != 0); fseg_validate_low(seg_inode, &mtr); descr_count += flst_get_len(seg_inode + FSEG_FREE, &mtr); descr_count += flst_get_len(seg_inode + FSEG_FULL, &mtr); descr_count += flst_get_len(seg_inode + FSEG_NOT_FULL, &mtr); n_used2 += fseg_get_n_frag_pages(seg_inode, &mtr); next_node_addr = flst_get_next_addr( seg_inode_page + FSEG_INODE_PAGE_NODE, &mtr); mtr_commit(&mtr); } while (++n < FSP_SEG_INODES_PER_PAGE(zip_size)); node_addr = next_node_addr; } mtr_start(&mtr); mtr_x_lock(latch, &mtr); header = fsp_get_space_header(space, zip_size, &mtr); node_addr = flst_get_first(header + FSP_SEG_INODES_FREE, &mtr); seg_inode_len_free = flst_get_len(header + FSP_SEG_INODES_FREE, &mtr); mtr_commit(&mtr); while (!fil_addr_is_null(node_addr)) { n = 0; do { mtr_start(&mtr); mtr_x_lock(latch, &mtr); seg_inode_page = fut_get_ptr( space, zip_size, node_addr, RW_X_LATCH, &mtr) - FSEG_INODE_PAGE_NODE; seg_inode = fsp_seg_inode_page_get_nth_inode( seg_inode_page, n, zip_size, &mtr); if (mach_read_from_8(seg_inode + FSEG_ID)) { fseg_validate_low(seg_inode, &mtr); descr_count += flst_get_len( seg_inode + FSEG_FREE, &mtr); descr_count += flst_get_len( seg_inode + FSEG_FULL, &mtr); descr_count += flst_get_len( seg_inode + FSEG_NOT_FULL, &mtr); n_used2 += fseg_get_n_frag_pages( seg_inode, &mtr); } next_node_addr = flst_get_next_addr( seg_inode_page + FSEG_INODE_PAGE_NODE, &mtr); mtr_commit(&mtr); } while (++n < FSP_SEG_INODES_PER_PAGE(zip_size)); node_addr = next_node_addr; } ut_a(descr_count * FSP_EXTENT_SIZE == free_limit); if (!zip_size) { ut_a(n_used + n_full_frag_pages == n_used2 + 2 * ((free_limit + (UNIV_PAGE_SIZE - 1)) / UNIV_PAGE_SIZE) + seg_inode_len_full + seg_inode_len_free); } else { ut_a(n_used + n_full_frag_pages == n_used2 + 2 * ((free_limit + (zip_size - 1)) / zip_size) + seg_inode_len_full + seg_inode_len_free); } ut_a(frag_n_used == n_used); mtr_commit(&mtr2); return(TRUE); } /*******************************************************************//** Prints info of a file space. */ UNIV_INTERN void fsp_print( /*======*/ ulint space) /*!< in: space id */ { fsp_header_t* header; fseg_inode_t* seg_inode; page_t* seg_inode_page; prio_rw_lock_t* latch; ulint flags; ulint zip_size; ulint size; ulint free_limit; ulint frag_n_used; fil_addr_t node_addr; fil_addr_t next_node_addr; ulint n_free; ulint n_free_frag; ulint n_full_frag; ib_id_t seg_id; ulint n; ulint n_segs = 0; mtr_t mtr; mtr_t mtr2; latch = fil_space_get_latch(space, &flags); zip_size = fsp_flags_get_zip_size(flags); /* Start first a mini-transaction mtr2 to lock out all other threads from the fsp system */ mtr_start(&mtr2); mtr_x_lock(latch, &mtr2); mtr_start(&mtr); mtr_x_lock(latch, &mtr); header = fsp_get_space_header(space, zip_size, &mtr); size = mtr_read_ulint(header + FSP_SIZE, MLOG_4BYTES, &mtr); free_limit = mtr_read_ulint(header + FSP_FREE_LIMIT, MLOG_4BYTES, &mtr); frag_n_used = mtr_read_ulint(header + FSP_FRAG_N_USED, MLOG_4BYTES, &mtr); n_free = flst_get_len(header + FSP_FREE, &mtr); n_free_frag = flst_get_len(header + FSP_FREE_FRAG, &mtr); n_full_frag = flst_get_len(header + FSP_FULL_FRAG, &mtr); seg_id = mach_read_from_8(header + FSP_SEG_ID); fprintf(stderr, "FILE SPACE INFO: id %lu\n" "size %lu, free limit %lu, free extents %lu\n" "not full frag extents %lu: used pages %lu," " full frag extents %lu\n" "first seg id not used %llu\n", (ulong) space, (ulong) size, (ulong) free_limit, (ulong) n_free, (ulong) n_free_frag, (ulong) frag_n_used, (ulong) n_full_frag, (ullint) seg_id); mtr_commit(&mtr); /* Print segments */ mtr_start(&mtr); mtr_x_lock(latch, &mtr); header = fsp_get_space_header(space, zip_size, &mtr); node_addr = flst_get_first(header + FSP_SEG_INODES_FULL, &mtr); mtr_commit(&mtr); while (!fil_addr_is_null(node_addr)) { n = 0; do { mtr_start(&mtr); mtr_x_lock(latch, &mtr); seg_inode_page = fut_get_ptr( space, zip_size, node_addr, RW_X_LATCH, &mtr) - FSEG_INODE_PAGE_NODE; seg_inode = fsp_seg_inode_page_get_nth_inode( seg_inode_page, n, zip_size, &mtr); ut_a(mach_read_from_8(seg_inode + FSEG_ID) != 0); fseg_print_low(seg_inode, &mtr); n_segs++; next_node_addr = flst_get_next_addr( seg_inode_page + FSEG_INODE_PAGE_NODE, &mtr); mtr_commit(&mtr); } while (++n < FSP_SEG_INODES_PER_PAGE(zip_size)); node_addr = next_node_addr; } mtr_start(&mtr); mtr_x_lock(latch, &mtr); header = fsp_get_space_header(space, zip_size, &mtr); node_addr = flst_get_first(header + FSP_SEG_INODES_FREE, &mtr); mtr_commit(&mtr); while (!fil_addr_is_null(node_addr)) { n = 0; do { mtr_start(&mtr); mtr_x_lock(latch, &mtr); seg_inode_page = fut_get_ptr( space, zip_size, node_addr, RW_X_LATCH, &mtr) - FSEG_INODE_PAGE_NODE; seg_inode = fsp_seg_inode_page_get_nth_inode( seg_inode_page, n, zip_size, &mtr); if (mach_read_from_8(seg_inode + FSEG_ID)) { fseg_print_low(seg_inode, &mtr); n_segs++; } next_node_addr = flst_get_next_addr( seg_inode_page + FSEG_INODE_PAGE_NODE, &mtr); mtr_commit(&mtr); } while (++n < FSP_SEG_INODES_PER_PAGE(zip_size)); node_addr = next_node_addr; } mtr_commit(&mtr2); fprintf(stderr, "NUMBER of file segments: %lu\n", (ulong) n_segs); } #endif /* !UNIV_HOTBACKUP */
cvicentiu/mariadb-10.0
storage/xtradb/fsp/fsp0fsp.cc
C++
gpl-2.0
118,221
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // ****************************************************************** // * // * .,-::::: .,:: .::::::::. .,:: .: // * ,;;;'````' `;;;, .,;; ;;;'';;' `;;;, .,;; // * [[[ '[[,,[[' [[[__[[\. '[[,,[[' // * $$$ Y$$$P $$""""Y$$ Y$$$P // * `88bo,__,o, oP"``"Yo, _88o,,od8P oP"``"Yo, // * "YUMMMMMP",m" "Mm,""YUMMMP" ,m" "Mm, // * // * Cxbx->Win32->CxbxKrnl->EmuFile.cpp // * // * This file is part of the Cxbx project. // * // * Cxbx and Cxbe are free software; you can redistribute them // * and/or modify them 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 recieved 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, Bostom, MA 02111-1307, USA. // * // * (c) 2002-2003 Aaron Robinson <caustik@caustik.com> // * // * All rights reserved // * // ****************************************************************** #define _XBOXKRNL_DEFEXTRN_ #define LOG_PREFIX "FILE" #include "EmuFile.h" #include <vector> #include <string> #include <sstream> #include <cassert> #include <Shlobj.h> #include <Shlwapi.h> #pragma warning(disable:4005) // Ignore redefined status values #include <ntstatus.h> #pragma warning(default:4005) #include "CxbxKrnl.h" #include "VMManager.h" #include <experimental/filesystem> //#include "Logging.h" // For hex4() // Default Xbox Partition Table #define PE_PARTFLAGS_IN_USE 0x80000000 #define XBOX_SWAPPART1_LBA_START 0x400 #define XBOX_SWAPPART_LBA_SIZE 0x177000 #define XBOX_SWAPPART2_LBA_START (XBOX_SWAPPART1_LBA_START + XBOX_SWAPPART_LBA_SIZE) #define XBOX_SWAPPART3_LBA_START (XBOX_SWAPPART2_LBA_START + XBOX_SWAPPART_LBA_SIZE) #define XBOX_SYSPART_LBA_START (XBOX_SWAPPART3_LBA_START + XBOX_SWAPPART_LBA_SIZE) #define XBOX_SYSPART_LBA_SIZE 0xfa000 #define XBOX_MUSICPART_LBA_START (XBOX_SYSPART_LBA_START + XBOX_SYSPART_LBA_SIZE) #define XBOX_MUSICPART_LBA_SIZE 0x9896b0 XboxPartitionTable BackupPartTbl = { {'*', '*', '*', '*', 'P', 'A', 'R', 'T', 'I', 'N', 'F', 'O', '*', '*', '*', '*'}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, { {{'X', 'B', 'O', 'X', ' ', 'S', 'H', 'E', 'L', 'L', ' ', ' ', ' ', ' ', ' ', ' '}, PE_PARTFLAGS_IN_USE, XBOX_MUSICPART_LBA_START, XBOX_MUSICPART_LBA_SIZE, 0}, {{'X', 'B', 'O', 'X', ' ', 'D', 'A', 'T', 'A', ' ', ' ', ' ', ' ', ' ', ' ', ' '}, PE_PARTFLAGS_IN_USE, XBOX_SYSPART_LBA_START, XBOX_SYSPART_LBA_SIZE, 0}, {{'X', 'B', 'O', 'X', ' ', 'G', 'A', 'M', 'E', ' ', 'S', 'W', 'A', 'P', ' ', '1'}, PE_PARTFLAGS_IN_USE, XBOX_SWAPPART1_LBA_START, XBOX_SWAPPART_LBA_SIZE, 0}, {{'X', 'B', 'O', 'X', ' ', 'G', 'A', 'M', 'E', ' ', 'S', 'W', 'A', 'P', ' ', '2'}, PE_PARTFLAGS_IN_USE, XBOX_SWAPPART2_LBA_START, XBOX_SWAPPART_LBA_SIZE, 0}, {{'X', 'B', 'O', 'X', ' ', 'G', 'A', 'M', 'E', ' ', 'S', 'W', 'A', 'P', ' ', '3'}, PE_PARTFLAGS_IN_USE, XBOX_SWAPPART3_LBA_START, XBOX_SWAPPART_LBA_SIZE, 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}, } }; void CxbxCreatePartitionHeaderFile(std::string filename, bool partition0 = false) { HANDLE hf = CreateFile(filename.c_str(), GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0); if (!hf) { CxbxKrnlCleanup("CxbxCreatePartitionHeaderFile Failed\nUnable to create file: %s (%s)", filename); return; } // If this is partition 0, install the partiton table if (partition0) { DWORD NumberOfBytesWritten = 0; WriteFile(hf, &BackupPartTbl, sizeof(XboxPartitionTable), &NumberOfBytesWritten, 0); } SetFilePointer(hf, 512 * ONE_KB, 0, FILE_BEGIN); SetEndOfFile(hf); CloseHandle(hf); } XboxPartitionTable CxbxGetPartitionTable() { XboxPartitionTable table; FILE* fp = fopen((CxbxBasePath + "Partition0.bin").c_str(), "rb"); if (fp == nullptr) { CxbxKrnlCleanup("CxbxGetPartitionTable Failed:\nUnable to open file: %s", (CxbxBasePath + "Partition0.bin").c_str()); } fread(&table, sizeof(XboxPartitionTable), 1, fp); fclose(fp); // If the partition table is not valid, format it // This allows recovery from corrupted partition tables // Or invalid partition tables left behind from previous versions // of Cxbx-Reloaded if (memcmp(table.Magic, BackupPartTbl.Magic, 16) != 0) { DeleteFile((CxbxBasePath + "Partition0.bin").c_str()); CxbxCreatePartitionHeaderFile(CxbxBasePath + "Partition0.bin", true); memcpy(&table, &BackupPartTbl, sizeof(XboxPartitionTable)); } return table; } FATX_SUPERBLOCK CxbxGetFatXSuperBlock(int partitionNumber) { FATX_SUPERBLOCK superblock; std::stringstream ss; ss << CxbxBasePath << "Partition" << partitionNumber << ".bin"; FILE* fp = fopen(ss.str().c_str(), "rb"); fread(&superblock, sizeof(FATX_SUPERBLOCK), 1, fp); fclose(fp); return superblock; } int CxbxGetPartitionNumberFromHandle(HANDLE hFile) { // Get which partition number is being accessed, by parsing the filename and extracting the last portion char buffer[MAX_PATH] = {0}; if (!GetFinalPathNameByHandle(hFile, buffer, MAX_PATH, VOLUME_NAME_DOS)) { CxbxKrnlCleanup("CxbxGetPartitionNumberFromHandle Failed:\nUnable to determine path for HANDLE 0x%08X", hFile); } std::string bufferString(buffer); std::string partitionString = "\\Partition"; std::string partitionNumberString = bufferString.substr(bufferString.find(partitionString) + partitionString.length(), 1); // atoi returns 0 on non-numeric characters, so we don't need to error check here return atoi(partitionNumberString.c_str()); } std::string CxbxGetPartitionDataPathFromHandle(HANDLE hFile) { // Get which partition number is being accessed, by parsing the filename and extracting the last portion char buffer[MAX_PATH] = {0}; if (!GetFinalPathNameByHandle(hFile, buffer, MAX_PATH, VOLUME_NAME_DOS)) { CxbxKrnlCleanup("CxbxGetPartitionDataPathFromHandle Failed:\nUnable to determine path for HANDLE 0x%08X", hFile); } std::string bufferString(buffer); std::string partitionString = "\\Partition"; std::string partitionPath = bufferString.substr(0, bufferString.find(partitionString) + partitionString.length() + 1); return partitionPath; } void CxbxFormatPartitionByHandle(HANDLE hFile) { std::string partitionPath = CxbxGetPartitionDataPathFromHandle(hFile); // Sanity check, make sure we are actually deleting something within the Cxbx-Reloaded folder if (partitionPath.find("Cxbx-Reloaded") == std::string::npos) { EmuWarning("Attempting to format a path that is not within a Cxbx-Reloaded data folder... Ignoring!\n"); return; } // Format the partition, by iterating through the contents and removing all files/folders within // Previously, we deleted and re-created the folder, but that caused permission issues for some users try { for (auto& directoryEntry : std::experimental::filesystem::recursive_directory_iterator(partitionPath)) { std::experimental::filesystem::remove_all(directoryEntry); } } catch (std::experimental::filesystem::filesystem_error fsException) { printf("std::experimental::filesystem failed with message: %s\n", fsException.what()); } printf("Formatted EmuDisk Partition%d\n", CxbxGetPartitionNumberFromHandle(hFile)); } const std::string DrivePrefix = "\\??\\"; const std::string DriveSerial = DrivePrefix + "serial:"; const std::string DriveCdRom0 = DrivePrefix + "CdRom0:"; // CD-ROM device const std::string DriveMbfs = DrivePrefix + "mbfs:"; // media board's file system area device const std::string DriveMbcom = DrivePrefix + "mbcom:"; // media board's communication area device const std::string DriveMbrom = DrivePrefix + "mbrom:"; // media board's boot ROM device const std::string DriveA = DrivePrefix + "A:"; // A: could be CDROM const std::string DriveC = DrivePrefix + "C:"; // C: is HDD0 const std::string DriveD = DrivePrefix + "D:"; // D: is DVD Player const std::string DriveE = DrivePrefix + "E:"; const std::string DriveF = DrivePrefix + "F:"; const std::string DriveS = DrivePrefix + "S:"; const std::string DriveT = DrivePrefix + "T:"; // T: is Title persistent data region const std::string DriveU = DrivePrefix + "U:"; // U: is User persistent data region const std::string DriveV = DrivePrefix + "V:"; const std::string DriveW = DrivePrefix + "W:"; const std::string DriveX = DrivePrefix + "X:"; const std::string DriveY = DrivePrefix + "Y:"; // Y: is Dashboard volume (contains "xboxdash.xbe" and "XDASH" folder + contents) const std::string DriveZ = DrivePrefix + "Z:"; // Z: is Title utility data region const std::string DevicePrefix = "\\Device"; const std::string DeviceCdrom0 = DevicePrefix + "\\CdRom0"; const std::string DeviceHarddisk0 = DevicePrefix + "\\Harddisk0"; const std::string DeviceHarddisk0PartitionPrefix = DevicePrefix + "\\Harddisk0\\partition"; const std::string DeviceHarddisk0Partition0 = DeviceHarddisk0PartitionPrefix + "0"; // Contains raw config sectors (like XBOX_REFURB_INFO) + entire hard disk const std::string DeviceHarddisk0Partition1 = DeviceHarddisk0PartitionPrefix + "1"; // Data partition. Contains TDATA and UDATA folders. const std::string DeviceHarddisk0Partition2 = DeviceHarddisk0PartitionPrefix + "2"; // Shell partition. Contains Dashboard (cpxdash.xbe, evoxdash.xbe or xboxdash.xbe) const std::string DeviceHarddisk0Partition3 = DeviceHarddisk0PartitionPrefix + "3"; // First cache partition. Contains cache data (from here up to largest number) const std::string DeviceHarddisk0Partition4 = DeviceHarddisk0PartitionPrefix + "4"; const std::string DeviceHarddisk0Partition5 = DeviceHarddisk0PartitionPrefix + "5"; const std::string DeviceHarddisk0Partition6 = DeviceHarddisk0PartitionPrefix + "6"; const std::string DeviceHarddisk0Partition7 = DeviceHarddisk0PartitionPrefix + "7"; const std::string DeviceHarddisk0Partition8 = DeviceHarddisk0PartitionPrefix + "8"; const std::string DeviceHarddisk0Partition9 = DeviceHarddisk0PartitionPrefix + "9"; const std::string DeviceHarddisk0Partition10 = DeviceHarddisk0PartitionPrefix + "10"; const std::string DeviceHarddisk0Partition11 = DeviceHarddisk0PartitionPrefix + "11"; const std::string DeviceHarddisk0Partition12 = DeviceHarddisk0PartitionPrefix + "12"; const std::string DeviceHarddisk0Partition13 = DeviceHarddisk0PartitionPrefix + "13"; const std::string DeviceHarddisk0Partition14 = DeviceHarddisk0PartitionPrefix + "14"; const std::string DeviceHarddisk0Partition15 = DeviceHarddisk0PartitionPrefix + "15"; const std::string DeviceHarddisk0Partition16 = DeviceHarddisk0PartitionPrefix + "16"; const std::string DeviceHarddisk0Partition17 = DeviceHarddisk0PartitionPrefix + "17"; const std::string DeviceHarddisk0Partition18 = DeviceHarddisk0PartitionPrefix + "18"; const std::string DeviceHarddisk0Partition19 = DeviceHarddisk0PartitionPrefix + "19"; const std::string DeviceHarddisk0Partition20 = DeviceHarddisk0PartitionPrefix + "20"; // 20 = Largest possible partition number const char CxbxDefaultXbeDriveLetter = 'D'; int CxbxDefaultXbeDriveIndex = -1; EmuNtSymbolicLinkObject* NtSymbolicLinkObjects[26]; std::vector<XboxDevice> Devices; EmuHandle::EmuHandle(EmuNtObject* ntObject) { NtObject = ntObject; } NTSTATUS EmuHandle::NtClose() { return NtObject->NtClose(); } NTSTATUS EmuHandle::NtDuplicateObject(PHANDLE TargetHandle, DWORD Options) { *TargetHandle = NtObject->NtDuplicateObject(Options)->NewHandle(); return STATUS_SUCCESS; } EmuNtObject::EmuNtObject() { RefCount = 1; } HANDLE EmuNtObject::NewHandle() { RefCount++; return EmuHandleToHandle(new EmuHandle(this)); } NTSTATUS EmuNtObject::NtClose() { if (--RefCount <= 0) { delete this; } return STATUS_SUCCESS; } EmuNtObject* EmuNtObject::NtDuplicateObject(DWORD Options) { RefCount++; return this; } bool IsEmuHandle(HANDLE Handle) { return ((uint32)Handle > 0x80000000) && ((uint32)Handle < 0xFFFFFFFE); } EmuHandle* HandleToEmuHandle(HANDLE Handle) { return (EmuHandle*)((uint32_t)Handle & 0x7FFFFFFF); } HANDLE EmuHandleToHandle(EmuHandle* emuHandle) { return (HANDLE)((uint32_t)emuHandle | 0x80000000); } std::wstring string_to_wstring(std::string const & src) { std::wstring result = std::wstring(src.length(), L' '); std::copy(src.begin(), src.end(), result.begin()); return result; } std::wstring PUNICODE_STRING_to_wstring(NtDll::PUNICODE_STRING const & src) { return std::wstring(src->Buffer, src->Length / sizeof(NtDll::WCHAR)); } std::string PSTRING_to_string(xboxkrnl::PSTRING const & src) { return std::string(src->Buffer, src->Length); } void copy_string_to_PSTRING_to(std::string const & src, const xboxkrnl::PSTRING & dest) { dest->Length = (USHORT)src.size(); memcpy(dest->Buffer, src.c_str(), src.size()); } void replace_all(std::string& str, const std::string& from, const std::string& to) { if(from.empty()) return; size_t start_pos = 0; while((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx' } } NTSTATUS CxbxConvertFilePath( std::string RelativeXboxPath, OUT std::wstring &RelativeHostPath, OUT NtDll::HANDLE *RootDirectory, std::string aFileAPIName, bool partitionHeader) { std::string OriginalPath = RelativeXboxPath; std::string RelativePath = RelativeXboxPath; std::string XboxFullPath; std::string HostPath; EmuNtSymbolicLinkObject* NtSymbolicLinkObject = NULL; // Always trim '\??\' off : if (RelativePath.compare(0, DrivePrefix.length(), DrivePrefix.c_str()) == 0) RelativePath.erase(0, 4); // Check if we where called from a File-handling API : if (!aFileAPIName.empty()) { if (!partitionHeader) { // Check if the path starts with a volume indicator : if ((RelativePath.length() >= 2) && (RelativePath[1] == ':')) { // Look up the symbolic link information using the drive letter : NtSymbolicLinkObject = FindNtSymbolicLinkObjectByDriveLetter(RelativePath[0]); RelativePath.erase(0, 2); // Remove 'C:' // If the remaining path starts with a ':', remove it (to prevent errors) : if ((RelativePath.length() > 0) && (RelativePath[0] == ':')) RelativePath.erase(0, 1); // xbmp needs this, as it accesses 'e::\' } else if (RelativePath[0] == '$') { if (RelativePath.compare(0, 5, "$HOME") == 0) // "xbmp" needs this { NtSymbolicLinkObject = FindNtSymbolicLinkObjectByRootHandle(g_hCurDir); RelativePath.erase(0, 5); // Remove '$HOME' } else CxbxKrnlCleanup(("Unsupported path macro : " + OriginalPath).c_str()); } // Check if the path starts with a relative path indicator : else if (RelativePath[0] == '.') // "4x4 Evo 2" needs this { NtSymbolicLinkObject = FindNtSymbolicLinkObjectByRootHandle(g_hCurDir); RelativePath.erase(0, 1); // Remove the '.' } else { // TODO : How should we handle accesses to the serial: (?semi-)volume? if (RelativePath.compare(0, 7, "serial:") == 0) return STATUS_UNRECOGNIZED_VOLUME; // The path seems to be a device path, look it up : NtSymbolicLinkObject = FindNtSymbolicLinkObjectByDevice(RelativePath); // Fixup RelativePath path here if (NtSymbolicLinkObject != NULL) RelativePath.erase(0, NtSymbolicLinkObject->XboxSymbolicLinkPath.length()); // Remove '\Device\Harddisk0\Partition2' // else TODO : Turok requests 'gamedata.dat' without a preceding path, we probably need 'CurrentDir'-functionality } if (NtSymbolicLinkObject == NULL) { // Check if the path accesses a partition from Harddisk0 : if (_strnicmp(RelativePath.c_str(), DeviceHarddisk0PartitionPrefix.c_str(), DeviceHarddisk0PartitionPrefix.length()) == 0) { XboxFullPath = RelativePath; // Remove Harddisk0 prefix, in the hope that the remaining path might work : RelativePath.erase(0, DeviceHarddisk0.length() + 1); // And set Root to the folder containing the partition-folders : *RootDirectory = CxbxBasePathHandle; HostPath = CxbxBasePath; } else { // Finally, Assume relative to Xbe path NtSymbolicLinkObject = FindNtSymbolicLinkObjectByRootHandle(g_hCurDir); } } if (NtSymbolicLinkObject != NULL) { HostPath = NtSymbolicLinkObject->HostSymbolicLinkPath; XboxFullPath = NtSymbolicLinkObject->XboxSymbolicLinkPath; // If accessing a partition as a directly, set the root directory handle and keep relative path as is *RootDirectory = NtSymbolicLinkObject->RootDirectoryHandle; } } else { *RootDirectory = CxbxBasePathHandle; HostPath = CxbxBasePath; RelativePath = RelativeXboxPath.substr(DeviceHarddisk0.length()) + ".bin"; } // If the remaining path starts with a '\', remove it (to prevent working in a native root) : if ((RelativePath.length() > 0) && (RelativePath[0] == '\\')) { RelativePath.erase(0, 1); // And if needed, add it to the host path instead : if (HostPath.back() != '\\') HostPath.append(1, '\\'); } // Lastly, remove any '\\' sequences in the string (this should fix the problem with Azurik game saves) replace_all( RelativePath, "\\\\", "\\" ); if (g_bPrintfOn) { DbgPrintf("FILE: %s Corrected path...\n", aFileAPIName.c_str()); printf(" Org:\"%s\"\n", OriginalPath.c_str()); if (_strnicmp(HostPath.c_str(), CxbxBasePath.c_str(), CxbxBasePath.length()) == 0) { printf(" New:\"$CxbxPath\\%s%s\"\n", (HostPath.substr(CxbxBasePath.length(), std::string::npos)).c_str(), RelativePath.c_str()); } else printf(" New:\"$XbePath\\%s\"\n", RelativePath.c_str()); } } else { // For non-file API calls, prefix with '\??\' again : RelativePath = DrivePrefix + RelativePath; *RootDirectory = 0; } // Convert the relative path to unicode RelativeHostPath = string_to_wstring(RelativePath); return STATUS_SUCCESS; } NTSTATUS CxbxObjectAttributesToNT( xboxkrnl::POBJECT_ATTRIBUTES ObjectAttributes, OUT NativeObjectAttributes& nativeObjectAttributes, const std::string aFileAPIName, bool partitionHeader) { if (ObjectAttributes == NULL) { // When the pointer is nil, make sure we pass nil to Windows too : nativeObjectAttributes.NtObjAttrPtr = nullptr; return STATUS_SUCCESS; } // Pick up the ObjectName, and let's see what to make of it : std::string ObjectName = ""; if (ObjectAttributes->ObjectName != NULL) { ObjectName = PSTRING_to_string(ObjectAttributes->ObjectName); } std::wstring RelativeHostPath; NtDll::HANDLE RootDirectory = ObjectAttributes->RootDirectory; // Handle special root directory constants if (RootDirectory == (NtDll::HANDLE)-4) { RootDirectory = NULL; if (ObjectName.size() == 0){ ObjectName = "\\BaseNamedObjects"; } else { ObjectName = "\\BaseNamedObjects\\" + ObjectName; } } // Is there a filename API given? if (aFileAPIName.size() > 0) { // Then interpret the ObjectName as a filename, and update it to host relative : NTSTATUS result = CxbxConvertFilePath(ObjectName, /*OUT*/RelativeHostPath, /*OUT*/&RootDirectory, aFileAPIName, partitionHeader); if (FAILED(result)) return result; } else // When not called from a file-handling API, just convert the ObjectName to a wide string : RelativeHostPath = string_to_wstring(ObjectName); // Copy the wide string to the unicode string wcscpy_s(nativeObjectAttributes.wszObjectName, RelativeHostPath.c_str()); NtDll::RtlInitUnicodeString(&nativeObjectAttributes.NtUnicodeString, nativeObjectAttributes.wszObjectName); // And initialize the NT ObjectAttributes with that : InitializeObjectAttributes(&nativeObjectAttributes.NtObjAttr, &nativeObjectAttributes.NtUnicodeString, ObjectAttributes->Attributes, RootDirectory, NULL); // ObjectAttributes are given, so make sure the pointer we're going to pass to Windows is assigned : nativeObjectAttributes.NtObjAttrPtr = &nativeObjectAttributes.NtObjAttr; return STATUS_SUCCESS; } int CxbxDeviceIndexByDevicePath(const char *XboxDevicePath) { for (size_t i = 0; i < Devices.size(); i++) if (_strnicmp(XboxDevicePath, Devices[i].XboxDevicePath.c_str(), Devices[i].XboxDevicePath.length()) == 0) return(i); return -1; } XboxDevice *CxbxDeviceByDevicePath(const std::string XboxDevicePath) { int DeviceIndex = CxbxDeviceIndexByDevicePath(XboxDevicePath.c_str()); if (DeviceIndex >= 0) return &Devices[DeviceIndex]; return nullptr; } int CxbxRegisterDeviceHostPath(std::string XboxDevicePath, std::string HostDevicePath, bool IsFile) { int result = -1; NTSTATUS status = (NTSTATUS)-1; XboxDevice newDevice; newDevice.XboxDevicePath = XboxDevicePath; newDevice.HostDevicePath = HostDevicePath; // All HDD partitions have a .bin file to allow direct file io on the partition info if (_strnicmp(XboxDevicePath.c_str(), DeviceHarddisk0PartitionPrefix.c_str(), DeviceHarddisk0PartitionPrefix.length()) == 0) { std::string partitionHeaderPath = (HostDevicePath + ".bin").c_str(); if (!PathFileExists(partitionHeaderPath.c_str())) { CxbxCreatePartitionHeaderFile(partitionHeaderPath, XboxDevicePath == DeviceHarddisk0Partition0); } status = STATUS_SUCCESS; } // If this path is not a raw file partition, create the directory for it if (!IsFile) { status = SHCreateDirectoryEx(NULL, HostDevicePath.c_str(), NULL); } if (status == STATUS_SUCCESS || status == ERROR_ALREADY_EXISTS) { Devices.push_back(newDevice); result = Devices.size() - 1; } return result; } NTSTATUS CxbxCreateSymbolicLink(std::string SymbolicLinkName, std::string FullPath) { NTSTATUS result = 0; EmuNtSymbolicLinkObject* SymbolicLinkObject = FindNtSymbolicLinkObjectByName(SymbolicLinkName); if (SymbolicLinkObject != NULL) // In that case, close it (will also delete if reference count drops to zero) SymbolicLinkObject->NtClose(); // Now (re)create a symbolic link object, and initialize it with the new definition : SymbolicLinkObject = new EmuNtSymbolicLinkObject(); result = SymbolicLinkObject->Init(SymbolicLinkName, FullPath); if (result != STATUS_SUCCESS) SymbolicLinkObject->NtClose(); return result; } NTSTATUS EmuNtSymbolicLinkObject::Init(std::string aSymbolicLinkName, std::string aFullPath) { NTSTATUS result = STATUS_OBJECT_NAME_INVALID; int i = 0; int DeviceIndex = 0; // If aFullPath is an empty string, set it to the CD-ROM drive // This should work for all titles, as CD-ROM is mapped to the current working directory // This fixes the issue where titles crash after being launched from the update.xbe if (aFullPath.length() == 0) { aFullPath = DeviceCdrom0; } DriveLetter = SymbolicLinkToDriveLetter(aSymbolicLinkName); if (DriveLetter >= 'A' && DriveLetter <= 'Z') { result = STATUS_OBJECT_NAME_COLLISION; if (FindNtSymbolicLinkObjectByDriveLetter(DriveLetter) == NULL) { // Look up the partition in the list of pre-registered devices : result = STATUS_DEVICE_DOES_NOT_EXIST; // TODO : Is this the correct error? // If aFullPath starts with a Drive letter, find the originating path and substitute that if (aFullPath[1] == ':' && aFullPath[0] >= 'A' && aFullPath[0] <= 'Z') { EmuNtSymbolicLinkObject* DriveLetterLink = FindNtSymbolicLinkObjectByDriveLetter(aFullPath[0]); if (DriveLetterLink != NULL) { aFullPath = DriveLetterLink->XboxSymbolicLinkPath; } } // Make a distinction between Xbox paths (starting with '\Device'...) and host paths : IsHostBasedPath = _strnicmp(aFullPath.c_str(), DevicePrefix.c_str(), DevicePrefix.length()) != 0; if (IsHostBasedPath) DeviceIndex = CxbxDefaultXbeDriveIndex; else DeviceIndex = CxbxDeviceIndexByDevicePath(aFullPath.c_str()); if (DeviceIndex >= 0) { result = STATUS_SUCCESS; SymbolicLinkName = aSymbolicLinkName; if (IsHostBasedPath) { XboxSymbolicLinkPath = ""; HostSymbolicLinkPath = aFullPath; } else { XboxSymbolicLinkPath = aFullPath; HostSymbolicLinkPath = Devices[DeviceIndex].HostDevicePath; // Handle the case where a sub folder of the partition is mounted (instead of it's root) : std::string ExtraPath = aFullPath.substr(Devices[DeviceIndex].XboxDevicePath.length(), std::string::npos); if (!ExtraPath.empty()) HostSymbolicLinkPath = HostSymbolicLinkPath + ExtraPath; } SHCreateDirectoryEx(NULL, HostSymbolicLinkPath.c_str(), NULL); RootDirectoryHandle = CreateFile(HostSymbolicLinkPath.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if (RootDirectoryHandle == INVALID_HANDLE_VALUE) { result = STATUS_DEVICE_DOES_NOT_EXIST; // TODO : Is this the correct error? CxbxKrnlCleanup((std::string("Could not map ") + HostSymbolicLinkPath).c_str()); } else { NtSymbolicLinkObjects[DriveLetter - 'A'] = this; DbgPrintf("FILE: Linked \"%s\" to \"%s\" (residing at \"%s\")\n", aSymbolicLinkName.c_str(), aFullPath.c_str(), HostSymbolicLinkPath.c_str()); } } } } return result; } EmuNtSymbolicLinkObject::~EmuNtSymbolicLinkObject() { if (DriveLetter >= 'A' && DriveLetter <= 'Z') { NtSymbolicLinkObjects[DriveLetter - 'A'] = NULL; NtDll::NtClose(RootDirectoryHandle); } } char SymbolicLinkToDriveLetter(std::string SymbolicLinkName) { char result = '\0'; // SymbolicLinkName must look like this : "\??\D:" if ((SymbolicLinkName.size() == 6) && (SymbolicLinkName[0] == '\\') && (SymbolicLinkName[1] == '?') && (SymbolicLinkName[2] == '?') && (SymbolicLinkName[3] == '\\') && (SymbolicLinkName[5] == ':')) { result = SymbolicLinkName[4]; if (result >= 'A' && result <= 'Z') return result; if (result >= 'a' && result <= 'z') { return result + 'A' - 'a'; } } return NULL; } EmuNtSymbolicLinkObject* FindNtSymbolicLinkObjectByDriveLetter(const char DriveLetter) { if (DriveLetter >= 'A' && DriveLetter <= 'Z') return NtSymbolicLinkObjects[DriveLetter - 'A']; if (DriveLetter >= 'a' && DriveLetter <= 'z') return NtSymbolicLinkObjects[DriveLetter - 'a']; return NULL; } EmuNtSymbolicLinkObject* FindNtSymbolicLinkObjectByName(std::string SymbolicLinkName) { return FindNtSymbolicLinkObjectByDriveLetter(SymbolicLinkToDriveLetter(SymbolicLinkName)); } EmuNtSymbolicLinkObject* FindNtSymbolicLinkObjectByDevice(std::string DeviceName) { for (char DriveLetter = 'A'; DriveLetter <= 'Z'; DriveLetter++) { EmuNtSymbolicLinkObject* result = NtSymbolicLinkObjects[DriveLetter - 'A']; if ((result != NULL) && _strnicmp(DeviceName.c_str(), result->XboxSymbolicLinkPath.c_str(), result->XboxSymbolicLinkPath.length()) == 0) return result; } return NULL; } EmuNtSymbolicLinkObject* FindNtSymbolicLinkObjectByRootHandle(const HANDLE Handle) { for (char DriveLetter = 'A'; DriveLetter <= 'Z'; DriveLetter++) { EmuNtSymbolicLinkObject* result = NtSymbolicLinkObjects[DriveLetter - 'A']; if ((result != NULL) && (Handle == result->RootDirectoryHandle)) return result; } return NULL; } void _CxbxPVOIDDeleter(PVOID *ptr) { if (*ptr) g_VMManager.Deallocate((VAddr)*ptr); } // ---------------------------------------------------------------------------- // Xbox to NT converters // ---------------------------------------------------------------------------- NtDll::FILE_LINK_INFORMATION * _XboxToNTLinkInfo(xboxkrnl::FILE_LINK_INFORMATION *xboxLinkInfo, ULONG *Length) { // Convert the path from Xbox to native std::string originalFileName(xboxLinkInfo->FileName, xboxLinkInfo->FileNameLength); std::wstring convertedFileName; NtDll::HANDLE RootDirectory; NTSTATUS res = CxbxConvertFilePath(originalFileName, /*OUT*/convertedFileName, /*OUT*/&RootDirectory, "NtSetInformationFile"); // TODO : handle if(FAILED(res)) // Build the native FILE_LINK_INFORMATION struct *Length = sizeof(NtDll::FILE_LINK_INFORMATION) + convertedFileName.size() * sizeof(wchar_t); NtDll::FILE_LINK_INFORMATION *ntLinkInfo = (NtDll::FILE_LINK_INFORMATION *) g_VMManager.AllocateZeroed(*Length); ntLinkInfo->ReplaceIfExists = xboxLinkInfo->ReplaceIfExists; ntLinkInfo->RootDirectory = RootDirectory; ntLinkInfo->FileNameLength = convertedFileName.size() * sizeof(wchar_t); wmemcpy_s(ntLinkInfo->FileName, convertedFileName.size(), convertedFileName.c_str(), convertedFileName.size()); return ntLinkInfo; } NtDll::FILE_RENAME_INFORMATION * _XboxToNTRenameInfo(xboxkrnl::FILE_RENAME_INFORMATION *xboxRenameInfo, ULONG *Length) { // Convert the path from Xbox to native std::string originalFileName(xboxRenameInfo->FileName.Buffer, xboxRenameInfo->FileName.Length); std::wstring convertedFileName; NtDll::HANDLE RootDirectory; NTSTATUS res = CxbxConvertFilePath(originalFileName, /*OUT*/convertedFileName, /*OUT*/&RootDirectory, "NtSetInformationFile"); // TODO : handle if(FAILED(res)) // Build the native FILE_RENAME_INFORMATION struct *Length = sizeof(NtDll::FILE_RENAME_INFORMATION) + convertedFileName.size() * sizeof(wchar_t); NtDll::FILE_RENAME_INFORMATION *ntRenameInfo = (NtDll::FILE_RENAME_INFORMATION *) g_VMManager.AllocateZeroed(*Length); ntRenameInfo->ReplaceIfExists = xboxRenameInfo->ReplaceIfExists; ntRenameInfo->RootDirectory = RootDirectory; ntRenameInfo->FileNameLength = convertedFileName.size() * sizeof(wchar_t); wmemcpy_s(ntRenameInfo->FileName, convertedFileName.size(), convertedFileName.c_str(), convertedFileName.size()); return ntRenameInfo; } // ---------------------------------------------------------------------------- // NT to Xbox converters - common functions // ---------------------------------------------------------------------------- void _ConvertXboxBasicInfo(xboxkrnl::FILE_BASIC_INFORMATION *xboxBasicInfo) { // Fix up attributes xboxBasicInfo->FileAttributes &= FILE_ATTRIBUTE_VALID_FLAGS; } NTSTATUS _ConvertXboxNameInfo(NtDll::FILE_NAME_INFORMATION *ntNameInfo, xboxkrnl::FILE_NAME_INFORMATION *xboxNameInfo, int convertedFileNameLength, ULONG Length) { // Convert the file name to ANSI in-place xboxNameInfo->FileNameLength = convertedFileNameLength; // Check if the new file name fits within the given struct size and copy as many chars as possible if not int maxFileNameLength = Length - sizeof(xboxkrnl::FILE_NAME_INFORMATION); size_t convertedChars; wcstombs_s(&convertedChars, xboxNameInfo->FileName, maxFileNameLength, ntNameInfo->FileName, ntNameInfo->FileNameLength); // Return the appropriate result depending on whether the string was fully copied return convertedChars == ntNameInfo->FileNameLength / sizeof(NtDll::WCHAR) ? STATUS_SUCCESS : STATUS_BUFFER_OVERFLOW; } // ---------------------------------------------------------------------------- // NT to Xbox converters // ---------------------------------------------------------------------------- NTSTATUS _NTToXboxNetOpenInfo(NtDll::FILE_NETWORK_OPEN_INFORMATION *ntNetOpenInfo, xboxkrnl::FILE_NETWORK_OPEN_INFORMATION *xboxNetOpenInfo, ULONG Length) { // Copy everything from the NT struct memcpy_s(xboxNetOpenInfo, Length, ntNetOpenInfo, sizeof(NtDll::FILE_NETWORK_OPEN_INFORMATION)); // Fix up attributes xboxNetOpenInfo->FileAttributes &= FILE_ATTRIBUTE_VALID_FLAGS; return STATUS_SUCCESS; } NTSTATUS _NTToXboxBasicInfo(NtDll::FILE_BASIC_INFORMATION *ntBasicInfo, xboxkrnl::FILE_BASIC_INFORMATION *xboxBasicInfo, ULONG Length) { // Copy everything from the NT struct memcpy_s(xboxBasicInfo, sizeof(xboxkrnl::FILE_BASIC_INFORMATION), ntBasicInfo, sizeof(NtDll::FILE_BASIC_INFORMATION)); _ConvertXboxBasicInfo(xboxBasicInfo); return STATUS_SUCCESS; } NTSTATUS _NTToXboxNameInfo(NtDll::FILE_NAME_INFORMATION *ntNameInfo, xboxkrnl::FILE_NAME_INFORMATION *xboxNameInfo, ULONG Length) { // TODO: the FileName probably needs to be converted back to an Xbox path in some cases // Determine new file name length size_t convertedFileNameLength = ntNameInfo->FileNameLength / sizeof(NtDll::WCHAR); // Clean up the Xbox FILE_NAME_INFORMATION struct ZeroMemory(xboxNameInfo, Length); // Convert file name and return the result return _ConvertXboxNameInfo(ntNameInfo, xboxNameInfo, convertedFileNameLength, Length); } NTSTATUS _NTToXboxAllInfo(NtDll::FILE_ALL_INFORMATION *ntAllInfo, xboxkrnl::FILE_ALL_INFORMATION *xboxAllInfo, ULONG Length) { // TODO: the FileName probably needs to be converted back to an Xbox path in some cases // Determine new file name length size_t convertedFileNameLength = ntAllInfo->NameInformation.FileNameLength / sizeof(NtDll::WCHAR); // Copy everything from the NT struct memcpy_s(xboxAllInfo, Length, ntAllInfo, sizeof(NtDll::FILE_ALL_INFORMATION)); // Convert NT structs to Xbox where needed and return the result _ConvertXboxBasicInfo(&xboxAllInfo->BasicInformation); return _ConvertXboxNameInfo(&ntAllInfo->NameInformation, &xboxAllInfo->NameInformation, convertedFileNameLength, Length); } // ---------------------------------------------------------------------------- // File information struct converters // ---------------------------------------------------------------------------- PVOID _XboxToNTFileInformation ( IN PVOID xboxFileInformation, IN ULONG FileInformationClass, OUT ULONG *Length ) { // The following classes of file information structs are identical between platforms: // FileBasicInformation // FileDispositionInformation // FileEndOfFileInformation // FileLinkInformation // FilePositionInformation PVOID result = NULL; switch (FileInformationClass) { case xboxkrnl::FileLinkInformation: { xboxkrnl::FILE_LINK_INFORMATION *xboxLinkInfo = reinterpret_cast<xboxkrnl::FILE_LINK_INFORMATION *>(xboxFileInformation); result = _XboxToNTLinkInfo(xboxLinkInfo, Length); break; } case xboxkrnl::FileRenameInformation: { xboxkrnl::FILE_RENAME_INFORMATION *xboxRenameInfo = reinterpret_cast<xboxkrnl::FILE_RENAME_INFORMATION *>(xboxFileInformation); result = _XboxToNTRenameInfo(xboxRenameInfo, Length); break; } default: { result = NULL; break; } } return result; } NTSTATUS NTToXboxFileInformation ( IN PVOID nativeFileInformation, OUT PVOID xboxFileInformation, IN ULONG FileInformationClass, IN ULONG Length ) { // The following classes of file information structs are identical between platforms: // FileAccessInformation // FileAlignmentInformation // FileEaInformation // FileInternalInformation // FileModeInformation // FilePositionInformation // FileStandardInformation // FileReparsePointInformation NTSTATUS result = STATUS_SUCCESS; switch (FileInformationClass) { case NtDll::FileAllInformation: { NtDll::FILE_ALL_INFORMATION *ntAllInfo = reinterpret_cast<NtDll::FILE_ALL_INFORMATION *>(nativeFileInformation); xboxkrnl::FILE_ALL_INFORMATION *xboxAllInfo = reinterpret_cast<xboxkrnl::FILE_ALL_INFORMATION *>(xboxFileInformation); result = _NTToXboxAllInfo(ntAllInfo, xboxAllInfo, Length); break; } case NtDll::FileBasicInformation: { NtDll::FILE_BASIC_INFORMATION *ntBasicInfo = reinterpret_cast<NtDll::FILE_BASIC_INFORMATION *>(nativeFileInformation); xboxkrnl::FILE_BASIC_INFORMATION *xboxBasicInfo = reinterpret_cast<xboxkrnl::FILE_BASIC_INFORMATION *>(xboxFileInformation); result = _NTToXboxBasicInfo(ntBasicInfo, xboxBasicInfo, Length); break; } case NtDll::FileNameInformation: { NtDll::FILE_NAME_INFORMATION *ntNameInfo = reinterpret_cast<NtDll::FILE_NAME_INFORMATION *>(nativeFileInformation); xboxkrnl::FILE_NAME_INFORMATION *xboxNameInfo = reinterpret_cast<xboxkrnl::FILE_NAME_INFORMATION *>(xboxFileInformation); result = _NTToXboxNameInfo(ntNameInfo, xboxNameInfo, Length); break; } case NtDll::FileNetworkOpenInformation: { NtDll::FILE_NETWORK_OPEN_INFORMATION *ntNetOpenInfo = reinterpret_cast<NtDll::FILE_NETWORK_OPEN_INFORMATION *>(nativeFileInformation); xboxkrnl::FILE_NETWORK_OPEN_INFORMATION *xboxNetOpenInfo = reinterpret_cast<xboxkrnl::FILE_NETWORK_OPEN_INFORMATION *>(xboxFileInformation); result = _NTToXboxNetOpenInfo(ntNetOpenInfo, xboxNetOpenInfo, Length); break; } case NtDll::FileBothDirectoryInformation: { // TODO: handle differences // - Xbox reuses the FILE_DIRECTORY_INFORMATION struct, which is mostly identical to FILE_BOTH_DIR_INFORMATION // - NextEntryOffset might be a problem // - NT has extra fields before FileName: // - ULONG EaSize // - CCHAR ShortNameLength // - WCHAR ShortName[12] // - FileName on Xbox uses single-byte chars, NT uses wide chars //break; } case NtDll::FileDirectoryInformation: { // TODO: handle differences // - NextEntryOffset might be a problem // - FileName on Xbox uses single-byte chars, NT uses wide chars //break; } case NtDll::FileFullDirectoryInformation: { // TODO: handle differences // - Xbox reuses the FILE_DIRECTORY_INFORMATION struct, which is mostly identical to FILE_FULL_DIR_INFORMATION // - NextEntryOffset might be a problem // - NT has one extra field before FileName: // - ULONG EaSize // - FileName on Xbox uses single-byte chars, NT uses wide chars //break; } case NtDll::FileNamesInformation: { // TODO: handle differences // - NextEntryOffset might be a problem // - FileName on Xbox uses single-byte chars, NT uses wide chars //break; } case NtDll::FileObjectIdInformation: { // TODO: handle differences // - The LONGLONG FileReference field from NT can be ignored // - ExtendedInfo is an union on NT, but is otherwise identical //break; } default: { // No differences between structs; a simple copy should suffice memcpy_s(xboxFileInformation, Length, nativeFileInformation, Length); result = STATUS_SUCCESS; break; } } return result; } // TODO: FS_INFORMATION_CLASS and its related structs most likely need to be converted too // TODO : Move to a better suited file /* TODO : Also, fix C2593: "'operator <<' is ambiguous" for this std::ostream& operator<<(std::ostream& os, const NtDll::NTSTATUS& value) { os << hex4((uint32_t)value) << " = " << NtStatusToString(value); return os; } */ // TODO : Create (and use) an Xbox version of this too CHAR* NtStatusToString(IN NTSTATUS Status) { #define _CASE(s) case s: return #s; switch (Status) { // Note : Keep all cases sorted, for easier maintenance _CASE(DBG_APP_NOT_IDLE); _CASE(DBG_CONTINUE); _CASE(DBG_CONTROL_BREAK); _CASE(DBG_CONTROL_C); _CASE(DBG_EXCEPTION_HANDLED); _CASE(DBG_EXCEPTION_NOT_HANDLED); _CASE(DBG_NO_STATE_CHANGE); _CASE(DBG_PRINTEXCEPTION_C); _CASE(DBG_REPLY_LATER); _CASE(DBG_RIPEXCEPTION); _CASE(DBG_TERMINATE_PROCESS); _CASE(DBG_TERMINATE_THREAD); _CASE(DBG_UNABLE_TO_PROVIDE_HANDLE); _CASE(EPT_NT_CANT_CREATE); _CASE(EPT_NT_CANT_PERFORM_OP); _CASE(EPT_NT_INVALID_ENTRY); _CASE(EPT_NT_NOT_REGISTERED); _CASE(RPC_NT_ADDRESS_ERROR); _CASE(RPC_NT_ALREADY_LISTENING); _CASE(RPC_NT_ALREADY_REGISTERED); _CASE(RPC_NT_BAD_STUB_DATA); _CASE(RPC_NT_BINDING_HAS_NO_AUTH); _CASE(RPC_NT_BINDING_INCOMPLETE); _CASE(RPC_NT_BYTE_COUNT_TOO_SMALL); _CASE(RPC_NT_CALL_CANCELLED); _CASE(RPC_NT_CALL_FAILED); _CASE(RPC_NT_CALL_FAILED_DNE); _CASE(RPC_NT_CALL_IN_PROGRESS); _CASE(RPC_NT_CANNOT_SUPPORT); _CASE(RPC_NT_CANT_CREATE_ENDPOINT); _CASE(RPC_NT_COMM_FAILURE); _CASE(RPC_NT_DUPLICATE_ENDPOINT); _CASE(RPC_NT_ENTRY_ALREADY_EXISTS); _CASE(RPC_NT_ENTRY_NOT_FOUND); _CASE(RPC_NT_ENUM_VALUE_OUT_OF_RANGE); _CASE(RPC_NT_FP_DIV_ZERO); _CASE(RPC_NT_FP_OVERFLOW); _CASE(RPC_NT_FP_UNDERFLOW); _CASE(RPC_NT_GROUP_MEMBER_NOT_FOUND); _CASE(RPC_NT_INCOMPLETE_NAME); _CASE(RPC_NT_INTERFACE_NOT_FOUND); _CASE(RPC_NT_INTERNAL_ERROR); _CASE(RPC_NT_INVALID_ASYNC_CALL); _CASE(RPC_NT_INVALID_ASYNC_HANDLE); _CASE(RPC_NT_INVALID_AUTH_IDENTITY); _CASE(RPC_NT_INVALID_BINDING); _CASE(RPC_NT_INVALID_BOUND); _CASE(RPC_NT_INVALID_ENDPOINT_FORMAT); _CASE(RPC_NT_INVALID_ES_ACTION); _CASE(RPC_NT_INVALID_NAF_ID); _CASE(RPC_NT_INVALID_NAME_SYNTAX); _CASE(RPC_NT_INVALID_NETWORK_OPTIONS); _CASE(RPC_NT_INVALID_NET_ADDR); _CASE(RPC_NT_INVALID_OBJECT); _CASE(RPC_NT_INVALID_PIPE_OBJECT); _CASE(RPC_NT_INVALID_PIPE_OPERATION); _CASE(RPC_NT_INVALID_RPC_PROTSEQ); _CASE(RPC_NT_INVALID_STRING_BINDING); _CASE(RPC_NT_INVALID_STRING_UUID); _CASE(RPC_NT_INVALID_TAG); _CASE(RPC_NT_INVALID_TIMEOUT); _CASE(RPC_NT_INVALID_VERS_OPTION); _CASE(RPC_NT_MAX_CALLS_TOO_SMALL); _CASE(RPC_NT_NAME_SERVICE_UNAVAILABLE); _CASE(RPC_NT_NOTHING_TO_EXPORT); _CASE(RPC_NT_NOT_ALL_OBJS_UNEXPORTED); _CASE(RPC_NT_NOT_CANCELLED); _CASE(RPC_NT_NOT_LISTENING); _CASE(RPC_NT_NOT_RPC_ERROR); _CASE(RPC_NT_NO_BINDINGS); _CASE(RPC_NT_NO_CALL_ACTIVE); _CASE(RPC_NT_NO_CONTEXT_AVAILABLE); _CASE(RPC_NT_NO_ENDPOINT_FOUND); _CASE(RPC_NT_NO_ENTRY_NAME); _CASE(RPC_NT_NO_INTERFACES); _CASE(RPC_NT_NO_MORE_BINDINGS); _CASE(RPC_NT_NO_MORE_ENTRIES); _CASE(RPC_NT_NO_MORE_MEMBERS); _CASE(RPC_NT_NO_PRINC_NAME); _CASE(RPC_NT_NO_PROTSEQS); _CASE(RPC_NT_NO_PROTSEQS_REGISTERED); _CASE(RPC_NT_NULL_REF_POINTER); _CASE(RPC_NT_OBJECT_NOT_FOUND); _CASE(RPC_NT_OUT_OF_RESOURCES); _CASE(RPC_NT_PIPE_CLOSED); _CASE(RPC_NT_PIPE_DISCIPLINE_ERROR); _CASE(RPC_NT_PIPE_EMPTY); _CASE(RPC_NT_PROCNUM_OUT_OF_RANGE); _CASE(RPC_NT_PROTOCOL_ERROR); _CASE(RPC_NT_PROTSEQ_NOT_FOUND); _CASE(RPC_NT_PROTSEQ_NOT_SUPPORTED); _CASE(RPC_NT_SEC_PKG_ERROR); _CASE(RPC_NT_SEND_INCOMPLETE); _CASE(RPC_NT_SERVER_TOO_BUSY); _CASE(RPC_NT_SERVER_UNAVAILABLE); _CASE(RPC_NT_SS_CANNOT_GET_CALL_HANDLE); _CASE(RPC_NT_SS_CHAR_TRANS_OPEN_FAIL); _CASE(RPC_NT_SS_CHAR_TRANS_SHORT_FILE); _CASE(RPC_NT_SS_CONTEXT_DAMAGED); _CASE(RPC_NT_SS_CONTEXT_MISMATCH); _CASE(RPC_NT_SS_HANDLES_MISMATCH); _CASE(RPC_NT_SS_IN_NULL_CONTEXT); _CASE(RPC_NT_STRING_TOO_LONG); _CASE(RPC_NT_TYPE_ALREADY_REGISTERED); _CASE(RPC_NT_UNKNOWN_AUTHN_LEVEL); _CASE(RPC_NT_UNKNOWN_AUTHN_SERVICE); _CASE(RPC_NT_UNKNOWN_AUTHN_TYPE); _CASE(RPC_NT_UNKNOWN_AUTHZ_SERVICE); _CASE(RPC_NT_UNKNOWN_IF); _CASE(RPC_NT_UNKNOWN_MGR_TYPE); _CASE(RPC_NT_UNSUPPORTED_AUTHN_LEVEL); _CASE(RPC_NT_UNSUPPORTED_NAME_SYNTAX); _CASE(RPC_NT_UNSUPPORTED_TRANS_SYN); _CASE(RPC_NT_UNSUPPORTED_TYPE); _CASE(RPC_NT_UUID_LOCAL_ONLY); _CASE(RPC_NT_UUID_NO_ADDRESS); _CASE(RPC_NT_WRONG_ES_VERSION); _CASE(RPC_NT_WRONG_KIND_OF_BINDING); _CASE(RPC_NT_WRONG_PIPE_VERSION); _CASE(RPC_NT_WRONG_STUB_VERSION); _CASE(RPC_NT_ZERO_DIVIDE); _CASE(STATUS_ABANDONED_WAIT_0); _CASE(STATUS_ABANDONED_WAIT_63); _CASE(STATUS_ABIOS_INVALID_COMMAND); _CASE(STATUS_ABIOS_INVALID_LID); _CASE(STATUS_ABIOS_INVALID_SELECTOR); _CASE(STATUS_ABIOS_LID_ALREADY_OWNED); _CASE(STATUS_ABIOS_LID_NOT_EXIST); _CASE(STATUS_ABIOS_NOT_LID_OWNER); _CASE(STATUS_ABIOS_NOT_PRESENT); _CASE(STATUS_ABIOS_SELECTOR_NOT_AVAILABLE); _CASE(STATUS_ACCESS_DENIED); _CASE(STATUS_ACCESS_VIOLATION); _CASE(STATUS_ACCOUNT_DISABLED); _CASE(STATUS_ACCOUNT_EXPIRED); _CASE(STATUS_ACCOUNT_LOCKED_OUT); _CASE(STATUS_ACCOUNT_RESTRICTION); _CASE(STATUS_ACPI_ACQUIRE_GLOBAL_LOCK); _CASE(STATUS_ACPI_ADDRESS_NOT_MAPPED); _CASE(STATUS_ACPI_ALREADY_INITIALIZED); _CASE(STATUS_ACPI_ASSERT_FAILED); _CASE(STATUS_ACPI_FATAL); _CASE(STATUS_ACPI_HANDLER_COLLISION); _CASE(STATUS_ACPI_INCORRECT_ARGUMENT_COUNT); _CASE(STATUS_ACPI_INVALID_ACCESS_SIZE); _CASE(STATUS_ACPI_INVALID_ARGTYPE); _CASE(STATUS_ACPI_INVALID_ARGUMENT); _CASE(STATUS_ACPI_INVALID_DATA); _CASE(STATUS_ACPI_INVALID_EVENTTYPE); _CASE(STATUS_ACPI_INVALID_INDEX); _CASE(STATUS_ACPI_INVALID_MUTEX_LEVEL); _CASE(STATUS_ACPI_INVALID_OBJTYPE); _CASE(STATUS_ACPI_INVALID_OPCODE); _CASE(STATUS_ACPI_INVALID_REGION); _CASE(STATUS_ACPI_INVALID_SUPERNAME); _CASE(STATUS_ACPI_INVALID_TABLE); _CASE(STATUS_ACPI_INVALID_TARGETTYPE); _CASE(STATUS_ACPI_MUTEX_NOT_OWNED); _CASE(STATUS_ACPI_MUTEX_NOT_OWNER); _CASE(STATUS_ACPI_NOT_INITIALIZED); _CASE(STATUS_ACPI_POWER_REQUEST_FAILED); _CASE(STATUS_ACPI_REG_HANDLER_FAILED); _CASE(STATUS_ACPI_RS_ACCESS); _CASE(STATUS_ACPI_STACK_OVERFLOW); _CASE(STATUS_ADAPTER_HARDWARE_ERROR); _CASE(STATUS_ADDRESS_ALREADY_ASSOCIATED); _CASE(STATUS_ADDRESS_ALREADY_EXISTS); _CASE(STATUS_ADDRESS_CLOSED); _CASE(STATUS_ADDRESS_NOT_ASSOCIATED); _CASE(STATUS_AGENTS_EXHAUSTED); _CASE(STATUS_ALERTED); _CASE(STATUS_ALIAS_EXISTS); _CASE(STATUS_ALLOCATE_BUCKET); _CASE(STATUS_ALLOTTED_SPACE_EXCEEDED); _CASE(STATUS_ALREADY_COMMITTED); _CASE(STATUS_ALREADY_DISCONNECTED); _CASE(STATUS_ALREADY_WIN32); _CASE(STATUS_APP_INIT_FAILURE); _CASE(STATUS_ARBITRATION_UNHANDLED); _CASE(STATUS_ARRAY_BOUNDS_EXCEEDED); _CASE(STATUS_AUDIT_FAILED); _CASE(STATUS_BACKUP_CONTROLLER); _CASE(STATUS_BAD_COMPRESSION_BUFFER); _CASE(STATUS_BAD_CURRENT_DIRECTORY); _CASE(STATUS_BAD_DESCRIPTOR_FORMAT); _CASE(STATUS_BAD_DEVICE_TYPE); _CASE(STATUS_BAD_DLL_ENTRYPOINT); _CASE(STATUS_BAD_FUNCTION_TABLE); _CASE(STATUS_BAD_IMPERSONATION_LEVEL); _CASE(STATUS_BAD_INHERITANCE_ACL); _CASE(STATUS_BAD_INITIAL_PC); _CASE(STATUS_BAD_INITIAL_STACK); _CASE(STATUS_BAD_LOGON_SESSION_STATE); _CASE(STATUS_BAD_MASTER_BOOT_RECORD); _CASE(STATUS_BAD_NETWORK_NAME); _CASE(STATUS_BAD_NETWORK_PATH); _CASE(STATUS_BAD_REMOTE_ADAPTER); _CASE(STATUS_BAD_SERVICE_ENTRYPOINT); _CASE(STATUS_BAD_STACK); _CASE(STATUS_BAD_TOKEN_TYPE); _CASE(STATUS_BAD_VALIDATION_CLASS); _CASE(STATUS_BAD_WORKING_SET_LIMIT); _CASE(STATUS_BEGINNING_OF_MEDIA); _CASE(STATUS_BIOS_FAILED_TO_CONNECT_INTERRUPT); _CASE(STATUS_BREAKPOINT); _CASE(STATUS_BUFFER_ALL_ZEROS); _CASE(STATUS_BUFFER_OVERFLOW); _CASE(STATUS_BUFFER_TOO_SMALL); _CASE(STATUS_BUS_RESET); _CASE(STATUS_CACHE_PAGE_LOCKED); _CASE(STATUS_CANCELLED); _CASE(STATUS_CANNOT_DELETE); _CASE(STATUS_CANNOT_IMPERSONATE); _CASE(STATUS_CANNOT_LOAD_REGISTRY_FILE); _CASE(STATUS_CANT_ACCESS_DOMAIN_INFO); _CASE(STATUS_CANT_DISABLE_MANDATORY); _CASE(STATUS_CANT_ENABLE_DENY_ONLY); _CASE(STATUS_CANT_OPEN_ANONYMOUS); _CASE(STATUS_CANT_TERMINATE_SELF); _CASE(STATUS_CANT_WAIT); _CASE(STATUS_CARDBUS_NOT_SUPPORTED); _CASE(STATUS_CHECKING_FILE_SYSTEM); _CASE(STATUS_CHILD_MUST_BE_VOLATILE); _CASE(STATUS_CLIENT_SERVER_PARAMETERS_INVALID); _CASE(STATUS_COMMITMENT_LIMIT); _CASE(STATUS_COMMITMENT_MINIMUM); _CASE(STATUS_CONFLICTING_ADDRESSES); _CASE(STATUS_CONNECTION_ABORTED); _CASE(STATUS_CONNECTION_ACTIVE); _CASE(STATUS_CONNECTION_COUNT_LIMIT); _CASE(STATUS_CONNECTION_DISCONNECTED); _CASE(STATUS_CONNECTION_INVALID); _CASE(STATUS_CONNECTION_IN_USE); _CASE(STATUS_CONNECTION_REFUSED); _CASE(STATUS_CONNECTION_RESET); _CASE(STATUS_CONTROL_C_EXIT); _CASE(STATUS_CONVERT_TO_LARGE); _CASE(STATUS_CORRUPT_SYSTEM_FILE); _CASE(STATUS_COULD_NOT_INTERPRET); _CASE(STATUS_CRASH_DUMP); _CASE(STATUS_CRC_ERROR); _CASE(STATUS_CTL_FILE_NOT_SUPPORTED); _CASE(STATUS_CTX_BAD_VIDEO_MODE); _CASE(STATUS_CTX_CDM_CONNECT); _CASE(STATUS_CTX_CDM_DISCONNECT); _CASE(STATUS_CTX_CLIENT_LICENSE_IN_USE); _CASE(STATUS_CTX_CLIENT_LICENSE_NOT_SET); _CASE(STATUS_CTX_CLIENT_QUERY_TIMEOUT); _CASE(STATUS_CTX_CLOSE_PENDING); _CASE(STATUS_CTX_CONSOLE_CONNECT); _CASE(STATUS_CTX_CONSOLE_DISCONNECT); _CASE(STATUS_CTX_GRAPHICS_INVALID); _CASE(STATUS_CTX_INVALID_MODEMNAME); _CASE(STATUS_CTX_INVALID_PD); _CASE(STATUS_CTX_INVALID_WD); _CASE(STATUS_CTX_LICENSE_CLIENT_INVALID); _CASE(STATUS_CTX_LICENSE_EXPIRED); _CASE(STATUS_CTX_LICENSE_NOT_AVAILABLE); _CASE(STATUS_CTX_MODEM_INF_NOT_FOUND); _CASE(STATUS_CTX_MODEM_RESPONSE_BUSY); _CASE(STATUS_CTX_MODEM_RESPONSE_NO_CARRIER); _CASE(STATUS_CTX_MODEM_RESPONSE_NO_DIALTONE); _CASE(STATUS_CTX_MODEM_RESPONSE_TIMEOUT); _CASE(STATUS_CTX_MODEM_RESPONSE_VOICE); _CASE(STATUS_CTX_NOT_CONSOLE); _CASE(STATUS_CTX_NO_OUTBUF); _CASE(STATUS_CTX_PD_NOT_FOUND); _CASE(STATUS_CTX_RESPONSE_ERROR); _CASE(STATUS_CTX_SHADOW_DENIED); _CASE(STATUS_CTX_SHADOW_DISABLED); _CASE(STATUS_CTX_SHADOW_INVALID); _CASE(STATUS_CTX_TD_ERROR); _CASE(STATUS_CTX_WD_NOT_FOUND); _CASE(STATUS_CTX_WINSTATION_ACCESS_DENIED); _CASE(STATUS_CTX_WINSTATION_BUSY); _CASE(STATUS_CTX_WINSTATION_NAME_COLLISION); _CASE(STATUS_CTX_WINSTATION_NAME_INVALID); _CASE(STATUS_CTX_WINSTATION_NOT_FOUND); _CASE(STATUS_DATATYPE_MISALIGNMENT); _CASE(STATUS_DATATYPE_MISALIGNMENT_ERROR); _CASE(STATUS_DATA_ERROR); _CASE(STATUS_DATA_LATE_ERROR); _CASE(STATUS_DATA_NOT_ACCEPTED); _CASE(STATUS_DATA_OVERRUN); _CASE(STATUS_DEBUG_ATTACH_FAILED); _CASE(STATUS_DECRYPTION_FAILED); _CASE(STATUS_DELETE_PENDING); _CASE(STATUS_DESTINATION_ELEMENT_FULL); _CASE(STATUS_DEVICE_ALREADY_ATTACHED); _CASE(STATUS_DEVICE_BUSY); _CASE(STATUS_DEVICE_CONFIGURATION_ERROR); _CASE(STATUS_DEVICE_DATA_ERROR); _CASE(STATUS_DEVICE_DOES_NOT_EXIST); _CASE(STATUS_DEVICE_DOOR_OPEN); _CASE(STATUS_DEVICE_NOT_CONNECTED); _CASE(STATUS_DEVICE_NOT_PARTITIONED); _CASE(STATUS_DEVICE_NOT_READY); _CASE(STATUS_DEVICE_OFF_LINE); _CASE(STATUS_DEVICE_PAPER_EMPTY); _CASE(STATUS_DEVICE_POWERED_OFF); _CASE(STATUS_DEVICE_POWER_FAILURE); _CASE(STATUS_DEVICE_PROTOCOL_ERROR); _CASE(STATUS_DEVICE_REMOVED); _CASE(STATUS_DEVICE_REQUIRES_CLEANING); _CASE(STATUS_DFS_EXIT_PATH_FOUND); _CASE(STATUS_DFS_UNAVAILABLE); _CASE(STATUS_DIRECTORY_IS_A_REPARSE_POINT); _CASE(STATUS_DIRECTORY_NOT_EMPTY); _CASE(STATUS_DIRECTORY_SERVICE_REQUIRED); _CASE(STATUS_DISK_CORRUPT_ERROR); _CASE(STATUS_DISK_FULL); _CASE(STATUS_DISK_OPERATION_FAILED); _CASE(STATUS_DISK_RECALIBRATE_FAILED); _CASE(STATUS_DISK_RESET_FAILED); _CASE(STATUS_DLL_INIT_FAILED); _CASE(STATUS_DLL_INIT_FAILED_LOGOFF); _CASE(STATUS_DLL_NOT_FOUND); _CASE(STATUS_DOMAIN_CONTROLLER_NOT_FOUND); _CASE(STATUS_DOMAIN_CTRLR_CONFIG_ERROR); _CASE(STATUS_DOMAIN_EXISTS); _CASE(STATUS_DOMAIN_LIMIT_EXCEEDED); _CASE(STATUS_DOMAIN_TRUST_INCONSISTENT); _CASE(STATUS_DRIVER_CANCEL_TIMEOUT); _CASE(STATUS_DRIVER_ENTRYPOINT_NOT_FOUND); _CASE(STATUS_DRIVER_FAILED_SLEEP); _CASE(STATUS_DRIVER_INTERNAL_ERROR); _CASE(STATUS_DRIVER_ORDINAL_NOT_FOUND); _CASE(STATUS_DRIVER_UNABLE_TO_LOAD); _CASE(STATUS_DS_ADMIN_LIMIT_EXCEEDED); _CASE(STATUS_DS_ATTRIBUTE_OR_VALUE_EXISTS); _CASE(STATUS_DS_ATTRIBUTE_TYPE_UNDEFINED); _CASE(STATUS_DS_BUSY); _CASE(STATUS_DS_CANT_MOD_OBJ_CLASS); _CASE(STATUS_DS_CANT_MOD_PRIMARYGROUPID); _CASE(STATUS_DS_CANT_ON_NON_LEAF); _CASE(STATUS_DS_CANT_ON_RDN); _CASE(STATUS_DS_CANT_START); _CASE(STATUS_DS_CROSS_DOM_MOVE_FAILED); _CASE(STATUS_DS_GC_NOT_AVAILABLE); _CASE(STATUS_DS_GC_REQUIRED); _CASE(STATUS_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER); _CASE(STATUS_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER); _CASE(STATUS_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER); _CASE(STATUS_DS_HAVE_PRIMARY_MEMBERS); _CASE(STATUS_DS_INCORRECT_ROLE_OWNER); _CASE(STATUS_DS_INIT_FAILURE); _CASE(STATUS_DS_INVALID_ATTRIBUTE_SYNTAX); _CASE(STATUS_DS_INVALID_GROUP_TYPE); _CASE(STATUS_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER); _CASE(STATUS_DS_LOCAL_MEMBER_OF_LOCAL_ONLY); _CASE(STATUS_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED); _CASE(STATUS_DS_MEMBERSHIP_EVALUATED_LOCALLY); _CASE(STATUS_DS_NO_ATTRIBUTE_OR_VALUE); _CASE(STATUS_DS_NO_FPO_IN_UNIVERSAL_GROUPS); _CASE(STATUS_DS_NO_MORE_RIDS); _CASE(STATUS_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN); _CASE(STATUS_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN); _CASE(STATUS_DS_NO_RIDS_ALLOCATED); _CASE(STATUS_DS_OBJ_CLASS_VIOLATION); _CASE(STATUS_DS_RIDMGR_INIT_ERROR); _CASE(STATUS_DS_SAM_INIT_FAILURE); _CASE(STATUS_DS_SENSITIVE_GROUP_VIOLATION); _CASE(STATUS_DS_UNAVAILABLE); _CASE(STATUS_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER); _CASE(STATUS_DUPLICATE_NAME); _CASE(STATUS_DUPLICATE_OBJECTID); _CASE(STATUS_EAS_NOT_SUPPORTED); _CASE(STATUS_EA_CORRUPT_ERROR); _CASE(STATUS_EA_LIST_INCONSISTENT); _CASE(STATUS_EA_TOO_LARGE); _CASE(STATUS_ENCRYPTION_FAILED); _CASE(STATUS_END_OF_FILE); _CASE(STATUS_END_OF_MEDIA); _CASE(STATUS_ENTRYPOINT_NOT_FOUND); _CASE(STATUS_EOM_OVERFLOW); _CASE(STATUS_EVALUATION_EXPIRATION); _CASE(STATUS_EVENTLOG_CANT_START); _CASE(STATUS_EVENTLOG_FILE_CHANGED); _CASE(STATUS_EVENTLOG_FILE_CORRUPT); _CASE(STATUS_EVENT_DONE); _CASE(STATUS_EVENT_PENDING); _CASE(STATUS_EXTRANEOUS_INFORMATION); _CASE(STATUS_FAIL_CHECK); _CASE(STATUS_FATAL_APP_EXIT); _CASE(STATUS_FILEMARK_DETECTED); _CASE(STATUS_FILES_OPEN); _CASE(STATUS_FILE_CLOSED); _CASE(STATUS_FILE_CORRUPT_ERROR); _CASE(STATUS_FILE_DELETED); _CASE(STATUS_FILE_ENCRYPTED); _CASE(STATUS_FILE_FORCED_CLOSED); _CASE(STATUS_FILE_INVALID); _CASE(STATUS_FILE_IS_A_DIRECTORY); _CASE(STATUS_FILE_IS_OFFLINE); _CASE(STATUS_FILE_LOCK_CONFLICT); _CASE(STATUS_FILE_NOT_ENCRYPTED); _CASE(STATUS_FILE_RENAMED); _CASE(STATUS_FLOAT_DENORMAL_OPERAND); _CASE(STATUS_FLOAT_DIVIDE_BY_ZERO); _CASE(STATUS_FLOAT_INEXACT_RESULT); _CASE(STATUS_FLOAT_INVALID_OPERATION); _CASE(STATUS_FLOAT_MULTIPLE_FAULTS); _CASE(STATUS_FLOAT_MULTIPLE_TRAPS); _CASE(STATUS_FLOAT_OVERFLOW); _CASE(STATUS_FLOAT_STACK_CHECK); _CASE(STATUS_FLOAT_UNDERFLOW); _CASE(STATUS_FLOPPY_BAD_REGISTERS); _CASE(STATUS_FLOPPY_ID_MARK_NOT_FOUND); _CASE(STATUS_FLOPPY_UNKNOWN_ERROR); _CASE(STATUS_FLOPPY_VOLUME); _CASE(STATUS_FLOPPY_WRONG_CYLINDER); _CASE(STATUS_FOUND_OUT_OF_SCOPE); _CASE(STATUS_FREE_VM_NOT_AT_BASE); _CASE(STATUS_FS_DRIVER_REQUIRED); _CASE(STATUS_FT_MISSING_MEMBER); _CASE(STATUS_FT_ORPHANING); _CASE(STATUS_FT_READ_RECOVERY_FROM_BACKUP); _CASE(STATUS_FT_WRITE_RECOVERY); _CASE(STATUS_FULLSCREEN_MODE); _CASE(STATUS_GENERIC_NOT_MAPPED); _CASE(STATUS_GRACEFUL_DISCONNECT); _CASE(STATUS_GROUP_EXISTS); _CASE(STATUS_GUARD_PAGE_VIOLATION); _CASE(STATUS_GUIDS_EXHAUSTED); _CASE(STATUS_GUID_SUBSTITUTION_MADE); _CASE(STATUS_HANDLES_CLOSED); _CASE(STATUS_HANDLE_NOT_CLOSABLE); _CASE(STATUS_HOST_UNREACHABLE); _CASE(STATUS_ILLEGAL_CHARACTER); _CASE(STATUS_ILLEGAL_DLL_RELOCATION); _CASE(STATUS_ILLEGAL_ELEMENT_ADDRESS); _CASE(STATUS_ILLEGAL_FLOAT_CONTEXT); _CASE(STATUS_ILLEGAL_FUNCTION); _CASE(STATUS_ILLEGAL_INSTRUCTION); _CASE(STATUS_ILL_FORMED_PASSWORD); _CASE(STATUS_ILL_FORMED_SERVICE_ENTRY); _CASE(STATUS_IMAGE_ALREADY_LOADED); _CASE(STATUS_IMAGE_CHECKSUM_MISMATCH); _CASE(STATUS_IMAGE_MACHINE_TYPE_MISMATCH); _CASE(STATUS_IMAGE_MACHINE_TYPE_MISMATCH_EXE); _CASE(STATUS_IMAGE_MP_UP_MISMATCH); _CASE(STATUS_IMAGE_NOT_AT_BASE); _CASE(STATUS_INCOMPATIBLE_FILE_MAP); _CASE(STATUS_INFO_LENGTH_MISMATCH); _CASE(STATUS_INSTANCE_NOT_AVAILABLE); _CASE(STATUS_INSTRUCTION_MISALIGNMENT); _CASE(STATUS_INSUFFICIENT_LOGON_INFO); _CASE(STATUS_INSUFFICIENT_POWER); _CASE(STATUS_INSUFFICIENT_RESOURCES); _CASE(STATUS_INSUFF_SERVER_RESOURCES); _CASE(STATUS_INTEGER_DIVIDE_BY_ZERO); _CASE(STATUS_INTEGER_OVERFLOW); _CASE(STATUS_INTERNAL_DB_CORRUPTION); _CASE(STATUS_INTERNAL_DB_ERROR); _CASE(STATUS_INTERNAL_ERROR); _CASE(STATUS_INVALID_ACCOUNT_NAME); _CASE(STATUS_INVALID_ACL); _CASE(STATUS_INVALID_ADDRESS); _CASE(STATUS_INVALID_ADDRESS_COMPONENT); _CASE(STATUS_INVALID_ADDRESS_WILDCARD); _CASE(STATUS_INVALID_BLOCK_LENGTH); _CASE(STATUS_INVALID_BUFFER_SIZE); _CASE(STATUS_INVALID_CID); _CASE(STATUS_INVALID_COMPUTER_NAME); _CASE(STATUS_INVALID_CONNECTION); _CASE(STATUS_INVALID_DEVICE_REQUEST); _CASE(STATUS_INVALID_DEVICE_STATE); _CASE(STATUS_INVALID_DISPOSITION); _CASE(STATUS_INVALID_DOMAIN_ROLE); _CASE(STATUS_INVALID_DOMAIN_STATE); _CASE(STATUS_INVALID_EA_FLAG); _CASE(STATUS_INVALID_EA_NAME); _CASE(STATUS_INVALID_FILE_FOR_SECTION); _CASE(STATUS_INVALID_GROUP_ATTRIBUTES); _CASE(STATUS_INVALID_HANDLE); _CASE(STATUS_INVALID_HW_PROFILE); _CASE(STATUS_INVALID_ID_AUTHORITY); _CASE(STATUS_INVALID_IMAGE_FORMAT); _CASE(STATUS_INVALID_IMAGE_LE_FORMAT); _CASE(STATUS_INVALID_IMAGE_NE_FORMAT); _CASE(STATUS_INVALID_IMAGE_NOT_MZ); _CASE(STATUS_INVALID_IMAGE_PROTECT); _CASE(STATUS_INVALID_IMAGE_WIN_16); _CASE(STATUS_INVALID_INFO_CLASS); _CASE(STATUS_INVALID_LDT_DESCRIPTOR); _CASE(STATUS_INVALID_LDT_OFFSET); _CASE(STATUS_INVALID_LDT_SIZE); _CASE(STATUS_INVALID_LEVEL); _CASE(STATUS_INVALID_LOCK_SEQUENCE); _CASE(STATUS_INVALID_LOGON_HOURS); _CASE(STATUS_INVALID_LOGON_TYPE); _CASE(STATUS_INVALID_MEMBER); _CASE(STATUS_INVALID_NETWORK_RESPONSE); _CASE(STATUS_INVALID_OPLOCK_PROTOCOL); _CASE(STATUS_INVALID_OWNER); _CASE(STATUS_INVALID_PAGE_PROTECTION); _CASE(STATUS_INVALID_PARAMETER); _CASE(STATUS_INVALID_PARAMETER_1); _CASE(STATUS_INVALID_PARAMETER_10); _CASE(STATUS_INVALID_PARAMETER_11); _CASE(STATUS_INVALID_PARAMETER_12); _CASE(STATUS_INVALID_PARAMETER_2); _CASE(STATUS_INVALID_PARAMETER_3); _CASE(STATUS_INVALID_PARAMETER_4); _CASE(STATUS_INVALID_PARAMETER_5); _CASE(STATUS_INVALID_PARAMETER_6); _CASE(STATUS_INVALID_PARAMETER_7); _CASE(STATUS_INVALID_PARAMETER_8); _CASE(STATUS_INVALID_PARAMETER_9); _CASE(STATUS_INVALID_PARAMETER_MIX); _CASE(STATUS_INVALID_PIPE_STATE); _CASE(STATUS_INVALID_PLUGPLAY_DEVICE_PATH); _CASE(STATUS_INVALID_PORT_ATTRIBUTES); _CASE(STATUS_INVALID_PORT_HANDLE); _CASE(STATUS_INVALID_PRIMARY_GROUP); _CASE(STATUS_INVALID_QUOTA_LOWER); _CASE(STATUS_INVALID_READ_MODE); _CASE(STATUS_INVALID_SECURITY_DESCR); _CASE(STATUS_INVALID_SERVER_STATE); _CASE(STATUS_INVALID_SID); _CASE(STATUS_INVALID_SUB_AUTHORITY); _CASE(STATUS_INVALID_SYSTEM_SERVICE); _CASE(STATUS_INVALID_UNWIND_TARGET); _CASE(STATUS_INVALID_USER_BUFFER); _CASE(STATUS_INVALID_VARIANT); _CASE(STATUS_INVALID_VIEW_SIZE); _CASE(STATUS_INVALID_VOLUME_LABEL); _CASE(STATUS_INVALID_WORKSTATION); _CASE(STATUS_IN_PAGE_ERROR); _CASE(STATUS_IO_DEVICE_ERROR); _CASE(STATUS_IO_PRIVILEGE_FAILED); _CASE(STATUS_IO_REPARSE_DATA_INVALID); _CASE(STATUS_IO_REPARSE_TAG_INVALID); _CASE(STATUS_IO_REPARSE_TAG_MISMATCH); _CASE(STATUS_IO_REPARSE_TAG_NOT_HANDLED); _CASE(STATUS_IO_TIMEOUT); _CASE(STATUS_IP_ADDRESS_CONFLICT1); _CASE(STATUS_IP_ADDRESS_CONFLICT2); _CASE(STATUS_JOURNAL_DELETE_IN_PROGRESS); _CASE(STATUS_JOURNAL_ENTRY_DELETED); _CASE(STATUS_JOURNAL_NOT_ACTIVE); _CASE(STATUS_KERNEL_APC); _CASE(STATUS_KEY_DELETED); _CASE(STATUS_KEY_HAS_CHILDREN); _CASE(STATUS_LAST_ADMIN); _CASE(STATUS_LICENSE_QUOTA_EXCEEDED); _CASE(STATUS_LICENSE_VIOLATION); _CASE(STATUS_LINK_FAILED); _CASE(STATUS_LINK_TIMEOUT); _CASE(STATUS_LM_CROSS_ENCRYPTION_REQUIRED); _CASE(STATUS_LOCAL_DISCONNECT); _CASE(STATUS_LOCAL_USER_SESSION_KEY); _CASE(STATUS_LOCK_NOT_GRANTED); _CASE(STATUS_LOGIN_TIME_RESTRICTION); _CASE(STATUS_LOGIN_WKSTA_RESTRICTION); _CASE(STATUS_LOGON_FAILURE); _CASE(STATUS_LOGON_NOT_GRANTED); _CASE(STATUS_LOGON_SERVER_CONFLICT); _CASE(STATUS_LOGON_SESSION_COLLISION); _CASE(STATUS_LOGON_SESSION_EXISTS); _CASE(STATUS_LOGON_TYPE_NOT_GRANTED); _CASE(STATUS_LOG_FILE_FULL); _CASE(STATUS_LOG_HARD_ERROR); _CASE(STATUS_LONGJUMP); _CASE(STATUS_LOST_WRITEBEHIND_DATA); _CASE(STATUS_LPC_REPLY_LOST); _CASE(STATUS_LUIDS_EXHAUSTED); _CASE(STATUS_MAGAZINE_NOT_PRESENT); _CASE(STATUS_MAPPED_ALIGNMENT); _CASE(STATUS_MAPPED_FILE_SIZE_ZERO); _CASE(STATUS_MARSHALL_OVERFLOW); _CASE(STATUS_MEDIA_CHANGED); _CASE(STATUS_MEDIA_CHECK); _CASE(STATUS_MEDIA_WRITE_PROTECTED); _CASE(STATUS_MEMBERS_PRIMARY_GROUP); _CASE(STATUS_MEMBER_IN_ALIAS); _CASE(STATUS_MEMBER_IN_GROUP); _CASE(STATUS_MEMBER_NOT_IN_ALIAS); _CASE(STATUS_MEMBER_NOT_IN_GROUP); _CASE(STATUS_MEMORY_NOT_ALLOCATED); _CASE(STATUS_MESSAGE_NOT_FOUND); _CASE(STATUS_MISSING_SYSTEMFILE); _CASE(STATUS_MORE_ENTRIES); _CASE(STATUS_MORE_PROCESSING_REQUIRED); _CASE(STATUS_MP_PROCESSOR_MISMATCH); _CASE(STATUS_MULTIPLE_FAULT_VIOLATION); _CASE(STATUS_MUTANT_LIMIT_EXCEEDED); _CASE(STATUS_MUTANT_NOT_OWNED); _CASE(STATUS_MUTUAL_AUTHENTICATION_FAILED); _CASE(STATUS_NAME_TOO_LONG); _CASE(STATUS_NETLOGON_NOT_STARTED); _CASE(STATUS_NETWORK_ACCESS_DENIED); _CASE(STATUS_NETWORK_BUSY); _CASE(STATUS_NETWORK_CREDENTIAL_CONFLICT); _CASE(STATUS_NETWORK_NAME_DELETED); _CASE(STATUS_NETWORK_UNREACHABLE); _CASE(STATUS_NET_WRITE_FAULT); _CASE(STATUS_NOINTERFACE); _CASE(STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT); _CASE(STATUS_NOLOGON_SERVER_TRUST_ACCOUNT); _CASE(STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT); _CASE(STATUS_NONCONTINUABLE_EXCEPTION); _CASE(STATUS_NONEXISTENT_EA_ENTRY); _CASE(STATUS_NONEXISTENT_SECTOR); _CASE(STATUS_NONE_MAPPED); _CASE(STATUS_NOTIFY_CLEANUP); _CASE(STATUS_NOTIFY_ENUM_DIR); _CASE(STATUS_NOT_ALL_ASSIGNED); _CASE(STATUS_NOT_A_DIRECTORY); _CASE(STATUS_NOT_A_REPARSE_POINT); _CASE(STATUS_NOT_CLIENT_SESSION); _CASE(STATUS_NOT_COMMITTED); _CASE(STATUS_NOT_EXPORT_FORMAT); _CASE(STATUS_NOT_FOUND); _CASE(STATUS_NOT_IMPLEMENTED); _CASE(STATUS_NOT_LOCKED); _CASE(STATUS_NOT_LOGON_PROCESS); _CASE(STATUS_NOT_MAPPED_DATA); _CASE(STATUS_NOT_MAPPED_VIEW); _CASE(STATUS_NOT_REGISTRY_FILE); _CASE(STATUS_NOT_SAME_DEVICE); _CASE(STATUS_NOT_SERVER_SESSION); _CASE(STATUS_NOT_SUPPORTED); _CASE(STATUS_NOT_SUPPORTED_ON_SBS); _CASE(STATUS_NOT_TINY_STREAM); _CASE(STATUS_NO_BROWSER_SERVERS_FOUND); _CASE(STATUS_NO_CALLBACK_ACTIVE); _CASE(STATUS_NO_DATA_DETECTED); _CASE(STATUS_NO_EAS_ON_FILE); _CASE(STATUS_NO_EFS); _CASE(STATUS_NO_EVENT_PAIR); _CASE(STATUS_NO_GUID_TRANSLATION); _CASE(STATUS_NO_IMPERSONATION_TOKEN); _CASE(STATUS_NO_INHERITANCE); _CASE(STATUS_NO_LDT); _CASE(STATUS_NO_LOGON_SERVERS); _CASE(STATUS_NO_LOG_SPACE); _CASE(STATUS_NO_MATCH); _CASE(STATUS_NO_MEDIA); _CASE(STATUS_NO_MEDIA_IN_DEVICE); _CASE(STATUS_NO_MEMORY); _CASE(STATUS_NO_MORE_EAS); _CASE(STATUS_NO_MORE_ENTRIES); _CASE(STATUS_NO_MORE_FILES); _CASE(STATUS_NO_MORE_MATCHES); _CASE(STATUS_NO_PAGEFILE); _CASE(STATUS_NO_QUOTAS_FOR_ACCOUNT); _CASE(STATUS_NO_RECOVERY_POLICY); _CASE(STATUS_NO_SECURITY_ON_OBJECT); _CASE(STATUS_NO_SPOOL_SPACE); _CASE(STATUS_NO_SUCH_ALIAS); _CASE(STATUS_NO_SUCH_DEVICE); _CASE(STATUS_NO_SUCH_DOMAIN); _CASE(STATUS_NO_SUCH_FILE); _CASE(STATUS_NO_SUCH_GROUP); _CASE(STATUS_NO_SUCH_LOGON_SESSION); _CASE(STATUS_NO_SUCH_MEMBER); _CASE(STATUS_NO_SUCH_PACKAGE); _CASE(STATUS_NO_SUCH_PRIVILEGE); _CASE(STATUS_NO_SUCH_USER); _CASE(STATUS_NO_TOKEN); _CASE(STATUS_NO_TRACKING_SERVICE); _CASE(STATUS_NO_TRUST_LSA_SECRET); _CASE(STATUS_NO_TRUST_SAM_ACCOUNT); _CASE(STATUS_NO_USER_KEYS); _CASE(STATUS_NO_USER_SESSION_KEY); _CASE(STATUS_NO_YIELD_PERFORMED); _CASE(STATUS_NT_CROSS_ENCRYPTION_REQUIRED); _CASE(STATUS_NULL_LM_PASSWORD); _CASE(STATUS_OBJECTID_EXISTS); _CASE(STATUS_OBJECT_NAME_COLLISION); _CASE(STATUS_OBJECT_NAME_EXISTS); _CASE(STATUS_OBJECT_NAME_INVALID); _CASE(STATUS_OBJECT_NAME_NOT_FOUND); _CASE(STATUS_OBJECT_PATH_INVALID); _CASE(STATUS_OBJECT_PATH_NOT_FOUND); _CASE(STATUS_OBJECT_PATH_SYNTAX_BAD); _CASE(STATUS_OBJECT_TYPE_MISMATCH); _CASE(STATUS_ONLY_IF_CONNECTED); _CASE(STATUS_OPEN_FAILED); _CASE(STATUS_OPLOCK_BREAK_IN_PROGRESS); _CASE(STATUS_OPLOCK_NOT_GRANTED); _CASE(STATUS_ORDINAL_NOT_FOUND); _CASE(STATUS_PAGEFILE_CREATE_FAILED); _CASE(STATUS_PAGEFILE_QUOTA); _CASE(STATUS_PAGEFILE_QUOTA_EXCEEDED); _CASE(STATUS_PAGE_FAULT_COPY_ON_WRITE); _CASE(STATUS_PAGE_FAULT_DEMAND_ZERO); _CASE(STATUS_PAGE_FAULT_GUARD_PAGE); _CASE(STATUS_PAGE_FAULT_PAGING_FILE); _CASE(STATUS_PAGE_FAULT_TRANSITION); _CASE(STATUS_PARITY_ERROR); _CASE(STATUS_PARTIAL_COPY); _CASE(STATUS_PARTITION_FAILURE); _CASE(STATUS_PASSWORD_EXPIRED); _CASE(STATUS_PASSWORD_MUST_CHANGE); _CASE(STATUS_PASSWORD_RESTRICTION); _CASE(STATUS_PATH_NOT_COVERED); _CASE(STATUS_PENDING); _CASE(STATUS_PIPE_BROKEN); _CASE(STATUS_PIPE_BUSY); _CASE(STATUS_PIPE_CLOSING); _CASE(STATUS_PIPE_CONNECTED); _CASE(STATUS_PIPE_DISCONNECTED); _CASE(STATUS_PIPE_EMPTY); _CASE(STATUS_PIPE_LISTENING); _CASE(STATUS_PIPE_NOT_AVAILABLE); _CASE(STATUS_PLUGPLAY_NO_DEVICE); _CASE(STATUS_PNP_BAD_MPS_TABLE); _CASE(STATUS_PNP_IRQ_TRANSLATION_FAILED); _CASE(STATUS_PNP_REBOOT_REQUIRED); _CASE(STATUS_PNP_RESTART_ENUMERATION); _CASE(STATUS_PNP_TRANSLATION_FAILED); _CASE(STATUS_POLICY_OBJECT_NOT_FOUND); _CASE(STATUS_POLICY_ONLY_IN_DS); _CASE(STATUS_PORT_ALREADY_SET); _CASE(STATUS_PORT_CONNECTION_REFUSED); _CASE(STATUS_PORT_DISCONNECTED); _CASE(STATUS_PORT_MESSAGE_TOO_LONG); _CASE(STATUS_PORT_UNREACHABLE); _CASE(STATUS_POSSIBLE_DEADLOCK); _CASE(STATUS_POWER_STATE_INVALID); _CASE(STATUS_PREDEFINED_HANDLE); _CASE(STATUS_PRIMARY_TRANSPORT_CONNECT_FAILED); _CASE(STATUS_PRINT_CANCELLED); _CASE(STATUS_PRINT_QUEUE_FULL); _CASE(STATUS_PRIVILEGED_INSTRUCTION); _CASE(STATUS_PRIVILEGE_NOT_HELD); _CASE(STATUS_PROCEDURE_NOT_FOUND); _CASE(STATUS_PROCESS_IS_TERMINATING); _CASE(STATUS_PROFILING_AT_LIMIT); _CASE(STATUS_PROFILING_NOT_STARTED); _CASE(STATUS_PROFILING_NOT_STOPPED); _CASE(STATUS_PROPSET_NOT_FOUND); _CASE(STATUS_PROTOCOL_UNREACHABLE); _CASE(STATUS_PWD_HISTORY_CONFLICT); _CASE(STATUS_PWD_TOO_RECENT); _CASE(STATUS_PWD_TOO_SHORT); _CASE(STATUS_QUOTA_EXCEEDED); _CASE(STATUS_QUOTA_LIST_INCONSISTENT); _CASE(STATUS_RANGE_LIST_CONFLICT); _CASE(STATUS_RANGE_NOT_FOUND); _CASE(STATUS_RANGE_NOT_LOCKED); _CASE(STATUS_RDP_PROTOCOL_ERROR); _CASE(STATUS_RECEIVE_EXPEDITED); _CASE(STATUS_RECEIVE_PARTIAL); _CASE(STATUS_RECEIVE_PARTIAL_EXPEDITED); _CASE(STATUS_RECOVERY_FAILURE); _CASE(STATUS_REDIRECTOR_HAS_OPEN_HANDLES); _CASE(STATUS_REDIRECTOR_NOT_STARTED); _CASE(STATUS_REDIRECTOR_PAUSED); _CASE(STATUS_REDIRECTOR_STARTED); _CASE(STATUS_REGISTRY_CORRUPT); _CASE(STATUS_REGISTRY_IO_FAILED); _CASE(STATUS_REGISTRY_QUOTA_LIMIT); _CASE(STATUS_REGISTRY_RECOVERED); _CASE(STATUS_REG_NAT_CONSUMPTION); _CASE(STATUS_REINITIALIZATION_NEEDED); _CASE(STATUS_REMOTE_DISCONNECT); _CASE(STATUS_REMOTE_NOT_LISTENING); _CASE(STATUS_REMOTE_RESOURCES); _CASE(STATUS_REMOTE_SESSION_LIMIT); _CASE(STATUS_REMOTE_STORAGE_MEDIA_ERROR); _CASE(STATUS_REMOTE_STORAGE_NOT_ACTIVE); _CASE(STATUS_REPARSE); _CASE(STATUS_REPARSE_ATTRIBUTE_CONFLICT); _CASE(STATUS_REPARSE_OBJECT); _CASE(STATUS_REPARSE_POINT_NOT_RESOLVED); _CASE(STATUS_REPLY_MESSAGE_MISMATCH); _CASE(STATUS_REQUEST_ABORTED); _CASE(STATUS_REQUEST_NOT_ACCEPTED); _CASE(STATUS_RESOURCE_DATA_NOT_FOUND); _CASE(STATUS_RESOURCE_LANG_NOT_FOUND); _CASE(STATUS_RESOURCE_NAME_NOT_FOUND); _CASE(STATUS_RESOURCE_NOT_OWNED); _CASE(STATUS_RESOURCE_REQUIREMENTS_CHANGED); _CASE(STATUS_RESOURCE_TYPE_NOT_FOUND); _CASE(STATUS_RETRY); _CASE(STATUS_REVISION_MISMATCH); _CASE(STATUS_RXACT_COMMITTED); _CASE(STATUS_RXACT_COMMIT_FAILURE); _CASE(STATUS_RXACT_COMMIT_NECESSARY); _CASE(STATUS_RXACT_INVALID_STATE); _CASE(STATUS_RXACT_STATE_CREATED); _CASE(STATUS_SAM_INIT_FAILURE); _CASE(STATUS_SAM_NEED_BOOTKEY_FLOPPY); _CASE(STATUS_SAM_NEED_BOOTKEY_PASSWORD); _CASE(STATUS_SECRET_TOO_LONG); _CASE(STATUS_SECTION_NOT_EXTENDED); _CASE(STATUS_SECTION_NOT_IMAGE); _CASE(STATUS_SECTION_PROTECTION); _CASE(STATUS_SECTION_TOO_BIG); _CASE(STATUS_SEGMENT_NOTIFICATION); _CASE(STATUS_SEMAPHORE_LIMIT_EXCEEDED); _CASE(STATUS_SERIAL_COUNTER_TIMEOUT); _CASE(STATUS_SERIAL_MORE_WRITES); _CASE(STATUS_SERIAL_NO_DEVICE_INITED); _CASE(STATUS_SERVER_DISABLED); _CASE(STATUS_SERVER_HAS_OPEN_HANDLES); _CASE(STATUS_SERVER_NOT_DISABLED); _CASE(STATUS_SERVER_SID_MISMATCH); _CASE(STATUS_SERVICE_NOTIFICATION); _CASE(STATUS_SETMARK_DETECTED); _CASE(STATUS_SHARED_IRQ_BUSY); _CASE(STATUS_SHARED_POLICY); _CASE(STATUS_SHARING_PAUSED); _CASE(STATUS_SHARING_VIOLATION); _CASE(STATUS_SINGLE_STEP); _CASE(STATUS_SOME_NOT_MAPPED); _CASE(STATUS_SOURCE_ELEMENT_EMPTY); _CASE(STATUS_SPECIAL_ACCOUNT); _CASE(STATUS_SPECIAL_GROUP); _CASE(STATUS_SPECIAL_USER); _CASE(STATUS_STACK_OVERFLOW); _CASE(STATUS_STACK_OVERFLOW_READ); _CASE(STATUS_SUCCESS); _CASE(STATUS_SUSPEND_COUNT_EXCEEDED); _CASE(STATUS_SYNCHRONIZATION_REQUIRED); _CASE(STATUS_SYSTEM_IMAGE_BAD_SIGNATURE); _CASE(STATUS_SYSTEM_PROCESS_TERMINATED); _CASE(STATUS_THREAD_IS_TERMINATING); _CASE(STATUS_THREAD_NOT_IN_PROCESS); _CASE(STATUS_THREAD_WAS_SUSPENDED); _CASE(STATUS_TIMEOUT); _CASE(STATUS_TIMER_NOT_CANCELED); _CASE(STATUS_TIMER_RESOLUTION_NOT_SET); _CASE(STATUS_TIMER_RESUME_IGNORED); _CASE(STATUS_TIME_DIFFERENCE_AT_DC); _CASE(STATUS_TOKEN_ALREADY_IN_USE); _CASE(STATUS_TOO_LATE); _CASE(STATUS_TOO_MANY_ADDRESSES); _CASE(STATUS_TOO_MANY_COMMANDS); _CASE(STATUS_TOO_MANY_CONTEXT_IDS); _CASE(STATUS_TOO_MANY_GUIDS_REQUESTED); _CASE(STATUS_TOO_MANY_LINKS); _CASE(STATUS_TOO_MANY_LUIDS_REQUESTED); _CASE(STATUS_TOO_MANY_NAMES); _CASE(STATUS_TOO_MANY_NODES); _CASE(STATUS_TOO_MANY_OPENED_FILES); _CASE(STATUS_TOO_MANY_PAGING_FILES); _CASE(STATUS_TOO_MANY_SECRETS); _CASE(STATUS_TOO_MANY_SESSIONS); _CASE(STATUS_TOO_MANY_SIDS); _CASE(STATUS_TOO_MANY_THREADS); _CASE(STATUS_TRANSACTION_ABORTED); _CASE(STATUS_TRANSACTION_INVALID_ID); _CASE(STATUS_TRANSACTION_INVALID_TYPE); _CASE(STATUS_TRANSACTION_NO_MATCH); _CASE(STATUS_TRANSACTION_NO_RELEASE); _CASE(STATUS_TRANSACTION_RESPONDED); _CASE(STATUS_TRANSACTION_TIMED_OUT); _CASE(STATUS_TRANSLATION_COMPLETE); _CASE(STATUS_TRANSPORT_FULL); _CASE(STATUS_TRUSTED_DOMAIN_FAILURE); _CASE(STATUS_TRUSTED_RELATIONSHIP_FAILURE); _CASE(STATUS_TRUST_FAILURE); _CASE(STATUS_UNABLE_TO_DECOMMIT_VM); _CASE(STATUS_UNABLE_TO_DELETE_SECTION); _CASE(STATUS_UNABLE_TO_FREE_VM); _CASE(STATUS_UNABLE_TO_LOCK_MEDIA); _CASE(STATUS_UNABLE_TO_UNLOAD_MEDIA); _CASE(STATUS_UNDEFINED_CHARACTER); _CASE(STATUS_UNEXPECTED_IO_ERROR); _CASE(STATUS_UNEXPECTED_MM_CREATE_ERR); _CASE(STATUS_UNEXPECTED_MM_EXTEND_ERR); _CASE(STATUS_UNEXPECTED_MM_MAP_ERROR); _CASE(STATUS_UNEXPECTED_NETWORK_ERROR); _CASE(STATUS_UNHANDLED_EXCEPTION); _CASE(STATUS_UNKNOWN_REVISION); _CASE(STATUS_UNMAPPABLE_CHARACTER); _CASE(STATUS_UNRECOGNIZED_MEDIA); _CASE(STATUS_UNRECOGNIZED_VOLUME); _CASE(STATUS_UNSUCCESSFUL); _CASE(STATUS_UNSUPPORTED_COMPRESSION); _CASE(STATUS_UNWIND); _CASE(STATUS_USER_APC); _CASE(STATUS_USER_EXISTS); _CASE(STATUS_USER_MAPPED_FILE); _CASE(STATUS_USER_SESSION_DELETED); _CASE(STATUS_VALIDATE_CONTINUE); _CASE(STATUS_VARIABLE_NOT_FOUND); _CASE(STATUS_VDM_HARD_ERROR); _CASE(STATUS_VERIFY_REQUIRED); _CASE(STATUS_VIRTUAL_CIRCUIT_CLOSED); _CASE(STATUS_VOLUME_DISMOUNTED); _CASE(STATUS_VOLUME_MOUNTED); _CASE(STATUS_VOLUME_NOT_UPGRADED); _CASE(STATUS_WAIT_1); _CASE(STATUS_WAIT_2); _CASE(STATUS_WAIT_3); _CASE(STATUS_WAIT_63); _CASE(STATUS_WAKE_SYSTEM); _CASE(STATUS_WAKE_SYSTEM_DEBUGGER); _CASE(STATUS_WAS_LOCKED); _CASE(STATUS_WAS_UNLOCKED); _CASE(STATUS_WMI_GUID_NOT_FOUND); _CASE(STATUS_WMI_INSTANCE_NOT_FOUND); _CASE(STATUS_WMI_ITEMID_NOT_FOUND); _CASE(STATUS_WMI_NOT_SUPPORTED); _CASE(STATUS_WMI_READ_ONLY); _CASE(STATUS_WMI_SET_FAILURE); _CASE(STATUS_WMI_TRY_AGAIN); _CASE(STATUS_WORKING_SET_LIMIT_RANGE); _CASE(STATUS_WORKING_SET_QUOTA); _CASE(STATUS_WOW_ASSERTION); _CASE(STATUS_WRONG_EFS); _CASE(STATUS_WRONG_PASSWORD); _CASE(STATUS_WRONG_PASSWORD_CORE); _CASE(STATUS_WRONG_VOLUME); _CASE(STATUS_WX86_BREAKPOINT); _CASE(STATUS_WX86_CONTINUE); _CASE(STATUS_WX86_CREATEWX86TIB); _CASE(STATUS_WX86_EXCEPTION_CHAIN); _CASE(STATUS_WX86_EXCEPTION_CONTINUE); _CASE(STATUS_WX86_EXCEPTION_LASTCHANCE); _CASE(STATUS_WX86_FLOAT_STACK_CHECK); _CASE(STATUS_WX86_INTERNAL_ERROR); _CASE(STATUS_WX86_SINGLE_STEP); _CASE(STATUS_WX86_UNSIMULATE); default: return "STATUS_UNKNOWN"; } #undef _CASE }
jarupxx/Cxbx-Reloaded
src/CxbxKrnl/EmuFile.cpp
C++
gpl-2.0
75,098
<?php /** * Akeeba Engine * The modular PHP5 site backup engine * @copyright Copyright (c)2006-2018 Nicholas K. Dionysopoulos / Akeeba Ltd * @license GNU GPL version 3 or, at your option, any later version * @package akeebaengine * */ namespace Akeeba\Engine\Filter; // Protection against direct access defined('AKEEBAENGINE') or die(); use Akeeba\Engine\Factory; use Akeeba\Engine\Platform; /** * Incremental file filter * * It will only backup files which are newer than the last backup taken with this profile */ class Incremental extends Base { function __construct() { $this->object = 'file'; $this->subtype = 'all'; $this->method = 'api'; if (Factory::getKettenrad()->getTag() == 'restorepoint') { $this->enabled = false; } } protected function is_excluded_by_api($test, $root) { static $filter_switch = null; static $last_backup = null; if (is_null($filter_switch)) { $config = Factory::getConfiguration(); $filter_switch = Factory::getEngineParamsProvider()->getScriptingParameter('filter.incremental', 0); $filter_switch = ($filter_switch == 1); $last_backup = $config->get('volatile.filter.last_backup', null); if (is_null($last_backup) && $filter_switch) { // Get a list of backups on this profile $backups = Platform::getInstance()->get_statistics_list(array( 'filters' => array( array( 'field' => 'profile_id', 'value' => Platform::getInstance()->get_active_profile()) ) )); // Find this backup's ID $model = Factory::getStatistics(); $id = $model->getId(); if (is_null($id)) { $id = -1; } // Initialise $last_backup = time(); $now = $last_backup; // Find the last time a successful backup with this profile was made if (count($backups)) { foreach ($backups as $backup) { // Skip the current backup if ($backup['id'] == $id) { continue; } // Skip non-complete backups if ($backup['status'] != 'complete') { continue; } $tzUTC = new \DateTimeZone('UTC'); $dateTime = new \DateTime($backup['backupstart'], $tzUTC); $backuptime = $dateTime->getTimestamp(); $last_backup = $backuptime; break; } } if ($last_backup == $now) { // No suitable backup found; disable this filter $config->set('volatile.scripting.incfile.filter.incremental', 0); $filter_switch = false; } else { // Cache the last backup timestamp $config->set('volatile.filter.last_backup', $last_backup); } } } if (!$filter_switch) { return false; } // Get the filesystem path for $root $config = Factory::getConfiguration(); $fsroot = $config->get('volatile.filesystem.current_root', ''); $ds = ($fsroot == '') || ($fsroot == '/') ? '' : DIRECTORY_SEPARATOR; $filename = $fsroot . $ds . $test; // Get the timestamp of the file $timestamp = @filemtime($filename); // If we could not get this information, include the file in the archive if ($timestamp === false) { return false; } // Compare it with the last backup timestamp and exclude if it's older than the last backup if ($timestamp <= $last_backup) { //Factory::getLog()->log(LogLevel::DEBUG, "Excluding $filename due to incremental backup restrictions"); return true; } // No match? Just include the file! return false; } }
jq153387/THS
administrator/components/com_akeeba/BackupEngine/Filter/Incremental.php
PHP
gpl-2.0
3,468
#! /usr/bin/env rspec require_relative "test_helper" require "erb" Yast.import "Popup" describe Yast::Popup do let(:ui) { double("Yast::UI") } subject { Yast::Popup } before do # generic UI stubs for the progress dialog stub_const("Yast::UI", ui) end describe ".Feedback" do context "when arguments are good" do before do expect(ui).to receive(:OpenDialog) expect(ui).to receive(:CloseDialog) allow(ui).to receive(:BusyCursor) allow(ui).to receive(:GetDisplayInfo).and_return({}) end it "opens a popup dialog and closes it at the end" do # just pass an empty block subject.Feedback("Label", "Message") {} end it "closes the popup even when an exception occurs in the block" do # raise an exception in the block expect { subject.Feedback("Label", "Message") { raise "TEST" } }.to raise_error(RuntimeError, "TEST") end end context "when arguments are bad" do it "raises exception when the block parameter is missing" do # no block passed expect { subject.Feedback("Label", "Message") }.to raise_error(ArgumentError, /block must be supplied/) end end end describe ".Message" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(subject).to receive(:RichText).with("<h1>Title</h1>") subject.Message("<h1>Title</h1>") end end describe ".Warning" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(subject).to receive(:RichText).with("<h1>Title</h1>") subject.Warning("<h1>Title</h1>") end end describe ".Error" do before { allow(ui).to receive(:OpenDialog) } let(:switch_to_richtext) { true } let(:line) { "<h1>Title</h1>\n" } let(:limit) { subject.too_many_lines } # Backup and restore the original switch_to_richtext flag around do |example| old_switch_to_richtext = subject.switch_to_richtext subject.switch_to_richtext = switch_to_richtext example.run subject.switch_to_richtext = old_switch_to_richtext end context "when switching to richtext is not allowed" do let(:switch_to_richtext) { false } it "shows a popup without escaping tags" do message = line * limit expect(subject).to receive(:RichText).with(message) subject.Error(message) end end context "when switch to richtext is allowed" do let(:switch_to_richtext) { true } it "escapes the tags if message is too long" do message = line * limit expect(subject).to receive(:RichText).with(ERB::Util.html_escape(message)) subject.Error(message) end it "keeps the original text if the message is short" do expect(subject).to receive(:RichText).with(line) subject.Error(line) end end end # # LongMessage # describe ".LongMessage" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(subject).to receive(:RichText).with("<h1>Title</h1>") subject.LongMessage("<h1>Title</h1>") end end describe ".LongMessageGeometry" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(subject).to receive(:RichText).with("<h1>Title</h1>") subject.LongMessage("<h1>Title</h1>") end it "sets dialog width and height" do allow(subject).to receive(:HSpacing) allow(subject).to receive(:VSpacing) expect(subject).to receive(:HSpacing).with(30) expect(subject).to receive(:VSpacing).with(40) subject.LongMessageGeometry("Title", 30, 40) end end describe ".TimedLongMessage" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(ui).to receive(:TimeoutUserInput) allow(subject).to receive(:RichText).with("<h1>Title</h1>") subject.TimedLongMessage("<h1>Title</h1>", 1) end end describe ".TimedLongMessageGeometry" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(ui).to receive(:TimeoutUserInput) allow(subject).to receive(:RichText).with("<h1>Title</h1>") subject.TimedLongMessageGeometry("<h1>Title</h1>", 1, 30, 40) end it "sets dialog width and height" do allow(ui).to receive(:TimeoutUserInput) allow(subject).to receive(:HSpacing) allow(subject).to receive(:VSpacing) expect(subject).to receive(:HSpacing).with(30) expect(subject).to receive(:VSpacing).with(40) subject.TimedLongMessageGeometry("Title", 1, 30, 40) end end # # LongWarning # describe ".LongWarning" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(subject).to receive(:RichText).with("<h1>Title</h1>") subject.LongWarning("<h1>Title</h1>") end end describe ".LongWarningGeometry" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(subject).to receive(:RichText).with("<h1>Title</h1>") subject.LongWarningGeometry("<h1>Title</h1>", 30, 40) end it "sets dialog width and height" do allow(subject).to receive(:HSpacing) allow(subject).to receive(:VSpacing) expect(subject).to receive(:HSpacing).with(30) expect(subject).to receive(:VSpacing).with(40) subject.LongWarningGeometry("Title", 30, 40) end end describe ".TimedLongWarning" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(ui).to receive(:TimeoutUserInput) allow(subject).to receive(:RichText).with("<h1>Title</h1>") subject.TimedLongWarning("<h1>Title</h1>", 1) end end describe ".TimedLongWarningGeometry" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(ui).to receive(:TimeoutUserInput) allow(subject).to receive(:RichText).with("<h1>Title</h1>") subject.TimedLongWarningGeometry("<h1>Title</h1>", 1, 30, 40) end it "sets dialog width and height" do allow(ui).to receive(:TimeoutUserInput) allow(subject).to receive(:HSpacing) allow(subject).to receive(:VSpacing) expect(subject).to receive(:HSpacing).with(30) expect(subject).to receive(:VSpacing).with(40) subject.TimedLongWarningGeometry("Title", 1, 30, 40) end end # # LongError # describe ".LongError" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(subject).to receive(:RichText).with("<h1>Title</h1>") subject.LongError("<h1>Title</h1>") end end describe ".LongErrorGeometry" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(subject).to receive(:RichText).with("<h1>Title</h1>") subject.LongErrorGeometry("<h1>Title</h1>", 30, 40) end it "sets dialog width and height" do allow(subject).to receive(:HSpacing) allow(subject).to receive(:VSpacing) expect(subject).to receive(:HSpacing).with(30) expect(subject).to receive(:VSpacing).with(40) subject.LongErrorGeometry("Title", 30, 40) end end describe ".TimedLongError" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(ui).to receive(:TimeoutUserInput) allow(subject).to receive(:RichText).with("<h1>Title</h1>") subject.TimedLongError("<h1>Title</h1>", 1) end end describe ".TimedLongErrorGeometry" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(ui).to receive(:TimeoutUserInput) allow(subject).to receive(:RichText).with("<h1>Title</h1>") subject.TimedLongErrorGeometry("<h1>Title</h1>", 1, 30, 40) end it "sets dialog width and height" do allow(ui).to receive(:TimeoutUserInput) allow(subject).to receive(:HSpacing) allow(subject).to receive(:VSpacing) expect(subject).to receive(:HSpacing).with(30) expect(subject).to receive(:VSpacing).with(40) subject.TimedLongErrorGeometry("Title", 1, 30, 40) end context "when arguments are bad" do it "raises exception when the block parameter is missing" do # no block passed expect { subject.Feedback("Label", "Message") }.to raise_error(ArgumentError, /block must be supplied/) end end end describe ".AnyTimedMessage" do it "is an adapter for anyTimedMessageInternal" do expect(subject).to receive(:anyTimedMessageInternal) .with("headline", "message", Integer) expect(subject.AnyTimedMessage("headline", "message", 5)).to eq nil end end # # TimedLongNotify # describe ".LongNotify" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(subject).to receive(:RichText).with("<h1>Title</h1>") subject.LongNotify("<h1>Title</h1>") end end describe ".LongNotifyGeometry" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(subject).to receive(:RichText).with("<h1>Title</h1>") subject.LongNotifyGeometry("<h1>Title</h1>", 30, 40) end it "sets dialog width and height" do allow(subject).to receive(:HSpacing) allow(subject).to receive(:VSpacing) expect(subject).to receive(:HSpacing).with(30) expect(subject).to receive(:VSpacing).with(40) subject.LongNotifyGeometry("Title", 30, 40) end end describe ".TimedLongNotify" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(ui).to receive(:TimeoutUserInput) allow(subject).to receive(:RichText).with("<h1>Title</h1>") subject.TimedLongNotify("<h1>Title</h1>", 1) end end describe ".TimedLongNotifyGeometry" do before { allow(ui).to receive(:OpenDialog) } it "shows a popup without escaping tags" do expect(ui).to receive(:TimeoutUserInput) allow(subject).to receive(:RichText).with("<h1>Title</h1>") subject.TimedLongNotifyGeometry("<h1>Title</h1>", 1, 30, 40) end it "sets dialog width and height" do allow(ui).to receive(:TimeoutUserInput) allow(subject).to receive(:HSpacing) allow(subject).to receive(:VSpacing) expect(subject).to receive(:HSpacing).with(30) expect(subject).to receive(:VSpacing).with(40) subject.TimedLongNotifyGeometry("Title", 1, 30, 40) end end describe ".AnyTimedMessage" do it "is an adapter for anyTimedMessageInternal" do expect(subject).to receive(:anyTimedMessageInternal) .with("headline", "message", Integer) expect(subject.AnyTimedMessage("headline", "message", 5)).to eq nil end end describe ".AnyTimedRichMessage" do it "is an adapter for anyTimedRichMessageInternal" do expect(subject).to receive(:anyTimedRichMessageInternal) .with("headline", "message", Integer, Integer, Integer) expect(subject.AnyTimedRichMessage("headline", "message", 5)).to eq nil end end end
kobliha/yast-yast2
library/general/test/popup_test.rb
Ruby
gpl-2.0
11,426
/* Copyright 2012 Jesper K. Pedersen <blackie@kde.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) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. 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 "UploadWidget.h" #include <QLabel> #include <QHBoxLayout> #include <QTimer> #include "ImageCollection.h" #include <QFileSystemModel> #include <Settings/SettingsData.h> #include <QTreeView> #include "UploadImageCollection.h" namespace Plugins { UploadWidget::UploadWidget( QWidget* parent ) : KIPI::UploadWidget( parent ) { QTreeView* listView = new QTreeView(this); QHBoxLayout* layout = new QHBoxLayout(this); layout->addWidget(listView); m_model = new QFileSystemModel(this); m_model->setFilter( QDir::Dirs | QDir::NoDotDot); listView->setModel(m_model); m_path = Settings::SettingsData::instance()->imageDirectory(); const QModelIndex index = m_model->setRootPath( m_path ); listView->setRootIndex(index); connect(listView,SIGNAL(activated(QModelIndex)), this, SLOT(newIndexSelected(QModelIndex))); } KIPI::ImageCollection UploadWidget::selectedImageCollection() const { return KIPI::ImageCollection( new Plugins::UploadImageCollection( m_path ) ); } void UploadWidget::newIndexSelected(const QModelIndex& index ) { m_path = m_model->filePath(index); } } // namespace Plugins // vi:expandtab:tabstop=4 shiftwidth=4:
astifter/kphotoalbum-astifter-branch
Plugins/UploadWidget.cpp
C++
gpl-2.0
2,093
#!/usr/bin/python """ Usage: python manifestParser.py [path to list with manifest paths]. Parses the manifests indicated in the list file and cretes a pl file with the aplication permissions. """ import os,sys import subprocess import xml.etree.ElementTree as ET class manifestParser: """ Main class that parses manifest file """ def __init__(self, listFile): self.listFile = listFile def getApplicationFacts(self, aManifestFile): """ Method that obtains the permissions from a manifest file and parses it as a prolog fact """ # These lines are used to obtain the path to the working directory currentDir = os.getcwd() filename = os.path.join(currentDir, aManifestFile) # These lines parse the xml, the application permissions are stored as a list in permissions manifestTree = self.parseXml(filename) applicationName = self.getApplicationName(manifestTree) permissions = self.getPermissions(manifestTree) # Prolog defines atoms with an initial lower case. However in the manifest file, permissions are defined in uppercase manifestPermissions='permissions(' + applicationName.lower() +',[' permissionList=[] # Obtains the attribute stored in the permission list and appends it to the list for i in range(len(permissions)): permissionList.append(str(permissions[i].attrib['{http://schemas.android.com/apk/res/android}name'].split('.')[2]).lower()) if i < len(permissions) - 1: manifestPermissions= manifestPermissions + permissionList[i] + ',' else: manifestPermissions= manifestPermissions + permissionList[i] manifestPermissions = manifestPermissions + ']).\n' return manifestPermissions def parseXml(self, xmlPath): return ET.parse(xmlPath) def getPermissions(self, aManifestTree): return aManifestTree.findall('uses-permission') def getApplicationName(self, aManifestTree): appName = aManifestTree.findall('application') return appName[0].attrib['{http://schemas.android.com/apk/res/android}name'].split('.')[-1] def getManifests(self, aFileName): """ Method that reads the list file and creates a list with all the manifests paths """ # Reads the file listFile = open(aFileName, 'r') manifestPaths = [] # This for goes through the file object, line by line for line in listFile: # Appends each path to the list, the split is used to append the path without the newline <<<<<<< HEAD if len (line) < 2: continue ======= >>>>>>> cdf807928f1c8a63a07a8b559ea3dae692af51b0 manifestPaths.append(line.split('\n')[0]) return manifestPaths if __name__=="__main__": parser = manifestParser(sys.argv[1]) # Command line argument is a txt file that lists all manifests aFileName = sys.argv[1] # Get all the manifest files included in list.txt manifestList = parser.getManifests(aFileName) prologFactPermissionsString='' # Creates a string with the format permission(applicationName,[all permissions]) for i in range(len(manifestList)): prologFactPermissionsString = prologFactPermissionsString + parser.getApplicationFacts(manifestList[i]) # Writes the permissions to a pl file outputFile = open("permissions.pl", 'w') outputFile.write(prologFactPermissionsString) outputFile.close()
afmurillo/FinalHerramientas-2014-2
ProyectoFinal/Codigo/manifestParser.py
Python
gpl-2.0
3,248
<?php /* Plugin Name: Social Comments Plugin URI: http://en.bainternet.info Description: This plugin adds Google Plus Comments , facebook comments, Disqus comments and the native comments system to your blog Version: 0.1.2 Author: Bainternet Author Email: admin@bainternet.info License: Copyright Bainternet 2013 (admin@bainternet.info) 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. 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ if (!class_exists('SocialComments')){ class SocialComments { /**************** * Public Vars * ***************/ /** * $dir * * olds plugin directory * @var string */ public $dir = ''; /** * $url * * holds assets url * @var string */ public $url = ''; /** * $txdomain * * holds plugin textDomain * @var string */ public $txdomain = 'GPComments'; /** * $options * * holds plugin settings options * @var array */ public $options = array(); /**************** * Methods * ***************/ /** * Plugin class Constructor */ function __construct() { $this->setProperties(); $this->dir = plugin_dir_path(__FILE__); //Respects SSL $this->url = plugins_url('assets/', __FILE__); $this->hooks(); } /** * hooks * * function used to add action and filter hooks * Used with `adminHooks` and `clientHokks` * * hooks for both admin and client sides should be added at the buttom * * @return void */ public function hooks(){ if(is_admin()) $this->adminHooks(); else $this->clientHooks(); /** * hooks for both admin and client sides * hooks should be here */ } /** * adminHooks * * Admin side hooks should go here * @return void */ function adminHooks(){ //add admin panel if (!class_exists('SimplePanel')) require_once(plugin_dir_path(__FILE__).'classes/Simple_Panel_Class.php'); require_once(plugin_dir_path(__FILE__).'classes/gpcomments_Panel_Class.php'); } /** * clientHooks * * client side hooks should go here * @return void */ function clientHooks(){ $options = $this->getOptions(); if ($options['gplus_comments_enabled'] || $options['facebook_comments_enabled'] || $options['disqus_comments_enabled'] ){ //chatch comment template hook for replacement add_filter('comments_template',array($this, 'add_socialcomments_tmplate')); //add css add_action( 'wp_enqueue_scripts', array($this,'enqueue_style' )); } } /** * setProperties * * function to set class Properties * @param array $args array of arguments * @param boolean $properties arguments to set */ public function setProperties($args = array(), $properties = false){ if (!is_array($properties)) $properties = array_keys(get_object_vars($this)); foreach ($properties as $key ) { $this->$key = (isset($args[$key]) ? $args[$key] : $this->$key); } } /** * createNewView * * This create a new EasyView instance * @param array $args [description] * @return object EasyView instance */ public function createNewView($args = array('vars' => array())){ if(!class_exists('EasyView')) require_once($this->dir.'/classes/EasyView.php'); return new EasyView('',$args); } /** * createViewGet * * This is a shorthand function for creating a new EasyView object * and geting the rendered template. * * * @param string $template Template File * @param string $templatedir templates directory * @param array $args view args * @return string rendered view as astring */ public function createViewGet($template = '', $templatedir = '', $args = array('vars' => array())){ $v = $this->createNewView($templatedir, $args); return $v->getRender($template); } /** * getOptions * * gets the saved options and sets the defaults * @since 0.1 * @access public * @return array */ public function getOptions(){ if($this->options == null){ $def = array( 'how' => 'Tabbed', 'order' => array('wp', 'gplus', 'facebook','disqus'), 'iconset' => 'cleanlight', 'wp_comments_enabled' => TRUE, 'wp_comments_label' => __('WordPress'), 'wp_comments_img' => '', 'gplus_comments_enabled' => FALSE, 'gplus_comments_label' => __('Google + '), 'gplus_comments_img' => '', 'disqus_comments_enabled' => FALSE, 'disqus_comments_label' => __('Disqus'), 'disqus_comments_img' => '', 'disqus_shortname' => '', 'facebook_comments_enabled' => FALSE, 'facebook_appID' => 'null', 'facebook_colorScheme' => 'light', 'facebook_comments_label' => __('Facebook'), 'facebook_comments_img' => '', 'tabsTrigger' => 'Click', 'pre_tabs_label' => NULL ); $tmp = get_option('social_comments',array()); //fix reverse boolean if (count($tmp) > 0 && !isset($tmp['wp_comments_enabled'])){ $tmp['wp_comments_enabled'] = false; } $this->options = array_merge($def,$tmp); } return $this->options; } public function add_plusonecomments( $file ){ return $this->dir .'views/Google.comments.markup.php'; } public function getGoocleComments(){ $options = $this->getOptions(); $view = $this->createViewGet($this->dir.'/views/Google.comments.markup.php'); return $view; } public function getFacebookComments(){ $options = $this->getOptions(); $v = $this->createNewView(); $v->Color_Scheme = $options['facebook_colorScheme']; $v->appID = $options['facebook_appID']; $this->modLink = ''; if (current_user_can( 'moderate_comments' )) $this->modLink = '<a href="http://developers.facebook.com/tools/comments?id='.$options['facebook_appID'].'" target="_blank">'.__('Moderate Facebook Comments').'</a>'; return $v->getRender($this->dir.'/views/Facebook.comments.markup.php'); } public function getDisqusComments(){ $options = $this->getOptions(); $v = $this->createNewView(); $v->shortname = $options['disqus_shortname']; return $v->getRender($this->dir.'/views/disqus.comments.markup.php'); } public function getWordPressComments($file){ ob_start(); include($file); return ob_get_clean(); } function add_socialcomments_tmplate($file){ if ((is_single() || is_page() || is_singular()) && comments_open()){ $options = $this->getOptions(); $comm =''; $style =''; //exit if password protected and no cookie is found if (post_password_required()){ echo '<p><em>'.__('This is password protected.').'</em></p>'; return $this->dir.'/views/comments.php'; } //loop over the systems foreach ($options['order'] as $key => $value) { //skip if disabled if (!$options[$value.'_comments_enabled']) continue; $comm .= "<div id='{$value}_comments' style='{$style}'>"; //$style = 'display:none;'; switch ($value) { case 'wp': $comm .= $this->getWordPressComments($file); break; case 'gplus': $comm .= $this->getGoocleComments(); break; case 'facebook': $comm .= $this->getFacebookComments(); break; case 'disqus': $comm .= $this->getDisqusComments(); break; } $comm .= "</div><!-- #{$value} -->"; if ($options['how'] == 'Tabbed'){ if (isset($options[$value.'_comments_img']['url']) && !empty($options[$value.'_comments_img']['url'])) $img = $options[$value.'_comments_img']['url']; else{ $img = $this->url .'images/icons/'.$options['iconset'].'/'.$value.'.png'; } $img = "<img src='{$img}'>"; $ul[] = "<li><a href='#{$value}_comments'>{$img}".$options[$value.'_comments_label']."</a></li>"; } } if ($options['how'] == 'Tabbed'){ $pre_tabs = isset($options['pre_tabs_label'])? $options['pre_tabs_label'] : ''; $comm = "<div id='social_comments_control'>{$pre_tabs}<ul id='social_comments_nav'>".implode("",$ul). "</ul>". $comm ."</div>"; //add jQuery tabs wp_enqueue_script( 'jquery'); wp_enqueue_script( 'jquery-ui-tabs'); add_filter('wp_footer',array($this,'tabs_JS'),1000); } echo $comm; //dirty dirty hack to include an empty file since this filter will include the native comments otherwise return $this->dir.'/views/comments.php'; }else{ return $file; } } function enqueue_style(){ $suffix = ( is_rtl() ) ? '.rtl': ''; wp_register_style( 'social_comments_rtl', $this->url.'css/social_comments'.$suffix.'.css'); wp_enqueue_style( 'social_comments_rtl' ); } function tabs_JS(){ $options = $this->getOptions(); if ($options['tabsTrigger'] == "Click"){ ?><script type="text/javascript">jQuery(document).ready(function($){$("#social_comments_control").tabs();});</script><?php }else{ ?><script type="text/javascript">jQuery(document).ready(function($){$("#social_comments_control").tabs({ event: "mouseover" });});</script><?php } } } // end class }//end if $GLOBALS['SocialComments'] = new SocialComments();
browngd/bitcrunched
wp-content/plugins/social-comments/plugin.php
PHP
gpl-2.0
10,116
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2017 Paco Avila & Josep Llort * <p> * No bytes were intentionally harmed during the development of this application. * <p> * 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. * <p> * 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. * <p> * 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. */ package com.openkm.util.markov; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.InputMismatchException; import java.util.Random; /** * Creates a Markov graph from an input file and generates text * based on it. Given two input files, generates two graphs * and interpolates between them. * * @author Lawrence Kesteloot * @author Paco Avila */ public class Generator { private static final int DEFAULT_PREFIX_LENGTH = 4; private static final int LINE_WIDTH = 80; private static final int TOTAL_CHARACTERS = 300; private int prefixLength; private Markov markov; public Generator(InputStream in, int prefixLength) throws IOException { markov = new Markov(new InputStreamReader(in), prefixLength); this.prefixLength = prefixLength; } public Generator(InputStream in) throws IOException { markov = new Markov(new InputStreamReader(in), DEFAULT_PREFIX_LENGTH); this.prefixLength = DEFAULT_PREFIX_LENGTH; } /** * Generate a text using defaults to a writer */ public void generateText(int paragraphs, OutputStream out) throws Exception { generateText(paragraphs, LINE_WIDTH, TOTAL_CHARACTERS, out); } /** * Generate a text to a writer * @throws IOException * @throws InputMismatchException */ public void generateText(int paragraphs, int lineWidth, int totalCharacters, OutputStream out) throws InputMismatchException, IOException { for (int i = 0; i < paragraphs; i++) { generateParagraph(lineWidth, totalCharacters, out); out.write("\n\n".getBytes()); } } /** * Generate a paragraph using defaults to a writer * @throws IOException * @throws InputMismatchException */ public void generateParagraph(OutputStream out) throws InputMismatchException, IOException { generateParagraph(LINE_WIDTH, TOTAL_CHARACTERS, out); } /** * Generate a paragraph to a writer * @throws IOException * @throws InputMismatchException */ public void generateParagraph(int lineWidth, int totalCharacters, OutputStream out) throws InputMismatchException, IOException { Random random = new Random(); CharQueue queue = new CharQueue(prefixLength); float weight = 0; int width = prefixLength; int c; queue.set(markov.getBootstrapPrefix()); out.write(queue.toString().getBytes()); do { String prefix = queue.toString(); c = markov.get(prefix, random); if (c == -1) { break; } out.write((char) c); queue.put((char) c); width++; // line wrap if (c == ' ' && width > lineWidth) { out.write("\n".getBytes()); width = 0; } // go towards second Markov chain weight += 1.0 / totalCharacters; } while (weight < 1 || c != '.'); } }
Beau-M/document-management-system
src/main/java/com/openkm/util/markov/Generator.java
Java
gpl-2.0
3,689
// SPDX-License-Identifier: GPL-2.0 #include "testgitstorage.h" #include "git2.h" #include "core/device.h" #include "core/dive.h" #include "core/divesite.h" #include "core/file.h" #include "core/qthelper.h" #include "core/subsurfacestartup.h" #include "core/settings/qPrefProxy.h" #include "core/settings/qPrefCloudStorage.h" #include "core/trip.h" #include "core/git-access.h" #include <QDir> #include <QTextStream> #include <QNetworkProxy> #include <QTextCodec> #include <QDebug> #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) #include <QRandomGenerator> #endif // provide declarations for two local helper functions in git-access.c extern "C" char *get_local_dir(const char *remote, const char *branch); extern "C" void delete_remote_branch(git_repository *repo, const char *remote, const char *branch); QString email; QString gitUrl; QString cloudTestRepo; QString localCacheDir; QString localCacheRepo; QString randomBranch; static void moveDir(QString oldName, QString newName) { QDir oldDir(oldName); QDir newDir(newName); QCOMPARE(newDir.removeRecursively(), true); QCOMPARE(oldDir.rename(oldName, newName), true); } static void localRemoteCleanup() { // cleanup the local cache dir QDir localCacheDirectory(localCacheDir); QCOMPARE(localCacheDirectory.removeRecursively(), true); // get the remote/branch information as parsed by our git tooling const char *branch, *remote; struct git_repository *git_repo; // when this is first executed, we expect the branch not to exist on the remote server; // if that's true, this will print a harmless error to stderr git_repo = is_git_repository(qPrintable(cloudTestRepo), &branch, &remote, false); // this odd comparison is used to tell that we were able to connect to the remote repo; // in the error case we get the full cloudTestRepo name back as "branch" if (branch != randomBranch) { // dang, we weren't able to connect to the server - let's not fail the test // but just give up QSKIP("wasn't able to connect to server"); } // force delete any remote branch of that name on the server (and ignore any errors) delete_remote_branch(git_repo, remote, branch); // and since this will have created a local repo, remove that one, again so the tests start clean QCOMPARE(localCacheDirectory.removeRecursively(), true); free((void *)branch); free((void *)remote); git_repository_free(git_repo); } void TestGitStorage::initTestCase() { // Set UTF8 text codec as in real applications QTextCodec::setCodecForLocale(QTextCodec::codecForMib(106)); // first, setup the preferences an proxy information copy_prefs(&default_prefs, &prefs); QCoreApplication::setOrganizationName("Subsurface"); QCoreApplication::setOrganizationDomain("subsurface.hohndel.org"); QCoreApplication::setApplicationName("Subsurface"); qPrefProxy::load(); qPrefCloudStorage::load(); // setup our cloud test repo / credentials but allow the user to pick a different account by // setting these environment variables // Of course that email needs to exist as cloud storage account and have the given password // // To reduce the risk of collisions on the server, we have ten accounts set up for this purpose // please don't use them for other reasons as they will get deleted regularly email = qgetenv("SSRF_USER_EMAIL"); QString password = qgetenv("SSRF_USER_PASSWORD"); if (email.isEmpty()) { #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) email = QString("gitstorage%1@hohndel.org").arg(QRandomGenerator::global()->bounded(10)); #else // on Qt 5.9 we go back to using qsrand()/qrand() qsrand(time(NULL)); email = QString("gitstorage%1@hohndel.org").arg(qrand() % 10); #endif } if (password.isEmpty()) password = "please-only-use-this-in-the-git-tests"; gitUrl = prefs.cloud_base_url; if (gitUrl.right(1) != "/") gitUrl += "/"; gitUrl += "git"; prefs.cloud_storage_email_encoded = copy_qstring(email); prefs.cloud_storage_password = copy_qstring(password); gitUrl += "/" + email; // all user storage for historical reasons always uses the user's email both as // repo name and as branch. To allow us to keep testing and not step on parallel // runs we'll use actually random branch names - yes, this still has a chance of // conflict, but I'm not going to implement a distributed lock manager for this if (email.startsWith("gitstorage")) { #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) randomBranch = QString::number(QRandomGenerator::global()->bounded(0x1000000), 16) + QString::number(QRandomGenerator::global()->bounded(0x1000000), 16); #else // on Qt 5.9 we go back to using qsrand()/qrand() -- if we get to this code, qsrand() was already called // even on a 32bit system RAND_MAX is at least 32767 so this will also give us 12 random hex digits randomBranch = QString::number(qrand() % 0x1000, 16) + QString::number(qrand() % 0x1000, 16) + QString::number(qrand() % 0x1000, 16) + QString::number(qrand() % 0x1000, 16); #endif } else { // user supplied their own credentials, fall back to the usual "email is branch" pattern randomBranch = email; } cloudTestRepo = gitUrl + QStringLiteral("[%1]").arg(randomBranch); localCacheDir = get_local_dir(qPrintable(gitUrl), qPrintable(randomBranch)); localCacheRepo = localCacheDir + QStringLiteral("[%1]").arg(randomBranch); qDebug() << "repo used:" << cloudTestRepo; qDebug() << "local cache:" << localCacheRepo; // make sure we deal with any proxy settings that are needed QNetworkProxy proxy; proxy.setType(QNetworkProxy::ProxyType(prefs.proxy_type)); proxy.setHostName(prefs.proxy_host); proxy.setPort(prefs.proxy_port); if (prefs.proxy_auth) { proxy.setUser(prefs.proxy_user); proxy.setPassword(prefs.proxy_pass); } QNetworkProxy::setApplicationProxy(proxy); // we will keep switching between online and offline mode below; let's always start online git_local_only = false; // initialize libgit2 git_libgit2_init(); // cleanup local and remote branches localRemoteCleanup(); QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); } void TestGitStorage::cleanupTestCase() { localRemoteCleanup(); } void TestGitStorage::cleanup() { clear_dive_file_data(); } void TestGitStorage::testGitStorageLocal_data() { // Test different paths we may encounter (since storage depends on user name) // as well as with and without "file://" URL prefix. QTest::addColumn<QString>("testDirName"); QTest::addColumn<QString>("prefixRead"); QTest::addColumn<QString>("prefixWrite"); QTest::newRow("ASCII path") << "./gittest" << "" << ""; QTest::newRow("Non ASCII path") << "./gittest_éèêôàüäößíñóúäåöø" << "" << ""; QTest::newRow("ASCII path with file:// prefix on read") << "./gittest2" << "file://" << ""; QTest::newRow("Non ASCII path with file:// prefix on read") << "./gittest2_éèêôàüäößíñóúäåöø" << "" << "file://"; QTest::newRow("ASCII path with file:// prefix on write") << "./gittest3" << "file://" << ""; QTest::newRow("Non ASCII path with file:// prefix on write") << "./gittest3_éèêôàüäößíñóúäåöø" << "" << "file://"; } void TestGitStorage::testGitStorageLocal() { // test writing and reading back from local git storage git_repository *repo; QCOMPARE(parse_file(SUBSURFACE_TEST_DATA "/dives/SampleDivesV2.ssrf", &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); QFETCH(QString, testDirName); QFETCH(QString, prefixRead); QFETCH(QString, prefixWrite); QDir testDir(testDirName); QCOMPARE(testDir.removeRecursively(), true); QCOMPARE(QDir().mkdir(testDirName), true); QString repoNameRead = prefixRead + testDirName; QString repoNameWrite = prefixWrite + testDirName; QCOMPARE(git_repository_init(&repo, qPrintable(testDirName), false), 0); QCOMPARE(save_dives(qPrintable(repoNameWrite + "[test]")), 0); QCOMPARE(save_dives("./SampleDivesV3.ssrf"), 0); clear_dive_file_data(); QCOMPARE(parse_file(qPrintable(repoNameRead + "[test]"), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); QCOMPARE(save_dives("./SampleDivesV3viagit.ssrf"), 0); QFile org("./SampleDivesV3.ssrf"); org.open(QFile::ReadOnly); QFile out("./SampleDivesV3viagit.ssrf"); out.open(QFile::ReadOnly); QTextStream orgS(&org); QTextStream outS(&out); QString readin = orgS.readAll(); QString written = outS.readAll(); QCOMPARE(readin, written); } void TestGitStorage::testGitStorageCloud() { // test writing and reading back from cloud storage // connect to the ssrftest repository on the cloud server // and repeat the same test as before with the local git storage QCOMPARE(parse_file(SUBSURFACE_TEST_DATA "/dives/SampleDivesV2.ssrf", &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); QCOMPARE(save_dives(qPrintable(cloudTestRepo)), 0); clear_dive_file_data(); QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); QCOMPARE(save_dives("./SampleDivesV3viacloud.ssrf"), 0); QFile org("./SampleDivesV3.ssrf"); org.open(QFile::ReadOnly); QFile out("./SampleDivesV3viacloud.ssrf"); out.open(QFile::ReadOnly); QTextStream orgS(&org); QTextStream outS(&out); QString readin = orgS.readAll(); QString written = outS.readAll(); QCOMPARE(readin, written); } void TestGitStorage::testGitStorageCloudOfflineSync() { // make a change to local cache repo (pretending that we did some offline changes) // and then open the remote one again and check that things were propagated correctly // read the local repo from the previous test and add dive 10 QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); QCOMPARE(parse_file(SUBSURFACE_TEST_DATA "/dives/test10.xml", &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); // calling process_loaded_dives() sorts the table, but calling add_imported_dives() // causes it to try to update the window title... let's not do that process_loaded_dives(); // now save only to the local cache but not to the remote server git_local_only = true; QCOMPARE(save_dives(qPrintable(cloudTestRepo)), 0); QCOMPARE(save_dives("./SampleDivesV3plus10local.ssrf"), 0); clear_dive_file_data(); // now pretend that we are online again and open the cloud storage and compare git_local_only = false; QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); QCOMPARE(save_dives("./SampleDivesV3plus10viacloud.ssrf"), 0); QFile org("./SampleDivesV3plus10local.ssrf"); org.open(QFile::ReadOnly); QFile out("./SampleDivesV3plus10viacloud.ssrf"); out.open(QFile::ReadOnly); QTextStream orgS(&org); QTextStream outS(&out); QString readin = orgS.readAll(); QString written = outS.readAll(); QCOMPARE(readin, written); // write back out to cloud storage, move away the local cache, open again and compare QCOMPARE(save_dives(qPrintable(cloudTestRepo)), 0); clear_dive_file_data(); moveDir(localCacheDir, localCacheDir + "save"); QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); QCOMPARE(save_dives("./SampleDivesV3plus10fromcloud.ssrf"), 0); org.close(); org.open(QFile::ReadOnly); QFile out2("./SampleDivesV3plus10fromcloud.ssrf"); out2.open(QFile::ReadOnly); QTextStream orgS2(&org); QTextStream outS2(&out2); readin = orgS2.readAll(); written = outS2.readAll(); QCOMPARE(readin, written); } void TestGitStorage::testGitStorageCloudMerge() { // we want to test a merge - in order to do so we need to make changes to the cloud // repo from two clients - but since we have only one client here, we have to cheat // a little: // the local cache with the 'save' extension will serve as our second client; // // (1) first we make a change and save it to the cloud // (2) then we switch to the second client (i.e., we move that cache back in place) // (3) on that second client we make a different change while offline // (4) now we take that second client back online and get the merge // (5) let's make sure that we have the expected data on the second client // (6) go back to the first client and ensure we have the same data there after sync // (1) open the repo, add dive test11 and save to the cloud git_local_only = false; QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); QCOMPARE(parse_file(SUBSURFACE_TEST_DATA "/dives/test11.xml", &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); process_loaded_dives(); QCOMPARE(save_dives(qPrintable(cloudTestRepo)), 0); clear_dive_file_data(); // (2) switch to the second client by moving the old cache back in place moveDir(localCacheDir, localCacheDir + "client1"); moveDir(localCacheDir + "save", localCacheDir); // (3) open the repo from the old cache and add dive test12 while offline git_local_only = true; QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); QCOMPARE(parse_file(SUBSURFACE_TEST_DATA "/dives/test12.xml", &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); process_loaded_dives(); QCOMPARE(save_dives(qPrintable(cloudTestRepo)), 0); clear_dive_file_data(); // (4) now take things back online git_local_only = false; QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); clear_dive_file_data(); // (5) now we should have all the dives in our repo on the second client // first create the reference data from the xml files: QCOMPARE(parse_file("./SampleDivesV3plus10local.ssrf", &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); QCOMPARE(parse_file(SUBSURFACE_TEST_DATA "/dives/test11.xml", &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); QCOMPARE(parse_file(SUBSURFACE_TEST_DATA "/dives/test12.xml", &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); process_loaded_dives(); QCOMPARE(save_dives("./SampleDivesV3plus10-11-12.ssrf"), 0); // then load from the cloud clear_dive_file_data(); QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); process_loaded_dives(); QCOMPARE(save_dives("./SampleDivesV3plus10-11-12-merged.ssrf"), 0); // finally compare what we have QFile org("./SampleDivesV3plus10-11-12-merged.ssrf"); org.open(QFile::ReadOnly); QFile out("./SampleDivesV3plus10-11-12.ssrf"); out.open(QFile::ReadOnly); QTextStream orgS(&org); QTextStream outS(&out); QString readin = orgS.readAll(); QString written = outS.readAll(); QCOMPARE(readin, written); clear_dive_file_data(); // (6) move ourselves back to the first client and compare data there moveDir(localCacheDir + "client1", localCacheDir); QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); process_loaded_dives(); QCOMPARE(save_dives("./SampleDivesV3plus10-11-12-merged-client1.ssrf"), 0); QFile client1("./SampleDivesV3plus10-11-12-merged-client1.ssrf"); client1.open(QFile::ReadOnly); QTextStream client1S(&client1); readin = client1S.readAll(); QCOMPARE(readin, written); } void TestGitStorage::testGitStorageCloudMerge2() { // delete a dive offline // edit the same dive in the cloud repo // merge // (1) open repo, delete second dive, save offline QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); process_loaded_dives(); struct dive *dive = get_dive(1); delete_single_dive(1); QCOMPARE(save_dives("./SampleDivesMinus1.ssrf"), 0); git_local_only = true; QCOMPARE(save_dives(qPrintable(localCacheRepo)), 0); git_local_only = false; clear_dive_file_data(); // (2) move cache out of the way moveDir(localCacheDir, localCacheDir + "save"); // (3) now we open the cloud storage repo and modify that second dive QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); process_loaded_dives(); dive = get_dive(1); QVERIFY(dive != NULL); free(dive->notes); dive->notes = strdup("These notes have been modified by TestGitStorage"); QCOMPARE(save_dives(qPrintable(cloudTestRepo)), 0); clear_dive_file_data(); // (4) move the saved local cache backinto place and try to open the cloud repo // -> this forces a merge moveDir(localCacheDir + "save", localCacheDir); QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); QCOMPARE(save_dives("./SampleDivesMinus1-merged.ssrf"), 0); QCOMPARE(save_dives(qPrintable(cloudTestRepo)), 0); QFile org("./SampleDivesMinus1-merged.ssrf"); org.open(QFile::ReadOnly); QFile out("./SampleDivesMinus1.ssrf"); out.open(QFile::ReadOnly); QTextStream orgS(&org); QTextStream outS(&out); QString readin = orgS.readAll(); QString written = outS.readAll(); QCOMPARE(readin, written); } void TestGitStorage::testGitStorageCloudMerge3() { // create multi line notes and store them to the cloud repo and local cache // edit dive notes offline // edit the same dive notes in the cloud repo // merge // (1) open repo, edit notes of first three dives QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); process_loaded_dives(); struct dive *dive; QVERIFY((dive = get_dive(0)) != 0); free(dive->notes); dive->notes = strdup("Create multi line dive notes\nLine 2\nLine 3\nLine 4\nLine 5\nThat should be enough"); QVERIFY((dive = get_dive(1)) != 0); free(dive->notes); dive->notes = strdup("Create multi line dive notes\nLine 2\nLine 3\nLine 4\nLine 5\nThat should be enough"); QVERIFY((dive = get_dive(2)) != 0); free(dive->notes); dive->notes = strdup("Create multi line dive notes\nLine 2\nLine 3\nLine 4\nLine 5\nThat should be enough"); QCOMPARE(save_dives(qPrintable(cloudTestRepo)), 0); clear_dive_file_data(); // (2) make different edits offline QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); process_loaded_dives(); QVERIFY((dive = get_dive(0)) != 0); free(dive->notes); dive->notes = strdup("Create multi line dive notes\nDifferent line 2 and removed 3-5\n\nThat should be enough"); QVERIFY((dive = get_dive(1)) != 0); free(dive->notes); dive->notes = strdup("Line 2\nLine 3\nLine 4\nLine 5"); // keep the middle, remove first and last"); QVERIFY((dive = get_dive(2)) != 0); free(dive->notes); dive->notes = strdup("single line dive notes"); git_local_only = true; QCOMPARE(save_dives(qPrintable(cloudTestRepo)), 0); git_local_only = false; clear_dive_file_data(); // (3) simulate a second system by moving the cache away and open the cloud storage repo and modify // those first dive notes differently while online moveDir(localCacheDir, localCacheDir + "save"); QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); process_loaded_dives(); QVERIFY((dive = get_dive(0)) != 0); free(dive->notes); dive->notes = strdup("Completely different dive notes\nBut also multi line"); QVERIFY((dive = get_dive(1)) != 0); free(dive->notes); dive->notes = strdup("single line dive notes"); QVERIFY((dive = get_dive(2)) != 0); free(dive->notes); dive->notes = strdup("Line 2\nLine 3\nLine 4\nLine 5"); // keep the middle, remove first and last"); QCOMPARE(save_dives(qPrintable(cloudTestRepo)), 0); clear_dive_file_data(); // (4) move the saved local cache back into place and open the cloud repo -> this forces a merge moveDir(localCacheDir + "save", localCacheDir); QCOMPARE(parse_file(qPrintable(cloudTestRepo), &dive_table, &trip_table, &dive_site_table, &device_table, &filter_preset_table), 0); QCOMPARE(save_dives("./SampleDivesMerge3.ssrf"), 0); // we are not trying to compare this to a pre-determined result... what this test // checks is that there are no parsing errors with the merge } QTEST_GUILESS_MAIN(TestGitStorage)
janmulder/subsurface
tests/testgitstorage.cpp
C++
gpl-2.0
20,719
/** * OWASP Benchmark Project v1.2beta * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, version 2. * * The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest01565") public class BenchmarkTest01565 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String[] values = request.getParameterValues("vector"); String param; if (values != null && values.length > 0) param = values[0]; else param = ""; String bar = new Test().doSomething(param); // Code based on example from: // http://examples.javacodegeeks.com/core-java/crypto/encrypt-decrypt-file-stream-with-des/ // 8-byte initialization vector byte[] iv = { (byte)0xB2, (byte)0x12, (byte)0xD5, (byte)0xB2, (byte)0x44, (byte)0x21, (byte)0xC3, (byte)0xC3033 }; try { javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("DES/CBC/PKCS5Padding"); // Prepare the cipher to encrypt javax.crypto.SecretKey key = javax.crypto.KeyGenerator.getInstance("DES").generateKey(); java.security.spec.AlgorithmParameterSpec paramSpec = new javax.crypto.spec.IvParameterSpec(iv); c.init(javax.crypto.Cipher.ENCRYPT_MODE, key, paramSpec); // encrypt and store the results byte[] input = { (byte)'?' }; Object inputParam = bar; if (inputParam instanceof String) input = ((String) inputParam).getBytes(); if (inputParam instanceof java.io.InputStream) { byte[] strInput = new byte[1000]; int i = ((java.io.InputStream) inputParam).read(strInput); if (i == -1) { response.getWriter().println("This input source requires a POST, not a GET. Incompatible UI for the InputStream source."); return; } input = java.util.Arrays.copyOf(strInput, i); } byte[] result = c.doFinal(input); java.io.File fileTarget = new java.io.File( new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir),"passwordFile.txt"); java.io.FileWriter fw = new java.io.FileWriter(fileTarget,true); //the true will append the new data fw.write("secret_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n"); fw.close(); response.getWriter().println("Sensitive value: '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input)) + "' encrypted and stored<br/>"); } catch (java.security.NoSuchAlgorithmException e) { response.getWriter().println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (javax.crypto.NoSuchPaddingException e) { response.getWriter().println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (javax.crypto.IllegalBlockSizeException e) { response.getWriter().println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (javax.crypto.BadPaddingException e) { response.getWriter().println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (java.security.InvalidKeyException e) { response.getWriter().println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (java.security.InvalidAlgorithmParameterException e) { response.getWriter().println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String) executed"); } // end doPost private class Test { public String doSomething(String param) throws ServletException, IOException { String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param); return bar; } } // end innerclass Test } // end DataflowThruInnerClass
thc202/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01565.java
Java
gpl-2.0
5,690
<?php /** * * Precise Similar Topics [French] * Translated by Geolim4.com & Galixte (http://www.galixte.com) * * @copyright (c) 2013 Matt Friedman * @license GNU General Public License, version 2 (GPL-2.0) * */ /** * DO NOT CHANGE */ if (!defined('IN_PHPBB')) { exit; } if (empty($lang) || !is_array($lang)) { $lang = array(); } // DEVELOPERS PLEASE NOTE // // All language files should use UTF-8 as their encoding and the files must not contain a BOM. // // Placeholders can now contain order information, e.g. instead of // 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows // translators to re-order the output of data while ensuring it remains correct // // You do not need this where single placeholders are used, e.g. 'Message %d' is fine // equally where a string contains only two placeholders which are used to wrap text // in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine /** * EXTENSION-DEVELOPERS PLEASE NOTE * * You are able to put your permission sets into your extension. * The permissions logic should be added via the 'core.permissions' event. * You can easily add new permission categories, types and permissions, by * simply merging them into the respective arrays. * The respective language strings should be added into a language file, that * start with 'permissions_', so they are automatically loaded within the ACP. */ // User Permissions $lang = array_merge($lang, array( 'ACL_U_SIMILARTOPICS' => 'Peut voir les sujets similaires', ));
Mauron/similartopics
language/fr/permissions_similar_topics.php
PHP
gpl-2.0
1,528
<?php /** * @package Joomla.Platform * @subpackage Updater * * @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; jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); jimport('joomla.filesystem.path'); jimport('joomla.base.adapter'); jimport('joomla.utilities.arrayhelper'); /** * Updater Class * * @since 11.1 */ class JUpdater extends JAdapter { /** * Development snapshots, nightly builds, pre-release versions and so on * * @const integer * @since 3.4 */ const STABILITY_DEV = 0; /** * Alpha versions (work in progress, things are likely to be broken) * * @const integer * @since 3.4 */ const STABILITY_ALPHA = 1; /** * Beta versions (major functionality in place, show-stopper bugs are likely to be present) * * @const integer * @since 3.4 */ const STABILITY_BETA = 2; /** * Release Candidate versions (almost stable, minor bugs might be present) * * @const integer * @since 3.4 */ const STABILITY_RC = 3; /** * Stable versions (production quality code) * * @const integer * @since 3.4 */ const STABILITY_STABLE = 4; /** * @var JUpdater JUpdater instance container. * @since 11.3 */ protected static $instance; /** * Constructor * * @since 11.1 */ public function __construct() { // Adapter base path, class prefix parent::__construct(__DIR__, 'JUpdater'); } /** * Returns a reference to the global Installer object, only creating it * if it doesn't already exist. * * @return JUpdater An installer object * * @since 11.1 */ public static function getInstance() { if (!isset(self::$instance)) { self::$instance = new JUpdater; } return self::$instance; } /** * Finds the update for an extension. Any discovered updates are stored in the #__updates table. * * @param int|array $eid Extension Identifier or list of Extension Identifiers; if zero use all * sites * @param integer $cacheTimeout How many seconds to cache update information; if zero, force reload the * update information * @param integer $minimum_stability Minimum stability for the updates; 0=dev, 1=alpha, 2=beta, 3=rc, * 4=stable * @param boolean $includeCurrent Should I include the current version in the results? * * @return boolean True if there are updates * * @since 11.1 */ public function findUpdates($eid = 0, $cacheTimeout = 0, $minimum_stability = self::STABILITY_STABLE, $includeCurrent = false) { $retval = false; $results = $this->getUpdateSites($eid); if (empty($results)) { return $retval; } $now = time(); $earliestTime = $now - $cacheTimeout; $sitesWithUpdates = array(); if ($cacheTimeout > 0) { $sitesWithUpdates = $this->getSitesWithUpdates($earliestTime); } foreach ($results as $result) { /** * If we have already checked for updates within the cache timeout period we will report updates available * only if there are update records matching this update site. Then we skip processing of the update site * since it's already processed within the cache timeout period. */ if (($cacheTimeout > 0) && isset($result['last_check_timestamp']) && ($result['last_check_timestamp'] >= $earliestTime)) { $retval = $retval || in_array($result['update_site_id'], $sitesWithUpdates); continue; } $updateObjects = $this->getUpdateObjectsForSite($result, $minimum_stability, $includeCurrent); if (!empty($updateObjects)) { $retval = true; /** @var JTableUpdate $update */ foreach ($updateObjects as $update) { $update->store(); } } // Finally, update the last update check timestamp $this->updateLastCheckTimestamp($result['update_site_id']); } return $retval; } /** * Finds an update for an extension * * @param integer $id Id of the extension * * @return mixed * * @since 3.5.2 */ public function update($id) { $updaterow = JTable::getInstance('update'); $updaterow->load($id); $update = new JUpdate; if ($update->loadFromXml($updaterow->detailsurl)) { return $update->install(); } return false; } /** * Returns the update site records for an extension with ID $eid. If $eid is zero all enabled update sites records * will be returned. * * @param int $eid The extension ID to fetch. * * @return array * * @since 3.5.2 */ private function getUpdateSites($eid = 0) { $db = $this->getDbo(); $query = $db->getQuery(true); $query->select('DISTINCT a.update_site_id, a.type, a.location, a.last_check_timestamp, a.extra_query') ->from($db->quoteName('#__update_sites', 'a')) ->where('a.enabled = 1'); if ($eid) { $query->join('INNER', '#__update_sites_extensions AS b ON a.update_site_id = b.update_site_id'); if (is_array($eid)) { $query->where('b.extension_id IN (' . implode(',', $eid) . ')'); } elseif ((int) $eid) { $query->where('b.extension_id = ' . $eid); } } $db->setQuery($query); $result = $db->loadAssocList(); if (!is_array($result)) { return array(); } return $result; } /** * Loads the contents of an update site record $updateSite and returns the update objects * * @param array $updateSite The update site record to process * @param int $minimum_stability Minimum stability for the returned update records * @param bool $includeCurrent Should I also include the current version? * * @return array The update records. Empty array if no updates are found. * * @since 3.5.2 */ private function getUpdateObjectsForSite($updateSite, $minimum_stability = self::STABILITY_STABLE, $includeCurrent = false) { $retVal = array(); $this->setAdapter($updateSite['type']); if (!isset($this->_adapters[$updateSite['type']])) { // Ignore update sites requiring adapters we don't have installed return $retVal; } $updateSite['minimum_stability'] = $minimum_stability; // Get the update information from the remote update XML document /** @var JUpdateAdapter $adapter */ $adapter = $this->_adapters[ $updateSite['type']]; $update_result = $adapter->findUpdate($updateSite); // Version comparison operator. $operator = $includeCurrent ? 'ge' : 'gt'; if (is_array($update_result)) { // If we have additional update sites in the remote (collection) update XML document, parse them if (array_key_exists('update_sites', $update_result) && count($update_result['update_sites'])) { $thisUrl = trim($updateSite['location']); $thisId = (int) $updateSite['update_site_id']; foreach ($update_result['update_sites'] as $extraUpdateSite) { $extraUrl = trim($extraUpdateSite['location']); $extraId = (int) $extraUpdateSite['update_site_id']; // Do not try to fetch the same update site twice if (($thisId == $extraId) || ($thisUrl == $extraUrl)) { continue; } $extraUpdates = $this->getUpdateObjectsForSite($extraUpdateSite, $minimum_stability); if (count($extraUpdates)) { $retVal = array_merge($retVal, $extraUpdates); } } } if (array_key_exists('updates', $update_result) && count($update_result['updates'])) { /** @var JUpdate $current_update */ foreach ($update_result['updates'] as $current_update) { $current_update->extra_query = $updateSite['extra_query']; /** @var JTableUpdate $update */ $update = JTable::getInstance('update'); /** @var JTableExtension $extension */ $extension = JTable::getInstance('extension'); $uid = $update ->find( array( 'element' => $current_update->get('element'), 'type' => $current_update->get('type'), 'client_id' => $current_update->get('client_id'), 'folder' => $current_update->get('folder') ) ); $eid = $extension ->find( array( 'element' => $current_update->get('element'), 'type' => $current_update->get('type'), 'client_id' => $current_update->get('client_id'), 'folder' => $current_update->get('folder') ) ); if (!$uid) { // Set the extension id if ($eid) { // We have an installed extension, check the update is actually newer $extension->load($eid); $data = json_decode($extension->manifest_cache, true); if (version_compare($current_update->version, $data['version'], $operator) == 1) { $current_update->extension_id = $eid; $retVal[] = $current_update; } } else { // A potentially new extension to be installed $retVal[] = $current_update; } } else { $update->load($uid); // If there is an update, check that the version is newer then replaces if (version_compare($current_update->version, $update->version, $operator) == 1) { $retVal[] = $current_update; } } } } } return $retVal; } /** * Returns the IDs of the update sites with cached updates * * @param int $timestamp Optional. If set, only update sites checked before $timestamp will be taken into * account. * * @return array The IDs of the update sites with cached updates * * @since 3.5.2 */ private function getSitesWithUpdates($timestamp = 0) { $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select('DISTINCT update_site_id') ->from('#__updates'); if ($timestamp) { $subQuery = $db->getQuery(true) ->select('update_site_id') ->from('#__update_sites') ->where($db->qn('last_check_timestamp') . ' IS NULL', 'OR') ->where($db->qn('last_check_timestamp') . ' <= ' . $db->q($timestamp), 'OR'); $query->where($db->qn('update_site_id') . ' IN (' . $subQuery . ')'); } $retVal = $db->setQuery($query)->loadColumn(0); if (empty($retVal)) { return array(); } return $retVal; } /** * Update the last check timestamp of an update site * * @param int $updateSiteId The update site ID to mark as just checked * * @return void * * @since 3.5.2 */ private function updateLastCheckTimestamp($updateSiteId) { $timestamp = time(); $db = JFactory::getDbo(); $query = $db->getQuery(true) ->update($db->quoteName('#__update_sites')) ->set($db->quoteName('last_check_timestamp') . ' = ' . $db->quote($timestamp)) ->where($db->quoteName('update_site_id') . ' = ' . $db->quote($updateSiteId)); $db->setQuery($query); $db->execute(); } }
wnnz34/joomla-cms
libraries/joomla/updater/updater.php
PHP
gpl-2.0
10,978
<?php /** * A resource representing an SMSGlobal shared pool * * @package Smsglobal\RestApiClient\Resource */ class Smsglobal_RestApiClient_Resource_SharedPool extends Smsglobal_RestApiClient_Resource_Base { /** * Name * @var string */ protected $name; /** * Size * @var int */ protected $size; /** * Sets the name * * @param string $name The name of this shared pool * * @return $this Provides a fluent interface */ public function setName($name) { $this->name = $name; return $this; } /** * Gets the name * * @return string */ public function getName() { return $this->name; } /** * Gets the size * * @return int */ public function getSize() { return $this->size; } }
smsglobal/smsglobal-wordpress-plugin
vendor/rest-api-client-php-5.2/Smsglobal/RestApiClient/Resource/SharedPool.php
PHP
gpl-2.0
869
<?php namespace Illuminate\Database\Capsule; use PDO; use Illuminate\Support\Fluent; use Illuminate\Container\Container; use Illuminate\Database\DatabaseManager; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Database\Eloquent\Model as Eloquent; use Illuminate\Database\Connectors\ConnectionFactory; use Illuminate\Support\Traits\CapsuleManagerTrait; class Manager { use CapsuleManagerTrait; /** * The database manager instance. * * @var \Illuminate\Database\DatabaseManager */ protected $manager; /** * Create a new database capsule manager. * * @param \Illuminate\Container\Container|null $container * @return void */ public function __construct(Container $container = null) { $this->setupContainer($container ?: new Container); // Once we have the container setup, we will setup the default configuration // options in the container "config" binding. This will make the database // manager behave correctly since all the correct binding are in place. $this->setupDefaultConfiguration(); $this->setupManager(); } /** * Setup the default database configuration options. * * @return void */ protected function setupDefaultConfiguration() { $this->container['config']['database.fetch'] = PDO::FETCH_ASSOC; $this->container['config']['database.default'] = 'default'; } /** * Build the database manager instance. * * @return void */ protected function setupManager() { $factory = new ConnectionFactory($this->container); $this->manager = new DatabaseManager($this->container, $factory); } /** * Get a connection instance from the global manager. * * @param string $connection * @return \Illuminate\Database\Connection */ public static function connection($connection = null) { return static::$instance->getConnection($connection); } /** * Get a fluent query builder instance. * * @param string $table * @param string $connection * @return \Illuminate\Database\Query\Builder */ public static function table($table, $connection = null) { return static::$instance->connection($connection)->table($table); } /** * Get a schema builder instance. * * @param string $connection * @return \Illuminate\Database\Schema\Builder */ public static function schema($connection = null) { return static::$instance->connection($connection)->getSchemaBuilder(); } /** * Get a registered connection instance. * * @param string $name * @return \Illuminate\Database\Connection */ public function getConnection($name = null) { return $this->manager->connection($name); } /** * Register a connection with the manager. * * @param array $config * @param string $name * @return void */ public function addConnection(array $config, $name = 'default') { $connections = $this->container['config']['database.connections']; $connections[$name] = $config; $this->container['config']['database.connections'] = $connections; } /** * Bootstrap Eloquent so it is ready for usage. * * @return void */ public function bootEloquent() { Eloquent::setConnectionResolver($this->manager); // If we have an event dispatcher instance, we will go ahead and register it // with the Eloquent ORM, allowing for model callbacks while creating and // updating "model" instances; however, if it not necessary to operate. if ($dispatcher = $this->getEventDispatcher()) { Eloquent::setEventDispatcher($dispatcher); } } /** * Set the fetch mode for the database connections. * * @param int $fetchMode * @return $this */ public function setFetchMode($fetchMode) { $this->container['config']['database.fetch'] = $fetchMode; return $this; } /** * Get the database manager instance. * * @return \Illuminate\Database\DatabaseManager */ public function getDatabaseManager() { return $this->manager; } /** * Get the current event dispatcher instance. * * @return \Illuminate\Contracts\Events\Dispatcher */ public function getEventDispatcher() { if ($this->container->bound('events')) { return $this->container['events']; } } /** * Set the event dispatcher instance to be used by connections. * * @param \Illuminate\Contracts\Events\Dispatcher $dispatcher * @return void */ public function setEventDispatcher(Dispatcher $dispatcher) { $this->container->instance('events', $dispatcher); } /** * Dynamically pass methods to the default connection. * * @param string $method * @param array $parameters * @return mixed */ public static function __callStatic($method, $parameters) { return call_user_func_array(array(static::connection(), $method), $parameters); } }
teknic/musicapp
vendor/laravel/framework/src/Illuminate/Database/Capsule/Manager.php
PHP
gpl-2.0
4,733
/////////////////////////////////////////////////////////////////////////////// // For information as to what this class does, see the Javadoc, below. // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, // // 2007, 2008, 2009, 2010, 2014, 2015 by Peter Spirtes, Richard Scheines, Joseph // // Ramsey, and Clark Glymour. // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation; either version 2 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program; if not, write to the Free Software // // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /////////////////////////////////////////////////////////////////////////////// package edu.cmu.tetrad.search; import edu.cmu.tetrad.data.*; import edu.cmu.tetrad.graph.*; import edu.cmu.tetrad.sem.*; import edu.cmu.tetrad.util.ChoiceGenerator; import edu.cmu.tetrad.util.MatrixUtils; import edu.cmu.tetrad.util.TetradLogger; import java.util.*; /** * Purify is a implementation of the automated purification methods described on CPS and the report "Learning * Measurement Models" CMU-CALD-03-100. * <p> * No background knowledge is allowed yet. Future versions of this algorithm will include it. * <p> * References: * <p> * Silva, R.; Scheines, R.; Spirtes, P.; Glymour, C. (2003). "Learning measurement models". Technical report * CMU-CALD-03-100, Center for Automated Learning and Discovery, Carnegie Mellon University. * <p> * Bollen, K. (1990). "Outlier screening and distribution-free test for vanishing tetrads." Sociological Methods and * Research 19, 80-92. * <p> * Drton, M. and Richardson, T. (2003). "Iterative conditional fitting for Gaussian ancestral graphical models". * Technical report, Department of Statistics, University of Washington. * <p> * Wishart, J. (1928). "Sampling errors in the theory of two factors". British Journal of Psychology 19, 180-187. * * @author Ricardo Silva */ public class Purify { private boolean outputMessage; /** * Data storage */ private CorrelationMatrix correlationMatrix; private DataSet dataSet; private Clusters clusters; private int constraintSearchVariation = 0; private List forbiddenList; private int numVars; private TetradTest tetradTest; /** * The logger for this class. The config needs to be set. */ private TetradLogger logger = TetradLogger.getInstance(); private List<Node> variables; /********************************************************* * INITIALIZATION o *********************************************************/ /* * Constructor Purify */ public Purify(CorrelationMatrix correlationMatrix, double sig, TestType testType, Clusters clusters) { if (DataUtils.containsMissingValue(correlationMatrix.getMatrix())) { throw new IllegalArgumentException( "Please remove or impute missing data first."); } this.correlationMatrix = correlationMatrix; initAlgorithm(sig, testType, clusters); if (testType == TestType.TETRAD_DELTA) { throw new RuntimeException( "Covariance/correlation matrix is not enough to " + "run Bollen's tetrad test."); } this.variables = correlationMatrix.getVariables(); } public Purify(DataSet dataSet, double sig, TestType testType, Clusters clusters) { if (DataUtils.containsMissingValue(dataSet)) { throw new IllegalArgumentException( "Please remove or impute missing data first."); } if (dataSet.isContinuous()) { correlationMatrix = new CorrelationMatrix(dataSet); this.dataSet = dataSet; initAlgorithm(sig, testType, clusters); } else { this.dataSet = dataSet; initAlgorithm(sig, testType, clusters); } this.variables = dataSet.getVariables(); } public Purify(TetradTest tetradTest, Clusters knowledge) { this.tetradTest = tetradTest; initAlgorithm(-1., TestType.NONE, knowledge); this.variables = tetradTest.getVariables(); } public void setForbiddenList(List forbiddenList) { this.forbiddenList = forbiddenList; } private void initAlgorithm(double sig, TestType testType, Clusters clusters) { this.clusters = clusters; this.forbiddenList = null; if (this.tetradTest == null) { if (correlationMatrix != null) { // Should type these ones. TestType type = testType; if (testType == TestType.TETRAD_DELTA) { tetradTest = new ContinuousTetradTest(dataSet, type, sig); } else { tetradTest = new ContinuousTetradTest(correlationMatrix, type, sig); } } else { tetradTest = new DiscreteTetradTest(dataSet, sig); } } numVars = tetradTest.getVarNames().length; outputMessage = true; } public void setConstraintSearchVariation(int type) { this.constraintSearchVariation = type; } public void setOutputMessage(boolean outputMessage) { this.outputMessage = outputMessage; } /** * ****************************************************** SEARCH INTERFACE ******************************************************* */ public Graph search() { Graph graph = getResultGraph(); this.logger.log("graph", "\nReturning this graph: " + graph); return graph; } private Graph getResultGraph() { printlnMessage("\n**************Starting Purify search!!!*************\n"); // if (tetradTest instanceof DiscreteTetradTest) { // List pureClusters; // if (constraintSearchVariation == 0) { // pureClusters = tetradBasedPurify(getClusters()); // } else { // pureClusters = tetradBasedPurify2(getClusters()); // } // return convertSearchGraph(pureClusters); // } else { TestType type = ((ContinuousTetradTest) this.tetradTest).getTestType(); // type = TestType.TETRAD_BASED; type = null; if (type == TestType.TETRAD_BASED) { IPurify purifier = new PurifyTetradBased2(tetradTest); List<List<Node>> partition2 = purifier.purify(ClusterUtils.convertIntToList(getClusters(), getVariables())); List<int[]> pureClusters = ClusterUtils.convertListToInt(partition2, getVariables()); return ClusterUtils.convertSearchGraph(pureClusters, tetradTest.getVarNames()); // return convertSearchGraph(pureClusters); // List pureClusters = tetradBasedPurify2(getClusters()); // return convertSearchGraph(pureClusters); } if (type == TestType.GAUSSIAN_SCORE || type == TestType.GAUSSIAN_SCORE_MARKS) { SemGraph semGraph = scoreBasedPurify(getClusters()); return convertSearchGraph(semGraph); } else if (type == TestType.GAUSSIAN_SCORE_ITERATE) { SemGraph semGraphI = scoreBasedPurifyIterate(getClusters()); return convertSearchGraph(semGraphI); } else if (type == TestType.NONE) { SemGraph semGraph3 = dummyPurification(getClusters()); return convertSearchGraph(semGraph3); } else { List pureClusters; // if (constraintSearchVariation == 0) { IPurify purifier = new PurifyTetradBased2(tetradTest); List<List<Node>> partition2 = purifier.purify(ClusterUtils.convertIntToList(getClusters(), tetradTest.getVariables())); pureClusters = ClusterUtils.convertListToInt(partition2, tetradTest.getVariables()); // pureClusters = tetradBasedPurify(getClusters()); // } // else { // pureClusters = tetradBasedPurify2(getClusters()); // } return ClusterUtils.convertSearchGraph(pureClusters, tetradTest.getVarNames()); } } } private List<Node> getVariables() { return this.variables; } private List<int[]> getClusters() { List clusters = new ArrayList(); String varNames[] = tetradTest.getVarNames(); for (int i = 0; i < this.clusters.getNumClusters(); i++) { List clusterS = this.clusters.getCluster(i); int cluster[] = new int[clusterS.size()]; Iterator it = clusterS.iterator(); int count = 0; while (it.hasNext()) { String nextName = (String) it.next(); for (int j = 0; j < varNames.length; j++) { if (varNames[j].equals(nextName)) { cluster[count++] = j; break; } } } clusters.add(cluster); } return clusters; } public static Graph convertSearchGraph(SemGraph input) { if (input == null) { List nodes = new ArrayList(); nodes.add(new GraphNode("No_model.")); return new EdgeListGraph(nodes); } List inputIndicators = new ArrayList(), inputLatents = new ArrayList(); Iterator it = input.getNodes().iterator(); while (it.hasNext()) { Node next = (Node) it.next(); if (next.getNodeType() == NodeType.MEASURED) { inputIndicators.add(next); } else if (next.getNodeType() == NodeType.LATENT) { inputLatents.add(next); } } List allNodes = new ArrayList(inputIndicators); allNodes.addAll(inputLatents); Graph output = new EdgeListGraph(allNodes); Iterator nit1 = input.getNodes().iterator(); while (nit1.hasNext()) { Node node1 = (Node) nit1.next(); Iterator nit2 = input.getNodes().iterator(); while (nit2.hasNext()) { Node node2 = (Node) nit2.next(); Edge edge = input.getEdge(node1, node2); if (edge != null) { if (node1.getNodeType() == NodeType.ERROR && node2.getNodeType() == NodeType.ERROR) { Iterator ci = input.getChildren(node1).iterator(); Node indicator1 = (Node) ci.next(); //Assuming error nodes have only one children in SemGraphs... ci = input.getChildren(node2).iterator(); Node indicator2 = (Node) ci.next(); //Assuming error nodes have only one children in SemGraphs... if (indicator1.getNodeType() != NodeType.LATENT) { output.setEndpoint(indicator1, indicator2, Endpoint.ARROW); output.setEndpoint(indicator2, indicator1, Endpoint.ARROW); } } else if ((node1.getNodeType() != NodeType.LATENT || node2.getNodeType() != NodeType.LATENT) && node1.getNodeType() != NodeType.ERROR && node2.getNodeType() != NodeType.ERROR) { output.setEndpoint(edge.getNode1(), edge.getNode2(), Endpoint.ARROW); output.setEndpoint(edge.getNode2(), edge.getNode1(), Endpoint.TAIL); } } } } for (int i = 0; i < inputLatents.size() - 1; i++) { for (int j = i + 1; j < inputLatents.size(); j++) { output.setEndpoint((Node) inputLatents.get(i), (Node) inputLatents.get(j), Endpoint.TAIL); output.setEndpoint((Node) inputLatents.get(j), (Node) inputLatents.get(i), Endpoint.TAIL); } } return output; } /** * ****************************************************** DEBUG UTILITIES ******************************************************* */ private void printClustering(List clustering) { Iterator it = clustering.iterator(); while (it.hasNext()) { int c[] = (int[]) it.next(); printCluster(c); } } private void printCluster(int c[]) { String sorted[] = new String[c.length]; for (int i = 0; i < c.length; i++) { sorted[i] = tetradTest.getVarNames()[c[i]]; } for (int i = 0; i < sorted.length - 1; i++) { String min = sorted[i]; int min_idx = i; for (int j = i + 1; j < sorted.length; j++) { if (sorted[j].compareTo(min) < 0) { min = sorted[j]; min_idx = j; } } String temp = sorted[i]; sorted[i] = min; sorted[min_idx] = temp; } for (int i = 0; i < sorted.length; i++) { printMessage(sorted[i] + " "); } printlnMessage(); } /*private void printImpurities(int graph[][]) { printlnMessage("*** IMPURITIES:"); for (int i = 0; i < numV - 1; i++) for (int j = i + 1; j < numV; j++) //if (graph[i][j] == EDGE_GRAY || graph[i][j] == EDGE_YELLOW) //if (graph[i][j] == EDGE_BLUE) printlnMessage(labels[i] + " x " + labels[j] + ": " + graph[i][j]); }*/ /*private void printRelations(int graph[][]) { printlnMessage("*** RELATIONS:"); for (int i = 0; i < numV - 1; i++) for (int j = i + 1; j < numV; j++) printlnMessage(labels[i] + " x " + labels[j] + ": " + graph[i][j]); }*/ private void printMessage(String message) { if (outputMessage) { System.out.print(message); } } private void printlnMessage(String message) { if (outputMessage) { System.out.println(message); } } private void printlnMessage() { if (outputMessage) { System.out.println(); } } //private void printlnMessage(boolean flag) { // if (outputMessage) { // System.out.println(flag); // } //} private int sizeCluster(List cluster) { int total = 0; Iterator it = cluster.iterator(); while (it.hasNext()) { int next[] = (int[]) it.next(); total += next.length; } return total; } /** * --------------------------------------------------------------------------------------------------------------- * TETRAD-BASED PURIFY </p> - using tetrad constraints - This method checks if there is any evidence that a node is * impure. If there is not, then it is treated as pure. This is virtually the original Purify as described in CPS. */ private List tetradBasedPurify(List partition) { boolean eliminated[] = new boolean[numVars]; for (int i = 0; i < numVars; i++) { eliminated[i] = false; } printlnMessage("TETRAD-BASED PURIFY:"); printlnMessage("Finding Unidimensional Measurement Models"); printlnMessage(); printlnMessage("Initially Specified Measurement Model"); printlnMessage(); printClustering(partition); printlnMessage(); printlnMessage("INTRA-CONSTRUCT PHASE."); printlnMessage("----------------------"); printlnMessage(); int count = 0; for (Iterator it = partition.iterator(); it.hasNext(); ) { intraConstructPhase2((int[]) it.next(), eliminated, "T" + (++count)); } printlnMessage(); printlnMessage("CROSS-CONSTRUCT PHASE."); printlnMessage("----------------------"); printlnMessage(); crossConstructPhase2(partition, eliminated); printlnMessage(); printlnMessage( "------------------------------------------------------"); printlnMessage("Output Measurement Model"); List output = buildSolution(partition, eliminated); printClustering(output); return output; } /** * Marks for deletion nodes within a single cluster that are part of some tetrad constraint that does not hold * according to a statistical test. </p> False discovery rates will be used to adjust for multiple hypothesis * tests. */ private void intraConstructPhase(int cluster[], boolean eliminated[], String clusterName) { int clusterSize = cluster.length; double pvalues[][][][][] = new double[clusterSize][clusterSize][clusterSize][clusterSize][3]; int numNotEliminated = numNotEliminated(cluster, eliminated); List<Double> allPValues = new ArrayList<Double>(); int numImpurities = 0; Set failures[] = new Set[clusterSize]; for (int i = 0; i < clusterSize; i++) { failures[i] = new HashSet(); } for (int i = 0; i < clusterSize - 3; i++) { if (eliminated[cluster[i]]) { continue; } for (int j = i + 1; j < clusterSize - 2; j++) { if (eliminated[cluster[j]]) { continue; } for (int k = j + 1; k < clusterSize - 1; k++) { if (eliminated[cluster[k]]) { continue; } for (int l = k + 1; l < clusterSize; l++) { if (eliminated[cluster[l]]) { continue; } double p1 = tetradTest.tetradPValue(cluster[i], cluster[j], cluster[k], cluster[l]); double p2 = tetradTest.tetradPValue(cluster[i], cluster[j], cluster[l], cluster[k]); double p3 = tetradTest.tetradPValue(cluster[i], cluster[k], cluster[l], cluster[j]); allPValues.add(p1); allPValues.add(p2); allPValues.add(p3); pvalues[i][j][k][l][0] = p1; pvalues[i][j][k][l][1] = p2; pvalues[i][j][k][l][2] = p3; } } } } if (allPValues.size() == 0) return; Collections.sort(allPValues); System.out.println("numNotEliminated = " + numNotEliminated); System.out.println("allPValues = " + allPValues.size()); int c = 0; while (allPValues.get(c) < tetradTest.getSignificance() * (c + 1.) / allPValues.size()) { c++; } double cutoff = allPValues.get(c); System.out.println("c = " + c + " cutoff = " + allPValues.get(c)); for (int i = 0; i < clusterSize - 3; i++) { if (eliminated[cluster[i]]) { continue; } for (int j = i + 1; j < clusterSize - 2; j++) { if (eliminated[cluster[j]]) { continue; } for (int k = j + 1; k < clusterSize - 1; k++) { if (eliminated[cluster[k]]) { continue; } for (int l = k + 1; l < clusterSize; l++) { if (eliminated[cluster[l]]) { continue; } for (int t = 0; t < 3; t++) { if (pvalues[i][j][k][l][t] < cutoff) { int newFailure[] = new int[4]; newFailure[0] = i; newFailure[1] = j; newFailure[2] = k; newFailure[3] = l; failures[i].add(newFailure); failures[j].add(newFailure); failures[k].add(newFailure); failures[l].add(newFailure); numImpurities++; } } } } } } if (numImpurities > 0) { printlnMessage(clusterName + " -- Original Status: " + numImpurities + " of " + allPValues.size() + " tetrads fail the FDR test."); } else { printlnMessage( clusterName + " -- Original Status: Needs NO pruning."); } while (numImpurities > 0) { // Find a variable in the cluster with the most failures and eliminate it. int max = Integer.MIN_VALUE; int max_index = -1; for (int i = 0; i < clusterSize; i++) { if (!eliminated[cluster[i]] && failures[i].size() > max) { max = failures[i].size(); max_index = i; } } eliminated[cluster[max_index]] = true; // Decrement the number of impurities by the number of failures for that variable. numImpurities -= failures[max_index].size(); // Decrement the number of variables of variables left in the cluster. numNotEliminated--; for (int i = 0; i < clusterSize; i++) { if (eliminated[cluster[i]]) { continue; } Set toRemove = new HashSet(); for (Iterator it = failures[i].iterator(); it.hasNext(); ) { int impurity[] = (int[]) it.next(); for (int j = 0; j < 4; j++) { if (impurity[j] == max_index) { toRemove.add(impurity); break; } } } failures[i].removeAll(toRemove); } if (numNotEliminated < 3) { return; } // totalpvalues = numNotEliminated * (numNotEliminated - 1) * // (numNotEliminated - 2) * (numNotEliminated - 3) * 3; printlnMessage("Dropped " + tetradTest.getVarNames()[cluster[max_index]] + " Without it, " + numImpurities + " of " + allPValues.size() + " fail the FDR test."); } } private void intraConstructPhase2(int _cluster[], boolean eliminated[], String clusterName) { List<Integer> cluster = new ArrayList<Integer>(); for (int i : _cluster) cluster.add(i); int numNotEliminated = numNotEliminated2(cluster, eliminated); int numImpurities = 0; List<Double> allPValues = listPValues(cluster, eliminated, Double.MAX_VALUE); if (allPValues.size() == 0) return; Collections.sort(allPValues); System.out.println(allPValues); System.out.println("numNotEliminated = " + numNotEliminated); System.out.println("allPValues = " + allPValues.size()); double cutoff = 1.; for (int c = 0; c < allPValues.size(); c++) { if (allPValues.get(c) >= tetradTest.getSignificance() * (c + 1.) / allPValues.size()) { cutoff = allPValues.get(c); break; } } if (numImpurities > 0) { printlnMessage(clusterName + " -- Original Status: " + numImpurities + " of " + allPValues.size() + " tetrads fail the FDR test."); } else { printlnMessage( clusterName + " -- Original Status: Needs NO pruning."); } while (numImpurities > 0) { int min = Integer.MAX_VALUE; int minIndex = -1; for (int i : cluster) { if (eliminated[i]) continue; eliminated[i] = true; List<Double> pValues = listPValues(cluster, eliminated, cutoff); if (pValues.size() > min) { min = pValues.size(); minIndex = i; } } if (minIndex != -1) { eliminated[minIndex] = true; numImpurities = min; System.out.println("Dropped " + tetradTest.getVarNames()[cluster.get(minIndex)]); } } } private List<Double> listPValues(List<Integer> cluster, boolean[] eliminated, double cutoff) { if (cluster.size() < 4) return new ArrayList<Double>(); List<Double> pValues = new ArrayList<Double>(); ChoiceGenerator gen = new ChoiceGenerator(cluster.size(), 4); int[] choice; while ((choice = gen.next()) != null) { int i = choice[0]; int j = choice[1]; int k = choice[2]; int l = choice[2]; int ci = cluster.get(i); int cj = cluster.get(j); int ck = cluster.get(k); int cl = cluster.get(l); if (eliminated[ci] || eliminated[cj] || eliminated[ck] || eliminated[cl]) { continue; } double p1 = tetradTest.tetradPValue(ci, cj, ck, cl); double p2 = tetradTest.tetradPValue(ci, cj, cl, ck); double p3 = tetradTest.tetradPValue(ci, ck, cl, cj); if (p1 < cutoff) { pValues.add(p1); } if (p2 < cutoff) { pValues.add(p2); } if (p3 < cutoff) { pValues.add(p3); } } return pValues; } /** * Marks for deletion nodes that are part of some tetrad constraint between two clusters that does not hold * according to a statistical test. </p> False discovery rates will be used to adjust for multiple hypothesis * tests. */ private void crossConstructPhase(List<int[]> partition, boolean eliminated[]) { int numImpurities = 0; List<Double> allPValues = new ArrayList<Double>(); Set failures[][] = new Set[partition.size()][]; for (int i = 0; i < partition.size(); i++) { int cluster[] = partition.get(i); failures[i] = new Set[cluster.length]; for (int j = 0; j < cluster.length; j++) { failures[i][j] = new HashSet(); } } for (int p1 = 0; p1 < partition.size(); p1++) { int cluster1[] = partition.get(p1); for (int p2 = p1 + 1; p2 < partition.size(); p2++) { // if (p1 == p2) { // continue; // } int cluster2[] = partition.get(p2); for (int i = 0; i < cluster1.length - 2; i++) { if (eliminated[cluster1[i]]) { continue; } for (int j = i + 1; j < cluster1.length - 1; j++) { if (eliminated[cluster1[j]]) { continue; } for (int k = j + 1; k < cluster1.length; k++) { if (eliminated[cluster1[k]]) { continue; } for (int l = 0; l < cluster2.length; l++) { if (eliminated[cluster2[l]]) { continue; } allPValues.add(tetradTest.tetradPValue( cluster1[i], cluster1[j], cluster1[k], cluster2[l])); allPValues.add(tetradTest.tetradPValue( cluster1[i], cluster1[j], cluster2[l], cluster1[k])); allPValues.add(tetradTest.tetradPValue( cluster1[i], cluster1[k], cluster2[l], cluster1[j])); } } } } } } if (allPValues.isEmpty()) return; for (int p1 = 0; p1 < partition.size() - 1; p1++) { int cluster1[] = partition.get(p1); for (int p2 = p1 + 1; p2 < partition.size(); p2++) { int cluster2[] = partition.get(p2); for (int i = 0; i < cluster1.length - 1; i++) { if (eliminated[cluster1[i]]) { continue; } for (int j = i + 1; j < cluster1.length; j++) { if (eliminated[cluster1[j]]) { continue; } for (int k = 0; k < cluster2.length - 1; k++) { if (eliminated[cluster2[k]]) { continue; } for (int l = k + 1; l < cluster2.length; l++) { if (eliminated[cluster2[l]]) { continue; } allPValues.add(tetradTest.tetradPValue( cluster1[i], cluster1[j], cluster2[k], cluster2[l])); } } } } } } Collections.sort(allPValues); int c = 0; while (allPValues.get(c) < tetradTest.getSignificance() * (c + 1.) / allPValues.size()) { c++; } double cutoff = allPValues.get(c); System.out.println("c = " + c + " cutoff = " + allPValues.get(c)); double localPValues[] = new double[3]; for (int p1 = 0; p1 < partition.size(); p1++) { int cluster1[] = partition.get(p1); for (int p2 = p1 + 1; p2 < partition.size(); p2++) { // if (p1 == p2) { // continue; // } int cluster2[] = partition.get(p2); for (int i = 0; i < cluster1.length - 2; i++) { if (eliminated[cluster1[i]]) { continue; } for (int j = i + 1; j < cluster1.length - 1; j++) { if (eliminated[cluster1[j]]) { continue; } for (int k = j + 1; k < cluster1.length; k++) { if (eliminated[cluster1[k]]) { continue; } for (int l = 0; l < cluster2.length; l++) { if (eliminated[cluster2[l]]) { continue; } localPValues[0] = tetradTest.tetradPValue( cluster1[i], cluster1[j], cluster1[k], cluster2[l]); localPValues[1] = tetradTest.tetradPValue( cluster1[i], cluster1[j], cluster2[l], cluster1[k]); localPValues[2] = tetradTest.tetradPValue( cluster1[i], cluster1[k], cluster2[l], cluster1[j]); for (int t = 0; t < 3; t++) { if (localPValues[t] < cutoff) { int newFailure[] = new int[4]; newFailure[0] = cluster1[i]; newFailure[1] = cluster1[j]; newFailure[2] = cluster1[k]; newFailure[3] = cluster2[l]; failures[p1][i].add(newFailure); failures[p1][j].add(newFailure); failures[p1][k].add(newFailure); failures[p2][l].add(newFailure); numImpurities++; } } } } } } } } for (int p1 = 0; p1 < partition.size() - 1; p1++) { int cluster1[] = partition.get(p1); for (int p2 = p1 + 1; p2 < partition.size(); p2++) { int cluster2[] = partition.get(p2); for (int i = 0; i < cluster1.length - 1; i++) { if (eliminated[cluster1[i]]) { continue; } for (int j = i + 1; j < cluster1.length; j++) { if (eliminated[cluster1[j]]) { continue; } for (int k = 0; k < cluster2.length - 1; k++) { if (eliminated[cluster2[k]]) { continue; } for (int l = k + 1; l < cluster2.length; l++) { if (eliminated[cluster2[l]]) { continue; } if (tetradTest.tetradPValue(cluster1[i], cluster2[k], cluster1[j], cluster2[l]) < cutoff) { int newFailure[] = new int[4]; newFailure[0] = cluster1[i]; newFailure[1] = cluster1[j]; newFailure[2] = cluster2[k]; newFailure[3] = cluster2[l]; failures[p1][i].add(newFailure); failures[p1][j].add(newFailure); failures[p2][k].add(newFailure); failures[p2][l].add(newFailure); numImpurities++; } } } } } } } if (numImpurities > 0) { printlnMessage("Iteration 1 " + numImpurities + " of " + allPValues.size() + " tetrads fail the FDR test."); } else { printlnMessage("Needs NO pruning."); } while (numImpurities > 0) { int max = Integer.MIN_VALUE; int max_index_p = -1, max_index_i = -1; for (int p = 0; p < partition.size(); p++) { int cluster[] = partition.get(p); for (int i = 0; i < cluster.length; i++) { if (eliminated[cluster[i]]) { continue; } if (failures[p][i].size() > max) { max = failures[p][i].size(); max_index_p = p; max_index_i = i; } } } eliminated[partition.get(max_index_p)[max_index_i]] = true; numImpurities -= failures[max_index_p][max_index_i].size(); for (int p = 0; p < partition.size(); p++) { int cluster[] = partition.get(p); for (int i = 0; i < cluster.length; i++) { if (eliminated[cluster[i]]) { continue; } Set toRemove = new HashSet(); for (Iterator it = failures[p][i].iterator(); it.hasNext(); ) { int impurity[] = (int[]) it.next(); for (int j = 0; j < 4; j++) { if (impurity[j] == partition.get( max_index_p)[max_index_i]) { toRemove.add(impurity); break; } } } failures[p][i].removeAll(toRemove); } } int[] cluster = partition.get(max_index_p); String var = tetradTest.getVarNames()[(cluster[max_index_i])]; printlnMessage("Dropped " + var + " Without it, " + numImpurities + " of " + allPValues.size() + " tetrads fail the FDR test."); } } private void crossConstructPhase2(List<int[]> partition, boolean eliminated[]) { List<Double> allPValues = countCrossConstructPValues(partition, eliminated, Double.MAX_VALUE); if (allPValues.isEmpty()) return; Collections.sort(allPValues); double cutoff = 1.; for (int c = 0; c < allPValues.size(); c++) { if (allPValues.get(c) >= tetradTest.getSignificance() * (c + 1.) / allPValues.size()) { cutoff = allPValues.get(c); break; } } int numImpurities = countCrossConstructPValues(partition, eliminated, cutoff).size(); if (numImpurities > 0) { printlnMessage("Iteration 1 " + numImpurities + " of " + allPValues.size() + " tetrads fail the FDR test."); } else { printlnMessage("Needs NO pruning."); } while (numImpurities > 0) { int min = Integer.MAX_VALUE; int minIndex = -1; List<Integer> minCluster = null; for (int p = 0; p < partition.size(); p++) { int cluster[] = partition.get(p); for (int i = 0; i < cluster.length; i++) { if (eliminated[cluster[i]]) { continue; } eliminated[i] = true; List<Integer> _cluster = new ArrayList<Integer>(); for (int j : cluster) _cluster.add(j); List<Double> pValues = listPValues(_cluster, eliminated, cutoff); if (pValues.size() > min) { min = pValues.size(); minIndex = i; minCluster = new ArrayList<Integer>(minCluster); numImpurities = min; } } } if (minIndex != -1) { eliminated[minIndex] = true; numImpurities = min; System.out.println("Dropped " + tetradTest.getVarNames()[minCluster.get(minIndex)]); } } } private List<Double> countCrossConstructPValues(List<int[]> partition, boolean[] eliminated, double cutoff) { List<Double> allPValues = new ArrayList<Double>(); for (int p1 = 0; p1 < partition.size(); p1++) { for (int p2 = p1 + 1; p2 < partition.size(); p2++) { int cluster1[] = partition.get(p1); int cluster2[] = partition.get(p2); if (cluster1.length >= 3 && cluster2.length >= 1) { ChoiceGenerator gen1 = new ChoiceGenerator(cluster1.length, 3); ChoiceGenerator gen2 = new ChoiceGenerator(cluster2.length, 1); int[] choice1, choice2; while ((choice1 = gen1.next()) != null) { while ((choice2 = gen2.next()) != null) { List<Integer> crossCluster = new ArrayList<Integer>(); for (int i : choice1) crossCluster.add(cluster1[i]); for (int i : choice2) crossCluster.add(cluster2[i]); allPValues.addAll(listPValues(crossCluster, eliminated, cutoff)); } } } if (cluster1.length >= 2 && cluster2.length >= 2) { ChoiceGenerator gen1 = new ChoiceGenerator(cluster1.length, 2); ChoiceGenerator gen2 = new ChoiceGenerator(cluster2.length, 2); int[] choice1, choice2; while ((choice1 = gen1.next()) != null) { while ((choice2 = gen2.next()) != null) { List<Integer> crossCluster = new ArrayList<Integer>(); for (int i : choice1) crossCluster.add(cluster1[i]); for (int i : choice2) crossCluster.add(cluster2[i]); allPValues.addAll(listPValues(crossCluster, eliminated, cutoff)); } } } } } return allPValues; } // The number of variables in cluster that have not been eliminated. private int numNotEliminated(int[] cluster, boolean[] eliminated) { int n1 = 0; for (int i = 0; i < cluster.length; i++) { if (!eliminated[cluster[i]]) { n1++; } } return n1; } private int numNotEliminated2(List<Integer> cluster, boolean[] eliminated) { int n1 = 0; for (int i : cluster) { if (!eliminated[i]) { n1++; } } return n1; } private List buildSolution(List partition, boolean eliminated[]) { List solution = new ArrayList(); Iterator it = partition.iterator(); while (it.hasNext()) { int next[] = (int[]) it.next(); int draftArea[] = new int[next.length]; int draftCount = 0; for (int i = 0; i < next.length; i++) { if (!eliminated[next[i]]) { draftArea[draftCount++] = next[i]; } } int realCluster[] = new int[draftCount]; System.arraycopy(draftArea, 0, realCluster, 0, draftCount); solution.add(realCluster); } return solution; } /** * --------------------------------------------------------------------------------------------------------------- * TETRAD-BASED PURIFY2 </p> - using tetrad constraints - Second variation: this method checks for each pair (X, Y) * if there is another pair (W, Z) such that all three tetrads hold in (X, Y, W, Z). If not, this pair is marked as * impure. This is more likely to leave true impurities in the estimated graph, but on the other hand it tends to * remove less true pure indicators. We also do not use all variables as the domain of (W, Z): only those in the * given partition, in order to reduce the number of false positives. In my opinion, tetradBasedPurify2 is a better * compromise thatn tetradBasedPurify1, but one might want to test it with a larger variety of graphical structures * and sample size. </p> -- Ricardo Silva */ private final int PURE = 0; private final int IMPURE = 1; private final int UNDEFINED = 2; private List tetradBasedPurify2(List partition) { boolean impurities[][] = tetradBasedMarkImpurities(partition); List solution = findInducedPureGraph(partition, impurities); if (solution != null) { /*printlnMessage("--Solution"); Iterator it = solution.iterator(); while (it.hasNext()) { int c[] = (int[]) it.next(); for (int v = 0; v < c.length; v++) { printlnMessage(this.tetradTest.getVariableNames()[c[v]] + " "); } printlnMessage(); }*/ printlnMessage(">> SIZE: " + sizeCluster(solution)); printlnMessage(">> New solution found!"); } return solution; } /** * Verify if a pair of indicators is impure, or if there is no evidence they are pure. */ private boolean[][] tetradBasedMarkImpurities(List clustering) { printlnMessage(" (searching for impurities....)"); int relations[][] = new int[numVars][numVars]; for (int i = 0; i < numVars; i++) { for (int j = 0; j < numVars; j++) { if (i == j) { relations[i][j] = PURE; } else { relations[i][j] = UNDEFINED; } } } //Find intra-construct impurities for (int i = 0; i < clustering.size(); i++) { int cluster1[] = (int[]) clustering.get(i); if (cluster1.length < 3) { continue; } for (int j = 0; j < cluster1.length - 1; j++) { for (int k = j + 1; k < cluster1.length; k++) { if (relations[cluster1[j]][cluster1[k]] == UNDEFINED) { boolean found = false; //Try to find a 3x1 foursome that includes j and k for (int q = 0; q < cluster1.length && !found; q++) { if (j == q || k == q) { continue; } for (int l = 0; l < clustering.size() && !found; l++) { int cluster2[] = (int[]) clustering.get(l); for (int w = 0; w < cluster2.length && !found; w++) { if (l == i && (j == w || k == w || q == w)) { continue; } if (tetradTest.tetradScore3(cluster1[j], cluster1[k], cluster1[q], cluster2[w])) { found = true; relations[cluster1[j]][cluster1[k]] = relations[cluster1[k]][cluster1[j]] = PURE; relations[cluster1[j]][cluster1[q]] = relations[cluster1[q]][cluster1[j]] = PURE; relations[cluster1[k]][cluster1[q]] = relations[cluster1[q]][cluster1[k]] = PURE; } } } } } } } } //Find cross-construct impurities for (int i = 0; i < clustering.size(); i++) { int cluster1[] = (int[]) clustering.get(i); for (int j = 0; j < clustering.size(); j++) { if (i == j) { continue; } int cluster2[] = (int[]) clustering.get(j); for (int v1 = 0; v1 < cluster1.length; v1++) { for (int v2 = 0; v2 < cluster2.length; v2++) { if (relations[cluster1[v1]][cluster2[v2]] == UNDEFINED) { boolean found1 = false; //Try first to find a 3x1 foursome, with 3 elements //in cluster1 if (cluster1.length < 3) { found1 = true; } for (int v3 = 0; v3 < cluster1.length && !found1; v3++) { if (v3 == v1 || relations[cluster1[v1]][cluster1[v3]] == IMPURE || relations[cluster2[v2]][cluster1[v3]] == IMPURE) { continue; } for (int v4 = 0; v4 < cluster1.length && !found1; v4++) { if (v4 == v1 || v4 == v3 || relations[cluster1[v1]][cluster1[v4]] == IMPURE || relations[cluster2[v2]][cluster1[v4]] == IMPURE || relations[cluster1[v3]][cluster1[v4]] == IMPURE) { continue; } if (tetradTest.tetradScore3(cluster1[v1], cluster2[v2], cluster1[v3], cluster1[v4])) { found1 = true; } } } if (!found1) { continue; } boolean found2 = false; //Try to find a 3x1 foursome, now with 3 elements //in cluster2 if (cluster2.length < 3) { found2 = true; relations[cluster1[v1]][cluster2[v2]] = relations[cluster2[v2]][cluster1[v1]] = PURE; continue; } for (int v3 = 0; v3 < cluster2.length && !found2; v3++) { if (v3 == v2 || relations[cluster1[v1]][cluster2[v3]] == IMPURE || relations[cluster2[v2]][cluster2[v3]] == IMPURE) { continue; } for (int v4 = 0; v4 < cluster2.length && !found2; v4++) { if (v4 == v2 || v4 == v3 || relations[cluster1[v1]][cluster2[v4]] == IMPURE || relations[cluster2[v2]][cluster2[v4]] == IMPURE || relations[cluster2[v3]][cluster2[v4]] == IMPURE) { continue; } if (tetradTest.tetradScore3(cluster1[v1], cluster2[v2], cluster2[v3], cluster2[v4])) { found2 = true; relations[cluster1[v1]][cluster2[v2]] = relations[cluster2[v2]][cluster1[v1]] = PURE; } } } } } } } } boolean impurities[][] = new boolean[numVars][numVars]; for (int i = 0; i < numVars; i++) { for (int j = 0; j < numVars; j++) { if (relations[i][j] == UNDEFINED) { impurities[i][j] = true; } else { impurities[i][j] = false; } } } return impurities; } private SemGraph dummyPurification(List partition) { structuralEmInitialization(partition); SemGraph bestGraph = this.purePartitionGraph; return bestGraph; } // SCORE-BASED PURIFY </p> - using BIC score function and Structural EM for // search. Probabilistic model is Gaussian. - search operator consists only // of adding a bi-directed edge between pairs of error variables - after // such pairs are found, an heuristic is applied to eliminate one member of // each pair - this methods tends to be much slower than the "tetradBased" // ones. double Cyy[][], Cyz[][], Czz[][], bestCyy[][], bestCyz[][], bestCzz[][]; double covErrors[][], oldCovErrors[][], sampleCovErrors[][], betas[][], oldBetas[][]; double betasLat[][], varErrorLatent[]; double omega[][], omegaI[], parentsResidualsCovar[][][], iResidualsCovar[], selectedInverseOmega[][][], auxInverseOmega[][][]; int spouses[][], nSpouses[], parents[][], parentsLat[][]; double parentsCov[][][], parentsChildCov[][], parentsLatCov[][][], parentsChildLatCov[][]; double pseudoParentsCov[][][], pseudoParentsChildCov[][]; boolean parentsL[][]; int numObserved, numLatent, clusterId[]; Hashtable observableNames, latentNames; SemGraph purePartitionGraph; Graph basicGraph; ICovarianceMatrix covarianceMatrix; boolean correlatedErrors[][], latentParent[][], observedParent[][]; List latentNodes, measuredNodes; SemIm currentSemIm; boolean modifiedGraph; boolean extraDebugPrint = false; private SemGraph scoreBasedPurify(List partition) { structuralEmInitialization(partition); SemGraph bestGraph = this.purePartitionGraph; System.out.println(">>>> Structural EM: initial round"); //gaussianEM(bestGraph, null); for (int i = 0; i < correlatedErrors.length; i++) { for (int j = 0; j < correlatedErrors.length; j++) { correlatedErrors[i][j] = false; } } for (int i = 0; i < numObserved; i++) { for (int j = 0; j < numLatent; j++) { Node latentNode = purePartitionGraph.getNode( this.latentNodes.get(j).toString()); Node measuredNode = purePartitionGraph.getNode( this.measuredNodes.get(i).toString()); latentParent[i][j] = purePartitionGraph.isParentOf(latentNode, measuredNode); } for (int j = i; j < numObserved; j++) { observedParent[i][j] = observedParent[j][i] = false; } } do { this.modifiedGraph = false; double score = gaussianEM(bestGraph, null); printlnMessage("Initial score" + score); impurityScoreSearch(score); if (this.modifiedGraph) { printlnMessage(">>>> Structural EM: starting a new round"); bestGraph = updatedGraph(); //SemIm nextSemIm = getNextSemIm(bestGraph); //gaussianEM(bestGraph, nextSemIm); } } while (this.modifiedGraph); boolean impurities[][] = new boolean[numObserved][numObserved]; for (int i = 0; i < numObserved; i++) { List parents = bestGraph.getParents( bestGraph.getNode(this.measuredNodes.get(i).toString())); if (parents.size() > 1) { boolean latent_found = false; for (Iterator it = parents.iterator(); it.hasNext(); ) { Node parent = (Node) it.next(); if (parent.getNodeType() == NodeType.LATENT) { if (latent_found) { impurities[i][i] = true; break; } else { latent_found = true; } } } } else { impurities[i][i] = false; } for (int j = i + 1; j < numObserved; j++) { impurities[i][j] = correlatedErrors[i][j] || observedParent[i][j] || observedParent[j][i]; impurities[j][i] = impurities[i][j]; } } if (((ContinuousTetradTest) this.tetradTest).getTestType() == TestType.GAUSSIAN_SCORE) { bestGraph = removeMarkedImpurities(bestGraph, impurities); } return bestGraph; } /** * Second main method of this variation of Purify */ private SemGraph scoreBasedPurifyIterate(List partition) { boolean changed; int iter = 0; do { changed = false; printlnMessage( "####Iterated score-based purification: round" + (++iter)); scoreBasedPurify(partition); if (numObserved == 0) { return null; } int numImpurities[] = new int[numObserved]; for (int i = 0; i < numObserved; i++) { numImpurities[i] = 0; } for (int i = 0; i < numObserved; i++) { for (int j = i + 1; j < numObserved; j++) { if (correlatedErrors[i][j] || observedParent[i][j] || observedParent[j][i]) { numImpurities[i]++; numImpurities[j]++; changed = true; } } } if (changed) { int max = numImpurities[0]; List choices = new ArrayList(); choices.add(0); for (int i = 1; i < numObserved; i++) { if (numImpurities[i] > max) { choices.clear(); choices.add(i); max = numImpurities[i]; } else if (numImpurities[i] == max) { choices.add(i); } } int choice = (Integer) choices.get(0); int chosenCluster[] = (int[]) partition.get(clusterId[choice]); for (Iterator it = choices.iterator(); it.hasNext(); ) { int nextChoice = (Integer) it.next(); int nextCluster[] = (int[]) partition.get(clusterId[nextChoice]); if ((nextCluster.length > chosenCluster.length && chosenCluster.length >= 3) || ( nextCluster.length < chosenCluster.length && nextCluster.length < 3)) { choice = nextChoice; chosenCluster = nextCluster; } } printlnMessage( "!! Removing " + measuredNodes.get(choice).toString()); List newPartition = new ArrayList(); int count = 0; for (Iterator it = partition.iterator(); it.hasNext(); ) { int next[] = (int[]) it.next(); if (choice >= count + next.length) { newPartition.add(next); } else { int newCluster[] = new int[next.length - 1]; for (int i = 0; i < next.length; i++) { if (i < choice - count) { newCluster[i] = next[i]; } else if (i > choice - count) { newCluster[i - 1] = next[i]; } } newPartition.add(newCluster); choice = numObserved; } count += next.length; } partition = newPartition; } } while (changed); Graph bestGraph = new EdgeListGraph(); List latentNodes = new ArrayList(); for (int p = 0; p < partition.size(); p++) { int next[] = (int[]) partition.get(p); Node newLatent = new GraphNode("_L" + p); newLatent.setNodeType(NodeType.LATENT); bestGraph.addNode(newLatent); Iterator it = latentNodes.iterator(); while (it.hasNext()) { Node previousLatent = (Node) it.next(); bestGraph.addDirectedEdge(previousLatent, newLatent); } latentNodes.add(newLatent); for (int i = 0; i < next.length; i++) { Node newNode = new GraphNode(tetradTest.getVarNames()[next[i]]); bestGraph.addNode(newNode); bestGraph.addDirectedEdge(newLatent, newNode); } } return new SemGraph(bestGraph); } /** * This initialization has to be done only once per complete search. No need to call it multiple times for each * stage of purifyScoreSearch */ private void structuralEmInitialization(List partition) { // Initialize semGraph this.observableNames = new Hashtable(); this.latentNames = new Hashtable(); this.numObserved = 0; this.numLatent = 0; this.latentNodes = new ArrayList(); this.measuredNodes = new ArrayList(); this.basicGraph = new EdgeListGraph(); for (int p = 0; p < partition.size(); p++) { int next[] = (int[]) partition.get(p); Node newLatent = new GraphNode("_L" + p); newLatent.setNodeType(NodeType.LATENT); basicGraph.addNode(newLatent); Iterator it = latentNodes.iterator(); while (it.hasNext()) { Node previousLatent = (Node) it.next(); basicGraph.addDirectedEdge(previousLatent, newLatent); } latentNodes.add(newLatent); latentNames.put(newLatent.toString(), numLatent); numLatent++; for (int i = 0; i < next.length; i++) { Node newNode = new GraphNode(tetradTest.getVarNames()[next[i]]); basicGraph.addNode(newNode); basicGraph.addDirectedEdge(newLatent, newNode); observableNames.put(newNode.toString(), numObserved); measuredNodes.add(newNode); numObserved++; } } if (this.numLatent + this.numObserved < 1) { throw new IllegalArgumentException( "Input clusters must contain at least one variable."); } this.clusterId = new int[numObserved]; int count = 0; for (int p = 0; p < partition.size(); p++) { int next[] = (int[]) partition.get(p); for (int i = 0; i < next.length; i++) { this.clusterId[count++] = p; } } this.purePartitionGraph = new SemGraph(basicGraph); if (((ContinuousTetradTest) this.tetradTest).getTestType() == TestType.NONE) { return; } //Information for graph modification this.correlatedErrors = new boolean[numObserved][numObserved]; this.latentParent = new boolean[numObserved][numLatent]; this.observedParent = new boolean[numObserved][numObserved]; //Information for MAG expectation this.Cyy = new double[numObserved][numObserved]; this.bestCyy = new double[numObserved][numObserved]; this.bestCyz = new double[numObserved][numLatent]; this.bestCzz = new double[numLatent][numLatent]; this.covarianceMatrix = ((ContinuousTetradTest) tetradTest).getCovMatrix(); String varNames[] = covarianceMatrix.getVariableNames().toArray(new String[0]); double cov[][] = covarianceMatrix.getMatrix().toArray(); for (int i = 0; i < cov.length; i++) { for (int j = 0; j < cov.length; j++) { if (observableNames.get(varNames[i]) != null && observableNames.get(varNames[j]) != null) { Cyy[((Integer) observableNames.get( varNames[i]))][((Integer) observableNames .get(varNames[j]))] = cov[i][j]; } } } //Information for MAG maximization this.parents = new int[this.numObserved][]; this.spouses = new int[this.numObserved][]; this.nSpouses = new int[this.numObserved]; this.parentsLat = new int[this.numLatent][]; this.parentsL = new boolean[this.numObserved][]; this.parentsCov = new double[this.numObserved][][]; this.parentsChildCov = new double[this.numObserved][]; this.parentsLatCov = new double[this.numLatent][][]; this.parentsChildLatCov = new double[this.numLatent][]; this.pseudoParentsCov = new double[this.numObserved][][]; this.pseudoParentsChildCov = new double[this.numObserved][]; this.covErrors = new double[this.numObserved][this.numObserved]; this.oldCovErrors = new double[this.numObserved][this.numObserved]; this.sampleCovErrors = new double[this.numObserved][this.numObserved]; this.varErrorLatent = new double[this.numLatent]; this.omega = new double[this.numLatent + this.numObserved - 1][ this.numLatent + this.numObserved - 1]; this.omegaI = new double[this.numLatent + this.numObserved - 1]; this.selectedInverseOmega = new double[this.numObserved][][]; this.auxInverseOmega = new double[this.numObserved][][]; this.parentsResidualsCovar = new double[this.numObserved][][]; this.iResidualsCovar = new double[this.numObserved + this.numLatent - 1]; this.betas = new double[this.numObserved][this.numObserved + this.numLatent]; this.oldBetas = new double[this.numObserved][this.numObserved + this.numLatent]; this.betasLat = new double[this.numLatent][this.numLatent]; } /** * Estimate parameters of a general measurement model with possible impurities but where each indicator may have * multiple latent and observed parents. */ private double gaussianEM(SemGraph semdag, SemIm initialSemIm) { double score, newScore = -Double.MAX_VALUE, bestScore = -Double.MAX_VALUE; SemPm semPm = new SemPm(semdag); for (int p = 0; p < numObserved; p++) { for (int q = 0; q < numObserved; q++) { this.bestCyy[p][q] = this.Cyy[p][q]; } if (this.Cyz != null) { for (int q = 0; q < numLatent; q++) { this.bestCyz[p][q] = this.Cyz[p][q]; } } } if (this.Czz != null) { for (int p = 0; p < numLatent; p++) { for (int q = 0; q < numLatent; q++) { this.bestCzz[p][q] = this.Czz[p][q]; } } } semdag.setShowErrorTerms(true); initializeGaussianEM(semdag); for (int i = 0; i < 3; i++) { System.out.println("--Trial " + i); SemIm semIm; if (i == 0 && initialSemIm != null) { semIm = initialSemIm; } else { semIm = new SemIm(semPm); semIm.setCovMatrix(this.covarianceMatrix); } do { score = newScore; gaussianExpectation(semIm); newScore = gaussianMaximization(semIm); if (newScore == -Double.MAX_VALUE) { break; } } while (Math.abs(score - newScore) > 1.E-3); System.out.println(newScore); if (newScore > bestScore && !Double.isInfinite(newScore)) { bestScore = newScore; for (int p = 0; p < numObserved; p++) { for (int q = 0; q < numObserved; q++) { this.bestCyy[p][q] = this.Cyy[p][q]; } for (int q = 0; q < numLatent; q++) { this.bestCyz[p][q] = this.Cyz[p][q]; } } for (int p = 0; p < numLatent; p++) { for (int q = 0; q < numLatent; q++) { this.bestCzz[p][q] = this.Czz[p][q]; } } } } for (int p = 0; p < numObserved; p++) { for (int q = 0; q < numObserved; q++) { this.Cyy[p][q] = this.bestCyy[p][q]; } for (int q = 0; q < numLatent; q++) { this.Cyz[p][q] = this.bestCyz[p][q]; } } for (int p = 0; p < numLatent; p++) { for (int q = 0; q < numLatent; q++) { this.Czz[p][q] = this.bestCzz[p][q]; } } if (Double.isInfinite(bestScore)) { System.out.println("* * Warning: Heywood case in this step"); return -Double.MAX_VALUE; } //System.exit(0); return bestScore; } private void initializeGaussianEM(SemGraph semMag) { //Build parents and spouses indices for (int i = 0; i < this.numLatent; i++) { Node node = (Node) this.latentNodes.get(i); if (semMag.getParents(node).size() > 0) { this.parentsLat[i] = new int[semMag.getParents(node).size() - 1]; int count = 0; for (Iterator it = semMag.getParents(node).iterator(); it.hasNext(); ) { Node parent = (Node) it.next(); if (parent.getNodeType() == NodeType.LATENT) { this.parentsLat[i][count++] = ((Integer) this.latentNames.get( parent.getName())); } } this.parentsLatCov[i] = new double[this.parentsLat[i].length][this.parentsLat[i].length]; this.parentsChildLatCov[i] = new double[this.parentsLat[i].length]; } } boolean correlatedErrors[][] = new boolean[this.numObserved][this.numObserved]; for (int i = 0; i < this.numObserved; i++) { for (int j = 0; j < this.numObserved; j++) { correlatedErrors[i][j] = false; } } for (Iterator it = semMag.getEdges().iterator(); it.hasNext(); ) { Edge nextEdge = (Edge) it.next(); if (nextEdge.getEndpoint1() == Endpoint.ARROW && nextEdge.getEndpoint2() == Endpoint.ARROW) { //By construction, getNode1() and getNode2() are error nodes. They have only one child each. Iterator it1 = semMag.getChildren(nextEdge.getNode1()) .iterator(); Node measure1 = (Node) it1.next(); Iterator it2 = semMag.getChildren(nextEdge.getNode2()) .iterator(); Node measure2 = (Node) it2.next(); correlatedErrors[((Integer) this.observableNames.get( measure1.getName()))][((Integer) this.observableNames .get(measure2.getName()))] = true; correlatedErrors[((Integer) this.observableNames.get( measure2.getName()))][((Integer) this .observableNames.get(measure1.getName()))] = true; } } for (int i = 0; i < this.numObserved; i++) { Node node = (Node) this.measuredNodes.get(i); this.parents[i] = new int[semMag.getParents(node).size() - 1]; this.parentsL[i] = new boolean[semMag.getParents(node).size() - 1]; int count = 0; for (Iterator it = semMag.getParents(node).iterator(); it.hasNext(); ) { Node parent = (Node) it.next(); if (parent.getNodeType() == NodeType.LATENT) { this.parents[i][count] = ((Integer) this.latentNames.get(parent.getName())); this.parentsL[i][count++] = true; } else if (parent.getNodeType() == NodeType.MEASURED) { this.parents[i][count] = ((Integer) this.observableNames.get( parent.getName())); this.parentsL[i][count++] = false; } } int numCovar = 0; for (int j = 0; j < correlatedErrors.length; j++) { if (i != j && correlatedErrors[i][j]) { numCovar++; } } if (numCovar > 0) { this.spouses[i] = new int[numCovar]; int countS = 0; for (int j = 0; j < this.numObserved; j++) { if (i == j) { continue; } if (correlatedErrors[i][j]) { this.spouses[i][countS++] = j; } } this.nSpouses[i] = countS; } else { this.spouses[i] = null; this.nSpouses[i] = 0; } this.parentsCov[i] = new double[this.parents[i].length][this.parents[i].length]; this.parentsChildCov[i] = new double[this.parents[i].length]; this.pseudoParentsCov[i] = new double[this.parents[i].length + this.nSpouses[i]][ this.parents[i].length + this.nSpouses[i]]; this.pseudoParentsChildCov[i] = new double[this.parents[i].length + this.nSpouses[i]]; this.parentsResidualsCovar[i] = new double[this.parents[i].length][ this.numLatent + this.numObserved - 1]; this.selectedInverseOmega[i] = new double[this.nSpouses[i]][ this.numLatent + this.numObserved - 1]; this.auxInverseOmega[i] = new double[this.nSpouses[i]][ this.numLatent + this.numObserved - 1]; } } /** * The expectation step for the structural EM algorithm. This is heavily based on "EM Algorithms for ML Factor * Analysis", by Rubin and Thayer (Psychometrika, 1982) */ private void gaussianExpectation(SemIm semIm) { //Get the parameters double beta[][] = new double[numLatent][numLatent]; //latent-to-latent coefficients double fi[][] = new double[numLatent][numLatent]; //latent error terms covariance double lambdaI[][] = new double[numObserved][numObserved]; //observed-to-indicatorcoefficients double lambdaL[][] = new double[numObserved][numLatent]; //latent-to-indicatorcoefficients double tau[][] = new double[numObserved][numObserved]; //measurement error variance //Note: error covariance matrix tau is usually *not* diagonal, unlike the implementation of other //structural EM algorithms such as in MimBuildScoreSearch. for (int i = 0; i < numLatent; i++) { for (int j = 0; j < numLatent; j++) { beta[i][j] = 0.; fi[i][j] = 0.; } } for (int i = 0; i < numObserved; i++) { for (int j = 0; j < numLatent; j++) { lambdaL[i][j] = 0.; } } for (int i = 0; i < numObserved; i++) { for (int j = 0; j < numObserved; j++) { tau[i][j] = 0.; lambdaI[i][j] = 0.; } } List parameters = semIm.getFreeParameters(); double paramValues[] = semIm.getFreeParamValues(); for (int i = 0; i < parameters.size(); i++) { Parameter parameter = (Parameter) parameters.get(i); if (parameter.getType() == ParamType.COEF) { Node from = parameter.getNodeA(); Node to = parameter.getNodeB(); if (to.getNodeType() == NodeType.MEASURED && from.getNodeType() == NodeType.LATENT) { //latent-to-indicator edge int position1 = (Integer) latentNames.get(from.getName()); int position2 = (Integer) observableNames.get(to.getName()); lambdaL[position2][position1] = paramValues[i]; } else if (to.getNodeType() == NodeType.MEASURED && from.getNodeType() == NodeType.MEASURED) { //indicator-to-indicator edge int position1 = (Integer) observableNames.get(from.getName()); int position2 = (Integer) observableNames.get(to.getName()); lambdaI[position2][position1] = paramValues[i]; } else if (to.getNodeType() == NodeType.LATENT) { //latent-to-latent edge int position1 = (Integer) latentNames.get(from.getName()); int position2 = (Integer) latentNames.get(to.getName()); beta[position2][position1] = paramValues[i]; } } else if (parameter.getType() == ParamType.VAR) { Node exo = parameter.getNodeA(); if (exo.getNodeType() == NodeType.ERROR) { Iterator ci = semIm.getSemPm().getGraph().getChildren(exo) .iterator(); exo = (Node) ci.next(); //Assuming error nodes have only one children in SemGraphs... } if (exo.getNodeType() == NodeType.LATENT) { fi[((Integer) latentNames.get( exo.getName()))][((Integer) latentNames .get(exo.getName()))] = paramValues[i]; } else { tau[((Integer) observableNames.get( exo.getName()))][((Integer) observableNames .get(exo.getName()))] = paramValues[i]; } } else if (parameter.getType() == ParamType.COVAR) { Node exo1 = parameter.getNodeA(); Node exo2 = parameter.getNodeB(); //exo1.getNodeType and exo1.getNodeType *should* be error terms of measured variables //We will change the pointers to point to their respective indicators // Iterator ci = semIm.getEstIm().getGraph().getChildren(exo1) // .iterator(); // exo1 = // (Node) ci.next(); //Assuming error nodes have only one children in SemGraphs... // ci = semIm.getEstIm().getGraph().getChildren(exo2).iterator(); // exo2 = // (Node) ci.next(); //Assuming error nodes have only one children in SemGraphs... exo1 = semIm.getSemPm().getGraph().getVarNode(exo1); exo2 = semIm.getSemPm().getGraph().getVarNode(exo2); tau[((Integer) observableNames.get( exo1.getName()))][((Integer) observableNames .get(exo2.getName()))] = tau[((Integer) observableNames .get(exo2.getName()))][((Integer) observableNames .get(exo1.getName()))] = paramValues[i]; } } //Fill expected sufficiente statistics accordingly to the order of //the variables table double identity[][] = new double[numLatent][numLatent]; for (int i = 0; i < numLatent; i++) { for (int j = 0; j < numLatent; j++) { if (i == j) { identity[i][j] = 1.; } else { identity[i][j] = 0.; } } } double identityI[][] = new double[numObserved][numObserved]; for (int i = 0; i < numObserved; i++) { for (int j = 0; j < numObserved; j++) { if (i == j) { identityI[i][j] = 1.; } else { identityI[i][j] = 0.; } } } double iMinusB[][] = MatrixUtils.inverse(MatrixUtils.subtract(identity, beta)); double latentImpliedCovar[][] = MatrixUtils.product(iMinusB, MatrixUtils.product(fi, MatrixUtils.transpose(iMinusB))); double iMinusI[][] = MatrixUtils.inverse(MatrixUtils.subtract(identityI, lambdaI)); double indImpliedCovar[][] = MatrixUtils.product(MatrixUtils.product( iMinusI, MatrixUtils.sum(MatrixUtils.product( MatrixUtils.product(lambdaL, latentImpliedCovar), MatrixUtils.transpose(lambdaL)), tau)), MatrixUtils.transpose(iMinusI)); double loadingLatentCovar[][] = MatrixUtils.product(iMinusI, MatrixUtils.product(lambdaL, latentImpliedCovar)); double smallDelta[][] = MatrixUtils.product( MatrixUtils.inverse(indImpliedCovar), loadingLatentCovar); double bigDelta[][] = MatrixUtils.subtract(latentImpliedCovar, MatrixUtils.product(MatrixUtils.transpose(loadingLatentCovar), smallDelta)); this.Cyz = MatrixUtils.product(this.Cyy, smallDelta); this.Czz = MatrixUtils.sum( MatrixUtils.product(MatrixUtils.transpose(smallDelta), Cyz), bigDelta); } /*private SemIm getNextSemIm(SemGraph2 semGraph) { SemPm semPm = new SemPm(semGraph); SemIm nextSemIm = SemIm.newInstance(semPm, this.CovarianceMatrix); gaussianMaximization(nextSemIm); return nextSemIm; }*/ private double impurityScoreSearch(double initialScore) { double score, nextScore = initialScore; boolean changed[] = new boolean[1]; do { changed[0] = false; score = nextScore; nextScore = addImpuritySearch(score, changed); if (changed[0]) { changed[0] = false; nextScore = deleteImpuritySearch(nextScore, changed); } } while (changed[0]); return score; } private double addImpuritySearch(double initialScore, boolean changed[]) { double score, nextScore = initialScore; int choiceType = -1; do { score = nextScore; int bestChoice1 = -1, bestChoice2 = -1; for (int i = 0; i < numObserved; i++) { //Add latent->indicator edges //NOTE: code deactivated. Seems not to be worthy trying. /*for (int j = 0; j < numLatent; j++) if (!latentParent[i][j]) { latentParent[i][j] = true; double newScore = scoreCandidate(); if (newScore > nextScore) { nextScore = newScore; bestChoice1 = i; bestChoice2 = j; choiceType = 0; } latentParent[i][j] = false; }*/ for (int j = i + 1; j < numObserved; j++) { //Check if one should ignore the possibility of an impurity for this pair if (forbiddenImpurity(this.measuredNodes.get(i).toString(), this.measuredNodes.get(j).toString())) { continue; } //indicator -> indicator edges (children of the same latent parent) //NOTE: code deactivated. Seems not to be worthy trying. // Here, I am not checking for cycles, and edges are considered only in one direction /*if (!correlatedErrors[i][j] && !observedParent[i][j] && !observedParent[j][i] && clusterId[i] == clusterId[j]) { // //Check if they have the same latent parent observedParent[i][j] = true; double newScore = scoreCandidate(); //System.out.println("Trying impurity " + i + " --> " + j + " (Score = " + newScore + ")"); //System.exit(0); if (newScore > nextScore) { nextScore = newScore; bestChoice1 = i; bestChoice2 = j; choiceType = 1; } observedParent[i][j] = false; }*/ //indicator <-> indicator edges if (!correlatedErrors[i][j] && !observedParent[i][j] && !observedParent[j][i]) { correlatedErrors[i][j] = correlatedErrors[j][i] = true; double newScore = scoreCandidate(); //System.out.println("Trying impurity " + i + " <--> " + j + " (Score = " + newScore + ")"); //System.exit(0); if (newScore > nextScore) { nextScore = newScore; bestChoice1 = i; bestChoice2 = j; choiceType = 2; } correlatedErrors[i][j] = correlatedErrors[j][i] = false; } } } if (bestChoice1 != -1) { this.modifiedGraph = true; switch (choiceType) { case 0: latentParent[bestChoice1][bestChoice2] = true; System.out.println( "****************************Added impurity: " + this.latentNodes.get( bestChoice2).toString() + " --> " + this.measuredNodes.get( bestChoice1).toString() + " " + nextScore); break; case 1: observedParent[bestChoice1][bestChoice2] = true; System.out.println( "****************************Added impurity: " + this.measuredNodes.get( bestChoice2).toString() + " --> " + this.measuredNodes.get( bestChoice1).toString() + " " + nextScore); break; case 2: System.out.println( "****************************Added impurity: " + this.measuredNodes.get( bestChoice1).toString() + " <--> " + this.measuredNodes.get( bestChoice2).toString() + " " + nextScore); correlatedErrors[bestChoice1][bestChoice2] = correlatedErrors[bestChoice2][bestChoice1] = true; } changed[0] = true; } } while (score < nextScore); printlnMessage("End of addition round"); return score; } private double deleteImpuritySearch(double initialScore, boolean changed[]) { double score, nextScore = initialScore; int choiceType = -1; do { score = nextScore; int bestChoice1 = -1, bestChoice2 = -1; for (int i = 0; i < numObserved - 1; i++) { for (int j = i + 1; j < numObserved; j++) { if (observedParent[i][j] || observedParent[j][i]) { boolean directionIJ = observedParent[i][j]; observedParent[i][j] = observedParent[j][i] = false; double newScore = scoreCandidate(); if (newScore > nextScore) { nextScore = newScore; bestChoice1 = i; bestChoice2 = j; choiceType = 0; } if (directionIJ) { observedParent[i][j] = true; } else { observedParent[j][i] = true; } } if (correlatedErrors[i][j]) { correlatedErrors[i][j] = correlatedErrors[j][i] = false; double newScore = scoreCandidate(); if (newScore > nextScore) { nextScore = newScore; bestChoice1 = i; bestChoice2 = j; choiceType = 1; } correlatedErrors[i][j] = correlatedErrors[j][i] = true; } } } if (bestChoice1 != -1) { this.modifiedGraph = true; switch (choiceType) { case 0: if (observedParent[bestChoice1][bestChoice2]) { System.out.println( "****************************Removed impurity: " + this.measuredNodes.get(bestChoice2) .toString() + " --> " + this.measuredNodes.get(bestChoice1) .toString() + " " + nextScore); } else { System.out.println( "****************************Removed impurity: " + this.measuredNodes.get(bestChoice1) .toString() + " --> " + this.measuredNodes.get(bestChoice2) .toString() + " " + nextScore); } observedParent[bestChoice1][bestChoice2] = observedParent[bestChoice2][bestChoice1] = false; break; case 1: System.out.println( "****************************Removed impurity: " + this.measuredNodes.get( bestChoice1).toString() + " <--> " + this.measuredNodes.get( bestChoice2).toString() + " " + nextScore); correlatedErrors[bestChoice1][bestChoice2] = correlatedErrors[bestChoice2][bestChoice1] = false; } changed[0] = true; } } while (score < nextScore); printlnMessage("End of deletion round"); return score; } private boolean forbiddenImpurity(String name1, String name2) { if (this.forbiddenList == null) { return false; } for (Iterator it = this.forbiddenList.iterator(); it.hasNext(); ) { Set nextPair = (Set) it.next(); if (nextPair.contains(name1) && nextPair.contains(name2)) { return true; } } return false; } private double scoreCandidate() { SemGraph graph = updatedGraph(); graph.setShowErrorTerms(true); initializeGaussianEM(graph); SemPm semPm = new SemPm(graph); SemIm semIm = new SemIm(semPm, covarianceMatrix); gaussianMaximization(semIm); return -semIm.getTruncLL() - 0.5 * semIm.getNumFreeParams() * Math.log(covarianceMatrix.getSampleSize()); } private SemGraph updatedGraph() { SemGraph output = new SemGraph(this.basicGraph); output.setShowErrorTerms(true); for (int i = 0; i < output.getNodes().size() - 1; i++) { Node node1 = output.getNodes().get(i); if (node1.getNodeType() != NodeType.MEASURED) { continue; } for (int j = 0; j < output.getNodes().size(); j++) { Node node2 = output.getNodes().get(j); if (node2.getNodeType() != NodeType.LATENT) { continue; } int pos1 = (Integer) observableNames.get( output.getNodes().get(i).toString()); int pos2 = (Integer) latentNames.get( output.getNodes().get(j).toString()); if (latentParent[pos1][pos2] && output.getEdge(node1, node2) == null) { output.addDirectedEdge(node2, node1); } } for (int j = i + 1; j < output.getNodes().size(); j++) { Node node2 = output.getNodes().get(j); if (node2.getNodeType() != NodeType.MEASURED) { continue; } Node errnode1 = output.getErrorNode(output.getNodes().get(i)); Node errnode2 = output.getErrorNode(output.getNodes().get(j)); int pos1 = (Integer) observableNames.get( output.getNodes().get(i).toString()); int pos2 = (Integer) observableNames.get( output.getNodes().get(j).toString()); if (correlatedErrors[pos1][pos2] && output.getEdge(errnode1, errnode2) == null) { output.addBidirectedEdge(errnode1, errnode2); } if (observedParent[pos1][pos2] && output.getEdge(node1, node2) == null) { output.addDirectedEdge(node2, node1); } else if (observedParent[pos2][pos1] && output.getEdge(node1, node2) == null) { output.addDirectedEdge(node1, node2); } } } return output; } /** * Find the MLE of a latent SemPm with double directed-edges using Drton and Richardson (2003). It is assumed that * data matrices such as betas, latentBetas, covErrors and covLatentErrors have been allocated to memory, and * indexing matrices such as parent as spouses allocated and initialized. Such initialization is usually done inside * the gaussianEM method. */ /*private SemIm getDummyExample() { this.numObserved = 13; this.numLatent = 4; ProtoSemGraph newGraph = new ProtoSemGraph(); Node v[] = new Node[17]; for (int i = 0; i < 17; i++) { if (i < 4) v[i] = new GraphNode("L" + (i + 1)); else v[i] = new GraphNode("V" + (i - 3)); newGraph.addNode(v[i]); } for (int l = 0; l < numLatent; l++) { for (int l2 = l + 1; l2 < numLatent; l2++) newGraph.addDirectedEdge(v[l], v[l2]); for (int i = 0; i < 3; i++) newGraph.addDirectedEdge(v[l], v[l * 3 + i + 4]); } newGraph.addDirectedEdge(v[3], v[16]); newGraph.addDirectedEdge(v[4], v[6]); newGraph.addDirectedEdge(v[14], v[15]); newGraph.addBidirectedEdge(v[9], v[10]); newGraph.addBidirectedEdge(v[7], v[12]); newGraph.addBidirectedEdge(v[12], v[16]); SemIm realIm = SemIm.newInstance(new SemPm(newGraph)); DataSet data = new DataSet(realIm.simulateData(1000)); System.out.println(data.toString()); System.out.println(new CovarianceMatrix(data)); System.out.println(); this.latentNames = new Hashtable(); this.latentNodes = new ArrayList(); for (int i = 0; i < numLatent; i++) { latentNames.put(v[i].getNode(), new Integer(i)); latentNodes.add(v[i]); } this.observableNames = new Hashtable(); this.measuredNodes = new ArrayList(); for (int i = numLatent; i < numLatent + numObserved; i++) { observableNames.put(v[i].getNode(), new Integer(i - numLatent)); measuredNodes.add(v[i]); } double temp[][] = (new CovarianceMatrix(data)).getMatrix(); Cyy = new double[numObserved][numObserved]; Czz = new double[numLatent][numLatent]; Cyz = new double[numObserved][numLatent]; for (int i = 0; i < numLatent; i++) for (int j = 0; j < numLatent; j++) Czz[i][j] = temp[i][j]; for (int i = 0; i < numObserved; i++) { for (int j = 0; j < numLatent; j++) Cyz[i][j] = temp[i + numLatent][j]; for (int j = 0; j < numObserved; j++) Cyy[i][j] = temp[i + numLatent][j + numLatent]; } this.correlatedErrors = new boolean[numObserved][numObserved]; this.latentParent = new boolean[numObserved][numLatent]; this.observedParent = new boolean[numObserved][numObserved]; CovarianceMatrix = new CovarianceMatrix(data); //Information for MAG maximization this.parents = new int[this.numObserved][]; this.spouses = new int[this.numObserved][]; this.nSpouses = new int[this.numObserved]; this.parentsLat = new int[this.numLatent][]; this.parentsL = new boolean[this.numObserved][]; this.parentsCov = new double[this.numObserved][][]; this.parentsChildCov = new double[this.numObserved][]; this.parentsLatCov = new double[this.numLatent][][]; this.parentsChildLatCov = new double[this.numLatent][]; this.pseudoParentsCov = new double[this.numObserved][][]; this.pseudoParentsChildCov = new double[this.numObserved][]; this.covErrors = new double[this.numObserved][this.numObserved]; this.oldCovErrors = new double[this.numObserved][this.numObserved]; this.sampleCovErrors = new double[this.numObserved][this.numObserved]; this.varErrorLatent = new double[this.numLatent]; this.omega = new double[this.numLatent + this.numObserved - 1][this.numLatent + this.numObserved - 1]; this.omegaI = new double[this.numLatent + this.numObserved - 1]; this.selectedInverseOmega = new double[this.numObserved][][]; this.auxInverseOmega = new double[this.numObserved][][]; this.parentsResidualsCovar = new double[this.numObserved][][]; this.iResidualsCovar = new double[this.numObserved + this.numLatent - 1]; this.betas = new double[this.numObserved][this.numObserved + this.numLatent]; this.oldBetas = new double[this.numObserved][this.numObserved + this.numLatent]; this.betasLat = new double[this.numLatent][this.numLatent]; for (int i = 0; i < numLatent; i++) v[i].setNodeType(NodeType.LATENT); SemGraph2 semGraph = new SemGraph2(newGraph); initializeGaussianEM(semGraph); return realIm; }*/ private double gaussianMaximization(SemIm semIm) { //SemIm realIm = getDummyExample(); //semIm = SemIm.newInstance(realIm.getEstIm()); //Fill matrices with semIm parameters for (int i = 0; i < this.numObserved; i++) { for (int j = 0; j < this.numObserved + this.numLatent; j++) { this.betas[i][j] = 0.; } } for (int i = 0; i < this.numLatent; i++) { for (int j = 0; j < this.numLatent; j++) { this.betasLat[i][j] = 0.; } } for (int i = 0; i < this.numObserved; i++) { for (int j = 0; j < this.numObserved; j++) { this.covErrors[i][j] = 0.; } } for (Iterator it = semIm.getFreeParameters().iterator(); it.hasNext(); ) { Parameter nextP = (Parameter) it.next(); if (nextP.getType() == ParamType.COEF) { Node node1 = nextP.getNodeA(); Node node2 = nextP.getNodeB(); if (node1.getNodeType() == NodeType.LATENT && node2.getNodeType() == NodeType.LATENT) { continue; } Node latent = null, observed = null; if (node1.getNodeType() == NodeType.LATENT) { latent = node1; observed = node2; } else if (node2.getNodeType() == NodeType.LATENT) { latent = node2; observed = node1; } if (latent != null) { int index1 = (Integer) this.latentNames.get(latent.getName()); int index2 = (Integer) this.observableNames.get( observed.getName()); this.betas[index2][index1] = semIm.getParamValue(nextP); } else { int index1 = (Integer) this.observableNames.get(node1.getName()); int index2 = (Integer) this.observableNames.get(node2.getName()); if (semIm.getSemPm().getGraph().isParentOf(node1, node2)) { this.betas[index2][this.numLatent + index1] = semIm.getParamValue(nextP); } else { this.betas[index1][this.numLatent + index2] = semIm.getParamValue(nextP); } } } else if (nextP.getType() == ParamType.COVAR) { Node exo1 = nextP.getNodeA(); Node exo2 = nextP.getNodeB(); //exo1.getNodeType and exo1.getNodeType *should* be error terms of measured variables //We will change the pointers to point to their respective indicators // Iterator ci = semIm.getEstIm().getGraph().getChildren(exo1) // .iterator(); // exo1 = // (Node) ci.next(); //Assuming error nodes have only one children in SemGraphs... // ci = semIm.getEstIm().getGraph().getChildren(exo2).iterator(); // exo2 = // (Node) ci.next(); //Assuming error nodes have only one children in SemGraphs... exo1 = semIm.getSemPm().getGraph().getVarNode(exo1); exo2 = semIm.getSemPm().getGraph().getVarNode(exo2); int index1 = (Integer) this.observableNames.get(exo1.getName()); int index2 = (Integer) this.observableNames.get(exo2.getName()); this.covErrors[index1][index2] = this.covErrors[index2][index1] = semIm.getParamValue(nextP); } else if (nextP.getType() == ParamType.VAR) { Node exo = nextP.getNodeA(); if (exo.getNodeType() == NodeType.LATENT) { continue; } // Iterator ci = semIm.getEstIm().getGraph().getChildren(exo) // .iterator(); // exo = // (Node) ci.next(); //Assuming error nodes have only one children in SemGraphs... exo = semIm.getSemPm().getGraph().getVarNode(exo); if (exo.getNodeType() == NodeType.MEASURED) { int index = (Integer) this.observableNames.get(exo.getName()); this.covErrors[index][index] = semIm.getParamValue(nextP); } } } //Find estimates for the latent->latent edges and latent variances //Assuming latents[0] is always the exogenous node in the latent layer this.varErrorLatent[0] = this.Czz[0][0]; for (int i = 1; i < this.numLatent; i++) { for (int j = 0; j < this.parentsLat[i].length; j++) { this.parentsChildLatCov[i][j] = this.Czz[i][this.parentsLat[i][j]]; for (int k = j; k < this.parentsLat[i].length; k++) { this.parentsLatCov[i][j][k] = this.Czz[this.parentsLat[i][j]][this.parentsLat[i][k]]; this.parentsLatCov[i][k][j] = this.parentsLatCov[i][j][k]; } } double betaL[] = MatrixUtils.product( MatrixUtils.inverse(this.parentsLatCov[i]), this.parentsChildLatCov[i]); this.varErrorLatent[i] = this.Czz[i][i] - MatrixUtils.innerProduct(this.parentsChildLatCov[i], betaL); for (int j = 0; j < this.parentsLat[i].length; j++) { this.betasLat[i][this.parentsLat[i][j]] = betaL[j]; } } //Initialize the covariance matrix for the parents of every observed node for (int i = 0; i < this.numObserved; i++) { for (int j = 0; j < this.parents[i].length; j++) { if (this.parentsL[i][j]) { this.parentsChildCov[i][j] = this.Cyz[i][this.parents[i][j]]; } else { this.parentsChildCov[i][j] = this.Cyy[i][this.parents[i][j]]; } for (int k = j; k < this.parents[i].length; k++) { if (this.parentsL[i][j] && this.parentsL[i][k]) { this.parentsCov[i][j][k] = this.Czz[this.parents[i][j]][this.parents[i][k]]; } else if (!this.parentsL[i][j] && this.parentsL[i][k]) { this.parentsCov[i][j][k] = this.Cyz[this.parents[i][j]][this.parents[i][k]]; } else if (this.parentsL[i][j] && !this.parentsL[i][k]) { this.parentsCov[i][j][k] = this.Cyz[this.parents[i][k]][this.parents[i][j]]; } else { this.parentsCov[i][j][k] = this.Cyy[this.parents[i][j]][this.parents[i][k]]; } this.parentsCov[i][k][j] = this.parentsCov[i][j][k]; } } } //ICF algorithm of Drton and Richardson to find estimates for the other edges and variances/covariances double change; int iter = 0; do { for (int i = 0; i < this.covErrors.length; i++) { for (int j = 0; j < this.covErrors.length; j++) { this.oldCovErrors[i][j] = this.covErrors[i][j]; } } for (int i = 0; i < this.numObserved; i++) { for (int j = 0; j < this.betas[i].length; j++) { this.oldBetas[i][j] = this.betas[i][j]; } } for (int i = 0; i < this.numObserved; i++) { //Build matrix Omega_{-i,-i} as defined in Drton and Richardson (2003) for (int ii = 0; ii < this.omega.length; ii++) { for (int j = 0; j < this.omega.length; j++) { this.omega[ii][j] = 0.; } } for (int ii = 0; ii < this.numLatent; ii++) { this.omegaI[ii] = 0.; this.omega[ii][ii] = this.varErrorLatent[ii]; } for (int ii = 0; ii < this.numObserved; ii++) { if (ii > i) { this.omegaI[this.numLatent + ii - 1] = this.covErrors[i][ii]; this.omega[this.numLatent + ii - 1][ this.numLatent + ii - 1] = this.covErrors[ii][ii]; } else if (ii < i) { this.omegaI[this.numLatent + ii] = this.covErrors[i][ii]; this.omega[this.numLatent + ii][this.numLatent + ii] = this.covErrors[ii][ii]; } } for (int ii = 0; ii < this.numObserved; ii++) { int index_ii; if (ii > i) { index_ii = this.numLatent + ii - 1; } else if (ii < i) { index_ii = this.numLatent + ii; } else { continue; } for (int j = 0; j < this.nSpouses[ii]; j++) { if (this.spouses[ii][j] > i) { this.omega[index_ii][ this.numLatent + this.spouses[ii][j] - 1] = this.covErrors[ii][this.spouses[ii][j]]; } else if (this.spouses[ii][j] < i) { this.omega[index_ii][this.numLatent + this.spouses[ii][j]] = this.covErrors[ii][this.spouses[ii][j]]; } } } /*int tspouses = 0; for (int s = 0; s < numObserved; s++) tspouses += nSpouses[s]; if (tspouses > 0 && iter == 0) { System.out.println(); System.out.println("OMEGA: Trial " + iter); for (int v = 0; v < this.numLatent + this.numObserved - 1; v++) { for (int k = 0; k < this.numLatent + this.numObserved - 1; k++) System.out.print(this.omega[v][k] + " "); System.out.println(); } System.out.println(); }*/ //Find new residuals covariance matrix for every ii != i for (int ii = 0; ii < this.numObserved; ii++) { if (ii == i) { continue; } for (int j = ii; j < this.numObserved; j++) { if (j == i) { continue; } this.sampleCovErrors[ii][j] = this.Cyy[ii][j]; for (int p = 0; p < this.parents[ii].length; p++) { if (this.parentsL[ii][p]) { this.sampleCovErrors[ii][j] -= this.betas[ii][this.parents[ii][p]] * this.Cyz[j][this.parents[ii][p]]; } else { this.sampleCovErrors[ii][j] -= this.betas[ii][ this.numLatent + this.parents[ii][p]] * this.Cyy[j][this.parents[ii][p]]; } } for (int p = 0; p < this.parents[j].length; p++) { if (this.parentsL[j][p]) { this.sampleCovErrors[ii][j] -= this.betas[j][this.parents[j][p]] * this.Cyz[ii][this.parents[j][p]]; } else { this.sampleCovErrors[ii][j] -= this.betas[j][ this.numLatent + this.parents[j][p]] * this.Cyy[ii][this.parents[j][p]]; } } for (int p1 = 0; p1 < this.parents[ii].length; p1++) { for (int p2 = 0; p2 < this.parents[j].length; p2++) { if (this.parentsL[ii][p1] && this.parentsL[j][p2]) { this.sampleCovErrors[ii][j] += this.betas[ii][this.parents[ii][p1]] * this.betas[j][this.parents[j][p2]] * this.Czz[this.parents[ii][p1]][this.parents[j][p2]]; } else if (this.parentsL[ii][p1] && !this.parentsL[j][p2]) { this.sampleCovErrors[ii][j] += this.betas[ii][this.parents[ii][p1]] * this.betas[j][this .numLatent + this.parents[j][p2]] * this.Cyz[this.parents[j][p2]][this.parents[ii][p1]]; } else if (!this.parentsL[ii][p1] && this.parentsL[j][p2]) { this.sampleCovErrors[ii][j] += this.betas[ii][this.numLatent + this.parents[ii][p1]] * this.betas[j][this.parents[j][p2]] * this.Cyz[this.parents[ii][p1]][this.parents[j][p2]]; } else { this.sampleCovErrors[ii][j] += this.betas[ii][this.numLatent + this.parents[ii][p1]] * this.betas[j][this .numLatent + this.parents[j][p2]] * this.Cyy[this.parents[ii][p1]][this.parents[j][p2]]; } } } this.sampleCovErrors[j][ii] = this.sampleCovErrors[ii][j]; } } //First, find the covariance of the parents of i and the residuals \epsilon_{-i} for (int ii = 0; ii < this.parents[i].length; ii++) { //covariance of the parent wrt every residual of latents if (this.parentsL[i][ii]) { this.parentsResidualsCovar[i][ii][0] = this.Czz[this.parents[i][ii]][0]; } else { this.parentsResidualsCovar[i][ii][0] = this.Cyz[this.parents[i][ii]][0]; } for (int j = 1; j < this.numLatent; j++) { if (this.parentsL[i][ii]) { this.parentsResidualsCovar[i][ii][j] = this.Czz[this.parents[i][ii]][j]; for (int p = 0; p < this.parentsLat[j].length; p++) { this.parentsResidualsCovar[i][ii][j] -= this.betasLat[j][this.parentsLat[j][p]] * this.Czz[this.parents[i][ii]][this.parentsLat[j][p]]; } } else { this.parentsResidualsCovar[i][ii][j] = this.Cyz[this.parents[i][ii]][j]; for (int p = 0; p < this.parentsLat[j].length; p++) { this.parentsResidualsCovar[i][ii][j] -= this.betasLat[j][this.parentsLat[j][p]] * this.Cyz[this.parents[i][ii]][this.parentsLat[j][p]]; } } } //covariance of the parent wrt every residual of observables (except for i) for (int j = 0; j < this.numObserved; j++) { int index_j; if (j < i) { index_j = this.numLatent + j; } else if (j > i) { index_j = this.numLatent + j - 1; } else { continue; } if (this.parentsL[i][ii]) { this.parentsResidualsCovar[i][ii][index_j] = this.Cyz[j][this.parents[i][ii]]; for (int p = 0; p < this.parents[j].length; p++) { if (this.parentsL[j][p]) { this.parentsResidualsCovar[i][ii][index_j] -= this.betas[j][this.parents[j][p]] * this.Czz[this.parents[i][ii]][this.parents[j][p]]; } else { this.parentsResidualsCovar[i][ii][index_j] -= this.betas[j][this.numLatent + this.parents[j][p]] * this.Cyz[this.parents[j][p]][this.parents[i][ii]]; } } } else { this.parentsResidualsCovar[i][ii][index_j] = this.Cyy[j][this.parents[i][ii]]; for (int p = 0; p < this.parents[j].length; p++) { if (this.parentsL[j][p]) { this.parentsResidualsCovar[i][ii][index_j] -= this.betas[j][this.parents[j][p]] * this.Cyz[this.parents[i][ii]][this.parents[j][p]]; } else { this.parentsResidualsCovar[i][ii][index_j] -= this.betas[j][this.numLatent + this.parents[j][p]] * this.Cyy[this.parents[j][p]][this.parents[i][ii]]; } } } } } //Now, find the covariance of Y_i with respect to everybody else's residuals this.iResidualsCovar[0] = this.Cyz[i][0]; //the first latent is exogenous for (int j = 1; j < this.numLatent; j++) { this.iResidualsCovar[j] = this.Cyz[i][j]; for (int p = 0; p < this.parentsLat[j].length; p++) { this.iResidualsCovar[j] -= this.betasLat[j][this.parentsLat[j][p]] * this.Cyz[i][this.parentsLat[j][p]]; } } for (int j = 0; j < this.numObserved; j++) { int index_j; if (j < i) { index_j = this.numLatent + j; } else if (j > i) { index_j = this.numLatent + j - 1; } else { continue; } this.iResidualsCovar[index_j] = this.Cyy[i][j]; for (int p = 0; p < this.parents[j].length; p++) { if (this.parentsL[j][p]) { this.iResidualsCovar[index_j] -= this.betas[j][this.parents[j][p]] * this.Cyz[i][this.parents[j][p]]; } else { this.iResidualsCovar[index_j] -= this.betas[j][this .numLatent + this.parents[j][p]] * this.Cyy[i][this.parents[j][p]]; } } } //Transform it to get the covariance of parents of i and pseudo-variables Z_sp(i) double inverseOmega[][] = MatrixUtils.inverse(this.omega); for (int ii = 0; ii < this.nSpouses[i]; ii++) { int sp_index; if (this.spouses[i][ii] > i) { sp_index = this.numLatent + this.spouses[i][ii] - 1; } else { sp_index = this.numLatent + this.spouses[i][ii]; } for (int j = 0; j < this.numLatent + this.numObserved - 1; j++) { this.selectedInverseOmega[i][ii][j] = inverseOmega[sp_index][j]; } } for (int ii = 0; ii < this.nSpouses[i]; ii++) { for (int j = 0; j < this.numLatent; j++) { this.auxInverseOmega[i][ii][j] = this.selectedInverseOmega[i][ii][j] * this.varErrorLatent[j]; } for (int j = 0; j < this.numObserved; j++) { int index_j; if (j > i) { index_j = this.numLatent + j - 1; } else if (j < i) { index_j = this.numLatent + j; } else { continue; } this.auxInverseOmega[i][ii][index_j] = 0; for (int k = 0; k < this.numObserved; k++) { int index_k; if (k > i) { index_k = this.numLatent + k - 1; } else if (k < i) { index_k = this.numLatent + k; } else { continue; } this.auxInverseOmega[i][ii][index_j] += this.selectedInverseOmega[i][ii][index_k] * this.sampleCovErrors[k][j]; } } } for (int ii = 0; ii < this.parents[i].length; ii++) { for (int j = ii; j < this.parents[i].length; j++) { this.pseudoParentsCov[i][ii][j] = this.pseudoParentsCov[i][j][ii] = this.parentsCov[i][ii][j]; } } for (int ii = 0; ii < this.parents[i].length; ii++) { for (int j = 0; j < this.nSpouses[i]; j++) { this.pseudoParentsCov[i][ii][this.parents[i].length + j] = 0.; for (int k = 0; k < this.numLatent + this.numObserved - 1; k++) { this.pseudoParentsCov[i][ii][this.parents[i] .length + j] += this.parentsResidualsCovar[i][ii][k] * this.selectedInverseOmega[i][j][k]; } this.pseudoParentsCov[i][this.parents[i].length + j][ii] = this.pseudoParentsCov[i][ii][ this.parents[i].length + j]; } } for (int ii = 0; ii < this.nSpouses[i]; ii++) { for (int j = ii; j < this.nSpouses[i]; j++) { this.pseudoParentsCov[i][this.parents[i].length + ii][ this.parents[i].length + j] = 0; for (int k = 0; k < this.numLatent + this.numObserved - 1; k++) { this.pseudoParentsCov[i][this.parents[i].length + ii][this.parents[i].length + j] += this.auxInverseOmega[i][ii][k] * this.selectedInverseOmega[i][j][k]; } this.pseudoParentsCov[i][this.parents[i].length + j][ this.parents[i].length + ii] = this.pseudoParentsCov[i][this.parents[i] .length + ii][this.parents[i].length + j]; if (this.pseudoParentsCov[i][this.parents[i].length + j][this.parents[i].length + ii] == 0.) { System.out.println("Zero here... Iter = " + iter); /*for (int k = 0; k < this.numLatent + this.numObserved - 1; k++) System.out.println(this.auxInverseOmega[i][ii][k] + " " + this.selectedInverseOmega[i][j][k]); System.out.println(); for (int v = 0; v < this.numLatent + this.numObserved - 1; v++) { for (int k = 0; k < this.numLatent + this.numObserved - 1; k++) System.out.print(this.omega[v][k] + " "); System.out.println(); } System.out.println(semIm.getEstIm().getDag()); System.out.println("PARENTS"); for (int n = 0; n < this.numObserved; n++) { System.out.print(this.measuredNodes.get(n).toString() + " - "); for (int p = 0; p < this.parents[n].length; p++) { if (parentsL[n][p]) System.out.print(this.latentNodes.get(parents[n][p]).toString() + " "); else System.out.print(this.measuredNodes.get(parents[n][p]).toString() + " "); } System.out.println(); } System.out.println("SPOUSES"); for (int n = 0; n < this.numObserved; n++) { System.out.print(this.measuredNodes.get(n).toString() + " - "); for (int p = 0; p < this.nSpouses[n]; p++) { System.out.print(this.measuredNodes.get(spouses[n][p]).toString() + " "); } System.out.println(); } System.exit(0);*/ iter = 1000; break; } } } //Get the covariance of parents of i and pseudo-variables Z_sp(i) with respect to i for (int ii = 0; ii < this.parents[i].length; ii++) { this.pseudoParentsChildCov[i][ii] = this.parentsChildCov[i][ii]; } for (int j = 0; j < this.nSpouses[i]; j++) { this.pseudoParentsChildCov[i][this.parents[i].length + j] = 0; for (int k = 0; k < this.numLatent + this.numObserved - 1; k++) { this.pseudoParentsChildCov[i][this.parents[i].length + j] += selectedInverseOmega[i][j][k] * this.iResidualsCovar[k]; } } //Finally, regress Y_i on {parents} union {Z_i} //thisI = i; double params[] = MatrixUtils.product( MatrixUtils.inverse(this.pseudoParentsCov[i]), this.pseudoParentsChildCov[i]); //Update betas and omegas (entries in covErrors) for (int j = 0; j < this.parents[i].length; j++) { if (this.parentsL[i][j]) { this.betas[i][this.parents[i][j]] = params[j]; } else { this.betas[i][this.numLatent + this.parents[i][j]] = params[j]; } } for (int j = 0; j < this.nSpouses[i]; j++) { this.covErrors[i][this.spouses[i][j]] = this.covErrors[this.spouses[i][j]][i] = params[this.parents[i].length + j]; if (this.spouses[i][j] > i) { this.omegaI[this.numLatent + this.spouses[i][j] - 1] = params[this.parents[i].length + j]; } else { this.omegaI[this.numLatent + this.spouses[i][j]] = params[this.parents[i].length + j]; } } double conditionalVar = this.Cyy[i][i] - MatrixUtils.innerProduct(this.pseudoParentsChildCov[i], params); this.covErrors[i][i] = conditionalVar + MatrixUtils.innerProduct( MatrixUtils.product(this.omegaI, inverseOmega), this.omegaI); } change = 0.; for (int i = 0; i < this.covErrors.length; i++) { for (int j = i; j < this.covErrors.length; j++) { change += Math.abs( this.oldCovErrors[i][j] - this.covErrors[i][j]); } } for (int i = 0; i < this.numObserved; i++) { for (int j = 0; j < this.betas[i].length; j++) { change += Math.abs(oldBetas[i][j] - this.betas[i][j]); } } iter++; //System.out.println("Iteration = " + iter + ", change = " + change); } while (iter < 200 && change > 0.01); //Now, copy updated parameters back to semIm try { for (int i = 0; i < this.numObserved; i++) { Node node = semIm.getSemPm().getGraph().getNode( this.measuredNodes.get(i).toString()); // Node nodeErrorTerm = null; // for (Node parent : semIm.getEstIm().getGraph().getParents(node)) { // if (parent.getNodeType() == NodeType.ERROR) { // semIm.setParamValue(parent, parent, // this.covErrors[i][i]); // nodeErrorTerm = parent; // break; // } // } semIm.getSemPm().getGraph().setShowErrorTerms(true); Node nodeErrorTerm = semIm.getSemPm().getGraph().getExogenous(node); for (int j = 0; j < this.parents[i].length; j++) { Node parent; if (this.parentsL[i][j]) { parent = semIm.getSemPm().getGraph().getNode( this.latentNodes.get(this.parents[i][j]) .toString()); } else { parent = semIm.getSemPm().getGraph().getNode( this.measuredNodes.get(this.parents[i][j]) .toString()); } if (this.parentsL[i][j]) { semIm.setParamValue(parent, node, this.betas[i][this.parents[i][j]]); } else { semIm.setParamValue(parent, node, this.betas[i][this .numLatent + this.parents[i][j]]); } } for (int j = 0; j < this.nSpouses[i]; j++) { if (this.spouses[i][j] > i) { Node spouse = semIm.getSemPm().getGraph().getNode( this.measuredNodes.get(this.spouses[i][j]) .toString()); // Node spouseErrorTerm = null; // for (Iterator it = semIm.getEstIm().getGraph() // .getParents(spouse).iterator(); it.hasNext();) { // Node nextParent = (Node) it.next(); // if (nextParent.getNodeType() == NodeType.ERROR) { // spouseErrorTerm = nextParent; // break; // } // } Node spouseErrorTerm = semIm.getSemPm().getGraph().getExogenous(spouse); semIm.setParamValue(nodeErrorTerm, spouseErrorTerm, this.covErrors[i][this.spouses[i][j]]); } } } for (int i = 0; i < this.numLatent; i++) { Node node = semIm.getSemPm().getGraph().getNode( this.latentNodes.get(i).toString()); if (semIm.getSemPm().getGraph().getParents(node).size() == 0) { semIm.setParamValue(node, node, this.varErrorLatent[i]); } else { for (Iterator it = semIm.getSemPm().getGraph().getParents(node) .iterator(); it.hasNext(); ) { Node nextParent = (Node) it.next(); if (nextParent.getNodeType() == NodeType.ERROR) { semIm.setParamValue(nextParent, nextParent, this.varErrorLatent[i]); break; } } for (int j = 0; j < this.parentsLat[i].length; j++) { Node parent = semIm.getSemPm().getGraph().getNode( this.latentNodes.get(this.parentsLat[i][j]) .toString()); semIm.setParamValue(parent, node, this.betasLat[i][parentsLat[i][j]]); } } } /*if (true) { System.out.println("******* REAL IM"); System.out.println(); System.out.println(realIm.toString()); System.out.println("******* ESTIMATED IM"); System.out.println(); System.out.println(semIm.toString()); System.exit(0); }*/ } catch (java.lang.IllegalArgumentException e) { System.out.println("** Warning: " + e.toString()); return -Double.MAX_VALUE; } return -semIm.getTruncLL() - 0.5 * semIm.getNumFreeParams() * Math.log(this.covarianceMatrix.getSampleSize()); } /*private SemGraph2 greedyImpurityAddition() { boolean newCorrelatedErrors[][] = new boolean[correlatedErrors.length][correlatedErrors.length]; for (int i = 0; i < correlatedErrors.length; i++) for (int j = 0; j < correlatedErrors.length; j++) { correlatedErrors[i][j] = false; newCorrelatedErrors[i][j] = false; } double score = gaussianEM(purePartitionGraph, null); printlnMessage("* Greedy impurity addition - Initial score = " + score); for (int i = 0; i < measuredNodes.size() - 1; i++) for (int j = i + 1; j < measuredNodes.size(); j++) { if (correlatedErrors[i][j] == false) { System.out.println("Trying " + i + " <--> " + j); correlatedErrors[i][j] = correlatedErrors[j][i] = true; SemGraph2 newGraph = updatedGraph(); double newScore = gaussianEM(newGraph, null); if (newScore > score) { score = newScore; printlnMessage(">> Added impurity. New score = " + score); newCorrelatedErrors[i][j] = newCorrelatedErrors[j][i] = true; } correlatedErrors[i][j] = correlatedErrors[j][i] = false; } } for (int i = 0; i < correlatedErrors.length; i++) for (int j = 0; j < correlatedErrors.length; j++) correlatedErrors[i][j] = newCorrelatedErrors[i][j]; return updatedGraph(); }*/ private SemGraph removeMarkedImpurities(SemGraph graph, boolean impurities[][]) { printlnMessage(); printlnMessage("** PURIFY: using marked impure pairs"); List latents = new ArrayList(); List partition = new ArrayList(); for (int i = 0; i < graph.getNodes().size(); i++) { Node nextLatent = graph.getNodes().get(i); if (nextLatent.getNodeType() != NodeType.LATENT) { continue; } latents.add(graph.getNodes().get(i)); Iterator cit = graph.getChildren(nextLatent).iterator(); List children = new ArrayList(); while (cit.hasNext()) { Node cnext = (Node) cit.next(); if (cnext.getNodeType() == NodeType.MEASURED) { children.add(cnext); } } int newCluster[] = new int[children.size()]; for (int j = 0; j < children.size(); j++) { newCluster[j] = ((Integer) observableNames.get( children.get(j).toString())); } partition.add(newCluster); } for (int i = 0; i < impurities.length - 1; i++) { for (int j = i + 1; j < impurities.length; j++) { if (impurities[i][j]) { System.out.println(measuredNodes.get(i).toString() + " x " + measuredNodes.get(j).toString()); } } } List latentCliques = new ArrayList(); int firstClique[] = new int[latents.size()]; for (int i = 0; i < firstClique.length; i++) { firstClique[i] = i; } latentCliques.add(firstClique); //Now, ready to purify for (int i = 0; i < latentCliques.size(); i++) { int nextLatentList[] = (int[]) latentCliques.get(i); List nextPartition = new ArrayList(); for (int p = 0; p < nextLatentList.length; p++) { nextPartition.add(partition.get(nextLatentList[p])); } List solution = findInducedPureGraph(nextPartition, impurities); if (solution != null) { System.out.println("--Solution"); Iterator it = solution.iterator(); while (it.hasNext()) { int c[] = (int[]) it.next(); for (int v = 0; v < c.length; v++) { System.out.print( measuredNodes.get(c[v]).toString() + " "); } System.out.println(); } printlnMessage(">> SIZE: " + sizeCluster(solution)); printlnMessage(">> New solution found!"); SemGraph graph2 = new SemGraph(); Node latentsArray[] = new Node[solution.size()]; for (int p = 0; p < solution.size(); p++) { int cluster[] = (int[]) solution.get(p); latentsArray[p] = new GraphNode(ClusterUtils.LATENT_PREFIX + (p + 1)); latentsArray[p].setNodeType(NodeType.LATENT); graph2.addNode(latentsArray[p]); for (int q = 0; q < cluster.length; q++) { Node newIndicator = new GraphNode( this.measuredNodes.get(cluster[q]).toString()); graph2.addNode(newIndicator); graph2.addDirectedEdge(latentsArray[p], newIndicator); } } for (int p = 0; p < latentsArray.length - 1; p++) { for (int q = p + 1; q < latentsArray.length; q++) { graph2.addDirectedEdge(latentsArray[p], latentsArray[q]); } } return graph2; } else { return null; } } return null; } private void sortByImpurityPriority(int elements[][], int partitionCount[], boolean eliminated[]) { int temp[] = new int[3]; //First, throw all eliminated elements to the end of the array for (int i = 0; i < elements.length - 1; i++) { if (eliminated[elements[i][0]]) { for (int j = i + 1; j < elements.length; j++) { if (!eliminated[elements[j][0]]) { swapElements(elements, i, j, temp); break; } } } } int total = 0; while (total < elements.length && !eliminated[elements[total][0]]) { total++; } //Sort them in the descending order of number of impurities for (int i = 0; i < total - 1; i++) { int max = -1; int max_idx = -1; for (int j = i; j < total; j++) { if (elements[j][2] > max) { max = elements[j][2]; max_idx = j; } } swapElements(elements, i, max_idx, temp); } //Now, within each cluster, select first those that belong to clusters with less than three latents. //Then, in decreasing order of cluster size. int start = 0; while (start < total) { int size = partitionCount[elements[start][1]]; int end = start + 1; for (int j = start + 1; j < total; j++) { if (size != partitionCount[elements[j][1]]) { break; } end++; } //Put elements with partitionCount of 1 and 2 at the top of the list for (int i = start + 1; i < end; i++) { if (partitionCount[elements[i][1]] == 1) { swapElements(elements, i, start, temp); start++; } } for (int i = start + 1; i < end; i++) { if (partitionCount[elements[i][1]] == 2) { swapElements(elements, i, start, temp); start++; } } //Now, order elements in the descending order of partitionCount for (int i = start; i < end - 1; i++) { int max = -1; int max_idx = -1; for (int j = i; j < end; j++) { if (partitionCount[elements[j][1]] > max) { max = partitionCount[elements[j][1]]; max_idx = j; } } swapElements(elements, i, max_idx, temp); } start = end; } } private void swapElements(int elements[][], int i, int j, int buffer[]) { buffer[0] = elements[i][0]; buffer[1] = elements[i][1]; buffer[2] = elements[i][2]; elements[i][0] = elements[j][0]; elements[i][1] = elements[j][1]; elements[i][2] = elements[j][2]; elements[j][0] = buffer[0]; elements[j][1] = buffer[1]; elements[j][2] = buffer[2]; } private List findInducedPureGraph(List partition, boolean impurities[][]) { //Store the ID of all elements for fast access int elements[][] = new int[sizeCluster(partition)][3]; int partitionCount[] = new int[partition.size()]; int countElements = 0; for (int p = 0; p < partition.size(); p++) { int next[] = (int[]) partition.get(p); partitionCount[p] = 0; for (int i = 0; i < next.length; i++) { elements[countElements][0] = next[i]; // global ID elements[countElements][1] = p; // set partition ID countElements++; partitionCount[p]++; } } //Count how many impure relations are entailed by each indicator for (int i = 0; i < elements.length; i++) { elements[i][2] = 0; for (int j = 0; j < elements.length; j++) { if (impurities[elements[i][0]][elements[j][0]]) { elements[i][2]++; // number of impure relations } } } //Iteratively eliminate impurities till some solution (or no solution) is found boolean eliminated[] = new boolean[this.numVars]; for (int i = 0; i < elements.length; i++) { eliminated[elements[i][0]] = impurities[elements[i][0]][elements[i][0]]; } // while (!validSolution(elements, eliminated)) { // //Sort them in the descending order of number of impurities // //(heuristic to avoid exponential search) // sortByImpurityPriority(elements, partitionCount, eliminated); // //for (int i = 0; i < elements.length; i++) // // if (elements[i][2] > 0) // printlnMessage("-- Eliminating " + // this.tetradTest.getVarNames()[elements[0][0]]); // eliminated[elements[0][0]] = true; // for (int i = 0; i < elements.length; i++) { // if (impurities[elements[i][0]][elements[0][0]]) { // elements[i][2]--; // } // } // partitionCount[elements[0][1]]--; // } return buildSolution2(elements, eliminated, partition); } private boolean validSolution(int elements[][], boolean eliminated[]) { for (int i = 0; i < elements.length; i++) { if (!eliminated[elements[i][0]] && elements[i][2] > 0) { return false; } } return true; } private List buildSolution2(int elements[][], boolean eliminated[], List partition) { List solution = new ArrayList(); Iterator it = partition.iterator(); while (it.hasNext()) { int next[] = (int[]) it.next(); int draftArea[] = new int[next.length]; int draftCount = 0; for (int i = 0; i < next.length; i++) { for (int j = 0; j < elements.length; j++) { if (elements[j][0] == next[i] && !eliminated[elements[j][0]]) { draftArea[draftCount++] = next[i]; } } } if (draftCount > 0) { int realCluster[] = new int[draftCount]; System.arraycopy(draftArea, 0, realCluster, 0, draftCount); solution.add(realCluster); } } if (solution.size() > 0) { return solution; } else { return null; } } }
ajsedgewick/tetrad
tetrad-lib/src/main/java/edu/cmu/tetrad/search/Purify.java
Java
gpl-2.0
152,402
<?php /*--------------------------------------------------------------------------------------------- ÎļþÔ¶³Ì·¢²¼Ä¿Â¼¸üÐÂÅäÖÃ(config.file.inc.php) ˵Ã÷:±¾ÎļþÖ÷ÒªÓÃÓÚϵͳºǫ́[Éú³É]-[×Ô¶¯ÈÎÎñ]-[Ô¶³Ì·þÎñÆ÷ͬ²½] ÖеÄÎļþ¼Ð×Ô¶¨Òå¸üÐÂÅäÖÃËùÓÃ,ʹÓÃʱºòÈç¹ûÓÐÌØ¶¨Ä¿Â¼ÐèÒª½øÐÐͬ ²½,ÔòÐèÒªÔÚÕâ¸öÎļþÖнøÐÐÅäÖÃ,ÅäÖ÷½Ê½ÈçÏÂ: $remotefile[] = array( 'filedir' => '/yourdir', //ͬ²½Îļþ¼ÐĿ¼ 'description' => 'ÕâÀïÊÇÎļþ¼Ð˵Ã÷', 'dfserv' => '0', //ĬÈÏ·þÎñÆ÷Ñ¡Ïî,¿ÉÒÔÔÚϵͳºǫ́[ϵͳÉèÖÃ]-[·þÎñÆ÷·Ö²¼/Ô¶³Ì ]ÖÐÅäÖà 'state' => '0', //ͬ²½×´Ì¬,0:δͬ²½ 1:ÒÑͬ²½ ); -----------------------------------------------------------------------------------------------*/ global $remotefile; $remotefile = array(); //ÒÔÏÂÊDZر¸Í¬²½ÅäÖÃÏî //@start_config ²»Òª¸Ä¶¯ÏÂÃæ<>½á¹¹ #<s_config> $remotefile[0] = array( 'filedir'=>'/a', 'description'=>'ÎĵµHTMLĬÈϱ£´æÂ·', 'dfserv'=>0, 'state'=>1, 'issystem'=>1 ); $remotefile[1] = array( 'filedir'=>'/longhoo', 'description'=>'ÎĵµHTMLĬÈϱ£´æÂ·', 'dfserv'=>0, 'state'=>1, 'issystem'=>1 ); $remotefile[2] = array( 'filedir'=>'/uploads', 'description'=>'ͼƬ/ÉÏ´«ÎļþĬÈÏ·¾¶', 'dfserv'=>0, 'state'=>1, 'issystem'=>1 ); $remotefile[3] = array( 'filedir'=>'/special', 'description'=>'רÌâĿ¼', 'dfserv'=>0, 'state'=>1, 'issystem'=>1 ); $remotefile[4] = array( 'filedir'=>'/data/js', 'description'=>'Éú³ÉjsĿ¼', 'dfserv'=>0, 'state'=>1, 'issystem'=>1 ); $remotefile[5] = array( 'filedir'=>'/images', 'description'=>'Í¼Æ¬ËØ²Ä´æ·ÅÎļþ', 'dfserv'=>0, 'state'=>1, 'issystem'=>0 ); $remotefile[6] = array( 'filedir'=>'/templets/images', 'description'=>'Ä£°åÎļþͼƬ´æ·ÅĿ¼', 'dfserv'=>0, 'state'=>1, 'issystem'=>0 ); $remotefile[7] = array( 'filedir'=>'/templets/style', 'description'=>'Ä£°åÎļþCSSÑùʽ´æ·ÅĿ¼', 'dfserv'=>0, 'state'=>1, 'issystem'=>0 ); #<e_config> ?>
bylu/Test
wulu/2015.11.23/qipai/data/config.file.inc.php
PHP
gpl-2.0
1,992
<?php //error_reporting(E_COMPILE_ERROR|E_ERROR|E_CORE_ERROR); require('./roots.php'); require($root_path.'include/inc_environment_global.php'); /** * CARE2X Integrated Hospital Information System Deployment 2.1 - 2004-10-02 * GNU General Public License * Copyright 2002,2003,2004,2005 Elpidio Latorilla * elpidio@care2x.org, * * See the file "copy_notice.txt" for the licence notice */ define('LANG_FILE','doctors.php'); define('NO_2LEVEL_CHK',1); require_once($root_path.'include/inc_front_chain_lang.php'); require($root_path.'include/inc_2level_reset.php'); if(!session_is_registered('sess_path_referer')) session_register('sess_path_referer'); $breakfile=$root_path.'main/startframe.php'.URL_APPEND; $_SESSION['sess_path_referer']=$top_dir.basename(__FILE__); # Erase the cookie if(isset($_COOKIE['ck_doctors_dienstplan_user'.$sid])) setcookie('ck_doctors_dienstplan_user'.$sid,'',0,'/'); # erase the user_origin if(isset($_SESSION['sess_user_origin'])) $_SESSION['sess_user_origin']=''; # Start Smarty templating here /** * LOAD Smarty */ # Note: it is advisable to load this after the inc_front_chain_lang.php so # that the smarty script can use the user configured template theme require_once($root_path.'gui/smarty_template/smarty_care.class.php'); $smarty = new smarty_care('common'); # Create a helper smarty object without reinitializing the GUI $smarty2 = new smarty_care('common', FALSE); # Added for the common header top block $smarty->assign('sToolbarTitle',$LDDoctors); # Added for the common header top block $smarty->assign('pbHelp',"javascript:gethelp('submenu1.php','$LDDoctors')"); $smarty->assign('breakfile',$breakfile); # Window bar title $smarty->assign('title',$LDDoctors); # Prepare the submenu icons $aSubMenuIcon=array(createComIcon($root_path,'eye_s.gif','0'), createComIcon($root_path,'post_discussion.gif','0'), createComIcon($root_path,'forums.gif','0'), createComIcon($root_path,'bubble.gif','0') ); # Prepare the submenu item descriptions $aSubMenuText=array($LDQViewTxt, $LDDOCSTxt, $LDDocsForumTxt, $LDNewsTxt ); # Prepare the submenu item links indexed by their template tags $aSubMenuItem=array('LDQViewTxt' => '<a href="doctors-dienst-schnellsicht.php'.URL_APPEND.'&retpath=docs">'.$LDQView.'</a>', 'LDDutyPlanTxt' => '<a href="doctors-main-pass.php'.URL_APPEND.'&target=dutyplan&retpath=menu">'.$LDDOCS.'</a>', 'LDDocsForumTxt' => '<a href="doctors-main-pass.php'.URL_APPEND.'&target=setpersonal&retpath=menu">'.$LDDocsList.'</a>', 'LDNewsTxt' => '<a href="'.$root_path.'modules/news/newscolumns.php'.URL_APPEND.'&dept_nr=37&user_origin=dept">'.$LDNews.'</a>', ); # Create the submenu rows $iRunner = 0; while(list($x,$v)=each($aSubMenuItem)){ $sTemp=''; ob_start(); if($cfg['icons'] != 'no_icon') $smarty2->assign('sIconImg','<img '.$aSubMenuIcon[$iRunner].'>'); $smarty2->assign('sSubMenuItem',$v); $smarty2->assign('sSubMenuText',$aSubMenuText[$iRunner]); $smarty2->display('common/submenu_row.tpl'); $sTemp = ob_get_contents(); ob_end_clean(); $iRunner++; $smarty->assign($x,$sTemp); } # Assign the submenu to the mainframe center block $smarty->assign('sMainBlockIncludeFile','doctors/submenu_doctors.tpl'); /** * show Template */ $smarty->display('common/mainframe.tpl'); ?>
victorkagimu/khl-care2x
modules/doctors/doctors.php
PHP
gpl-2.0
3,412
## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # http://www.morningstarsecurity.com/research/whatweb ## # Version 0.2 # # Fixed regex to return multiple scripts ## Plugin.define "Script-URLs" do author "Brendan Coles <bcoles@gmail.com>" # 2010-10-14 version "0.2" description "This plugin detects instances of script HTML elements and retrieves the URL." # Google results as at 2010-10-14 # # 384 for "your browser does not support javascript" # Examples # examples %w| github.com morningstarsecurity.com twitter.com wordpress.com www.microsoft.com | # Matches # matches [ # Extract source URL { :string=>/<script[^>]+src\s*=\s*["']?([^>^"^']+)/i }, ] end
tennc/WhatWeb
plugins-disabled/script-urls.rb
Ruby
gpl-2.0
805
<?php //- $ranges=Array( "2483093504" => array("2483159039","US"), "2483159040" => array("2483224575","SE"), "2483224576" => array("2483290111","GB"), "2483290112" => array("2483421183","US"), "2483421184" => array("2483486719","HU"), "2483486720" => array("2486566911","US"), "2486566912" => array("2486632447","CH"), "2486632448" => array("2486697983","US"), "2486697984" => array("2486763519","AT"), "2486763520" => array("2486960127","US"), "2486960128" => array("2487025663","FR"), "2487025664" => array("2488205311","US"), "2488205312" => array("2488270847","GB"), "2488270848" => array("2488336383","US"), "2488336384" => array("2488401919","PL"), "2488401920" => array("2488532991","NO"), "2488532992" => array("2488795135","US"), "2488795136" => array("2488860671","GB"), "2488860672" => array("2489647103","US"), "2489843712" => array("2490236927","US"), "2490236928" => array("2490302463","LU"), "2490302464" => array("2490695679","US"), "2490695680" => array("2490761215","CA"), "2490761216" => array("2491154431","NO"), "2491154432" => array("2491875327","US"), "2491875328" => array("2492006399","SE"), "2492006400" => array("2492071935","US"), "2492071936" => array("2492137471","SE"), "2492137472" => array("2492203007","US"), "2492203008" => array("2492268543","NO"), "2492268544" => array("2492399615","US"), "2492399616" => array("2492465151","FR"), "2492465152" => array("2492530687","US"), "2492530688" => array("2492596223","AU"), "2492596224" => array("2492727295","US"), "2492727296" => array("2492792831","NL"), "2492792832" => array("2492923903","US"), "2492923904" => array("2492989439","OM"), "2492989440" => array("2493513727","US"), "2493513728" => array("2493579263","SE"), "2493579264" => array("2493644799","JP"), "2493644800" => array("2493710335","US"), "2493755904" => array("2493756415","US"), "2493775872" => array("2494103551","US"), "2494103552" => array("2494169087","FR"), "2494169088" => array("2494562303","US"), "2494562304" => array("2494627839","GB"), "2494627840" => array("2494889983","US"), "2494889984" => array("2494955519","GB"), "2494955520" => array("2495021055","AU"), "2495021056" => array("2495152127","US"), "2495152128" => array("2495217663","EU"), "2495217664" => array("2495283199","US"), "2495283200" => array("2495348735","CH"), "2495348736" => array("2495807487","US"), "2495807488" => array("2495873023","AU"), "2495873024" => array("2495938559","CH"), "2495938560" => array("2496004095","GB"), "2496004096" => array("2496069631","AT"), "2496069632" => array("2496135167","US"), "2496135168" => array("2496200703","NL"), "2496200704" => array("2499477503","MX"), "2499477504" => array("2499543039","DE"), "2499543040" => array("2499674111","GB"), "2499674112" => array("2499739647","US"), ); ?>
furax37/yeswiki
tools/ipblock/ip_files/148.php
PHP
gpl-2.0
2,760
<?php $conf['output'] = 'file'; $conf['usecache'] = 1; $conf['template'] = 'default'; $conf['maxbookmarks'] = 5; $conf['usestyles'] = ''; $conf['qrcodesize'] = '120x120';
neutrinog/Door43
lib/plugins/dw2pdf/conf/default.php
PHP
gpl-2.0
202
require 'spec_helper' describe EmbedController do let(:host) { "eviltrout.com" } let(:embed_url) { "http://eviltrout.com/2013/02/10/why-discourse-uses-emberjs.html" } it "is 404 without an embed_url" do get :best response.should_not be_success end it "raises an error with a missing host" do SiteSetting.stubs(:embeddable_host).returns(nil) get :best, embed_url: embed_url response.should_not be_success end context "with a host" do before do SiteSetting.stubs(:embeddable_host).returns(host) end it "raises an error with no referer" do get :best, embed_url: embed_url response.should_not be_success end context "success" do before do controller.request.stubs(:referer).returns(embed_url) end after do response.should be_success response.headers['X-Frame-Options'].should == "ALLOWALL" end it "tells the topic retriever to work when no previous embed is found" do TopicEmbed.expects(:topic_id_for_embed).returns(nil) retriever = mock TopicRetriever.expects(:new).returns(retriever) retriever.expects(:retrieve) get :best, embed_url: embed_url end it "creates a topic view when a topic_id is found" do TopicEmbed.expects(:topic_id_for_embed).returns(123) TopicView.expects(:new).with(123, nil, {best: 5}) get :best, embed_url: embed_url end end end end
niknard/posts_app
spec/controllers/embed_controller_spec.rb
Ruby
gpl-2.0
1,480
<?php include('page_inc/page_top.php'); ?> <div class="twoColRight" id="content"> <div id='navCol' class='clearfix '> <?php print $section_sub_menu; ?> &nbsp; <?php include('page_inc/saved_search_nav.php');?> </div> <div class="subcontent-wrapper"> <div id="mainCol"> <?php print $content; ?> </div> </div> </div> <?php include('page_inc/page_bottom.php'); ?>
himsme91/education
sites/all/themes/usgbc/templates/page/page-people.tpl.php
PHP
gpl-2.0
417
<?php namespace Mittwald\Typo3Forum\ViewHelpers\Post; /* - * * COPYRIGHT NOTICE * * * * (c) 2015 Mittwald CM Service GmbH & Co KG * * All rights reserved * * * * This script is part of the TYPO3 project. The TYPO3 project is * * free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published * * by the Free Software Foundation; either version 2 of the License, * * or (at your option) any later version. * * * * The GNU General Public License can be found at * * http://www.gnu.org/copyleft/gpl.html. * * * * This script 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. * * * * This copyright notice MUST APPEAR in all copies of the script! * * */ use Mittwald\Typo3Forum\Domain\Model\Forum\Post; use TYPO3\CMS\Fluid\ViewHelpers\CObjectViewHelper; class HelpfulButtonViewHelper extends CObjectViewHelper { /** * @var array */ protected $settings = null; /** * The frontend user repository. * @var \Mittwald\Typo3Forum\Domain\Repository\User\FrontendUserRepository */ protected $frontendUserRepository = null; /** * An authentication service. Handles the authentication mechanism. * * @var \Mittwald\Typo3Forum\Service\Authentication\AuthenticationServiceInterface * @inject */ protected $authenticationService; public function initialize() { parent::initialize(); $this->settings = $this->templateVariableContainer->get('settings'); } public function initializeArguments() { parent::initializeArguments(); $this->registerArgument('class', 'string', 'CSS class'); $this->registerArgument('post', Post::class, 'Post'); $this->registerArgument('countTarget', 'string', 'countTarget'); $this->registerArgument('countUserTarget', 'string', 'countUserTarget'); $this->registerArgument('title', 'string', 'title'); } /** * @return string */ public function render() { $class = $this->settings['forum']['post']['helpfulBtn']['iconClass']; /* @var \Mittwald\Typo3Forum\Domain\Model\Forum\Post $post */ $post = $this->arguments['post']; $title = $this->arguments['title']; $countUserTarget = $this->arguments['countUserTarget']; $countTarget = $this->arguments['countTarget']; if ($this->hasArgument('class')) { $class .= ' ' . $this->arguments['class']; } if ($post->getAuthor()->getUid() != $this->authenticationService->getUser()->getUid() && !$this->authenticationService->getUser()->isAnonymous()) { $class .= ' tx-typo3forum-helpfull-btn'; } if ($post->hasBeenSupportedByUser($this->authenticationService->getUser())) { $class .= ' supported'; } $btn = '<div data-toogle="tooltip" title="' . $title . '" class="' . $class . '" data-countusertarget="' . $countUserTarget . '" data-counttarget="' . $countTarget . '" data-post="' . $post->getUid() . '" data-pageuid="' . $this->settings['pids']['Forum'] . '" data-eid="' . $this->settings['forum']['post']['helpfulBtn']['eID'] . '"></div>'; return $btn; } }
mittwald/typo3-forum
Classes/ViewHelpers/Post/HelpfulButtonViewHelper.php
PHP
gpl-2.0
4,186
/* queryj Copyright (C) 2002-today Jose San Leandro Armendariz chous@acm-sl.org This library 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 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 General Public License for more details. You should have received a copy of the GNU 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 Thanks to ACM S.L. for distributing this library under the GPL license. Contact info: jose.sanleandro@acm-sl.com ****************************************************************************** * * Filename: TemplateGeneratorTemplateBuildHandler.java * * Author: Jose San Leandro Armendariz * * Description: Is responsible of building TemplateGeneratorTemplates. * * Date: 2013/08/21 * Time: 22:12 * */ package org.acmsl.queryj.templates.packaging.handlers; /* * Importing QueryJ-Core classes. */ import org.acmsl.queryj.QueryJCommand; import org.acmsl.queryj.QueryJCommandWrapper; import org.acmsl.queryj.templates.packaging.DefaultTemplatePackagingContext; import org.acmsl.queryj.templates.packaging.Literals; import org.acmsl.queryj.templates.packaging.TemplateDef; import org.acmsl.queryj.templates.packaging.TemplateGeneratorTemplate; import org.acmsl.queryj.templates.packaging.TemplateGeneratorTemplateFactory; /* * Importing JetBrains annotations. */ import org.jetbrains.annotations.NotNull; /* * Importing checkthread.org annotations. */ import org.checkthread.annotations.ThreadSafe; /* * Importing JDK classes. */ import java.util.List; /** * Is responsible of building {@link TemplateGeneratorTemplate}s. * @author <a href="mailto:queryj@acm-sl.org">Jose San Leandro</a> * @since 3.0 * Created: 2013/08/21 22:12 */ @ThreadSafe public class TemplateGeneratorTemplateBuildHandler extends PerTemplateDefBuildHandler <TemplateGeneratorTemplate<DefaultTemplatePackagingContext>, TemplateGeneratorTemplateFactory, DefaultTemplatePackagingContext> { /** * Builds the context from given parameters. * @param templateDef the template def. * @param parameters the command with the parameters. * @return the template context. */ @NotNull @Override protected DefaultTemplatePackagingContext buildContext( @NotNull final TemplateDef<String> templateDef, @NotNull final QueryJCommand parameters) { return buildDefaultContext(templateDef, parameters); } /** * Retrieves the template factory. * @return such instance. */ @NotNull @Override protected TemplateGeneratorTemplateFactory retrieveTemplateFactory() { return TemplateGeneratorTemplateFactory.getInstance(); } /** * Retrieves the template name, using the parameters if necessary. * @param parameters the parameters. * @return the template name. */ @NotNull @Override protected String retrieveTemplateName(@NotNull final QueryJCommand parameters) { return Literals.TEMPLATE_GENERATOR; } /** * Stores the templates in given attribute map. * @param templates the templates. * @param parameters the parameter map. */ @Override protected void storeTemplates( @NotNull final List<TemplateGeneratorTemplate<DefaultTemplatePackagingContext>> templates, @NotNull final QueryJCommand parameters) { new QueryJCommandWrapper <List<TemplateGeneratorTemplate<DefaultTemplatePackagingContext>>>(parameters) .setSetting(TEMPLATE_GENERATOR_TEMPLATES, templates); } /** * Retrieves the output package for the generated file. * @param parameters the parameters. * @return such package. */ @NotNull @Override protected String retrieveOutputPackage(@NotNull final QueryJCommand parameters) { return OUTPUT_PACKAGE; } }
rydnr/queryj
queryj-template-packaging/src/main/java/org/acmsl/queryj/templates/packaging/handlers/TemplateGeneratorTemplateBuildHandler.java
Java
gpl-2.0
4,398
/* --------------------------------------------------------------------------- * UI Sortable init for items * --------------------------------------------------------------------------- */ function mfnSortableInit(item){ item.find('.mfn-sortable').sortable({ connectWith : '.mfn-sortable', cursor : 'move', forcePlaceholderSize : true, placeholder : 'mfn-placeholder', items : '.mfn-item', opacity : 0.9, receive : mfnSortableReceive }); return item; } /* --------------------------------------------------------------------------- * UI Sortable receive callback * --------------------------------------------------------------------------- */ function mfnSortableReceive(event, ui){ var targetSectionID = jQuery(this).siblings('.mfn-row-id').val(); ui.item.find('.mfn-item-parent').val(targetSectionID); } /* --------------------------------------------------------------------------- * Muffin Builder 2.0 * --------------------------------------------------------------------------- */ function mfnBuilder(){ var desktop = jQuery('#mfn-desk'); if( ! desktop.length ) return false; // Exit if Builder HTML does not exist var sectionID = jQuery('#mfn-row-id'); // sizes & classes ======================================== // available items ---------------------------------------- var items = { 'accordion' : [ '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'article_box' : [ '1/3', '1/2' ], 'blockquote' : [ '1/6', '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'blog' : [ '1/1' ], 'blog_news' : [ '1/4', '1/3', '1/2' ], 'blog_slider' : [ '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'call_to_action' : [ '1/1' ], 'chart' : [ '1/4', '1/3', '1/2' ], 'clients' : [ '1/1' ], 'clients_slider' : [ '1/1' ], 'code' : [ '1/6', '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'column' : [ '1/6', '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'contact_box' : [ '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'content' : [ '1/6', '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'countdown' : [ '1/1' ], 'counter' : [ '1/6', '1/5', '1/4', '1/3', '1/2' ], 'divider' : [ '1/1' ], 'fancy_divider' : [ '1/1' ], 'fancy_heading' : [ '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'feature_list' : [ '1/1' ], 'faq' : [ '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'flat_box' : [ '1/4', '1/3', '1/2' ], 'hover_box' : [ '1/6', '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'hover_color' : [ '1/6', '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'how_it_works' : [ '1/4', '1/3' ], 'icon_box' : [ '1/5', '1/4', '1/3', '1/2' ], 'image' : [ '1/6', '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'info_box' : [ '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'list' : [ '1/6', '1/5', '1/4', '1/3', '1/2' ], 'map' : [ '1/6', '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'offer' : [ '1/1' ], 'offer_thumb' : [ '1/1' ], 'opening_hours' : [ '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'our_team' : [ '1/6', '1/5', '1/4', '1/3', '1/2' ], 'our_team_list' : [ '1/1' ], 'photo_box' : [ '1/6', '1/5', '1/4', '1/3', '1/2' ], 'placeholder' : [ '1/6', '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'portfolio' : [ '1/1' ], 'portfolio_grid' : [ '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'portfolio_photo' : [ '1/1' ], 'portfolio_slider' : [ '1/1' ], 'pricing_item' : [ '1/6', '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'progress_bars' : [ '1/6', '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'promo_box' : [ '1/2' ], 'quick_fact' : [ '1/6', '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'shop_slider' : [ '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'sidebar_widget' : [ '1/4', '1/3' ], 'slider' : [ '1/2', '2/3', '3/4', '1/1' ], 'slider_plugin' : [ '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'sliding_box' : [ '1/6', '1/5', '1/4', '1/3', '1/2' ], 'story_box' : [ '1/4', '1/3', '1/2' ], 'tabs' : [ '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'testimonials' : [ '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'testimonials_list' : [ '1/1' ], 'trailer_box' : [ '1/6', '1/5', '1/4', '1/3', '1/2' ], 'timeline' : [ '1/1' ], 'video' : [ '1/6', '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'visual' : [ '1/6', '1/5', '1/4', '1/3', '1/2', '2/3', '3/4', '1/1' ], 'zoom_box' : [ '1/4', '1/3', '1/2' ] }; // available classes ------------------------------------------ var classes = { '1/6' : 'mfn-item-1-6', '1/5' : 'mfn-item-1-5', '1/4' : 'mfn-item-1-4', '1/3' : 'mfn-item-1-3', '1/2' : 'mfn-item-1-2', '2/3' : 'mfn-item-2-3', '3/4' : 'mfn-item-3-4', '1/1' : 'mfn-item-1-1' }; // available textarea shortcodes ------------------------------ var shortcodes = { 'alert' : '[alert style="warning"]Insert your content here[/alert]', 'blockquote' : '[blockquote author="" link="" target="_blank"]Insert your content here[/blockquote]', 'button' : '[button title="" icon="" icon_position="" link="" target="_blank" color="" font_color="" large="0" class="" download="" onclick=""]', 'code' : '[code]Insert your content here[/code]', 'content_link' : '[content_link title="" icon="icon-lamp" link="" target="_blank" class="" download=""]', 'dropcap' : '[dropcap background="" color="" circle="0"]I[/dropcap]nsert your content here', 'fancy_link' : '[fancy_link title="" link="" target="" style="1" class="" download=""]', 'google_font' : '[google_font font="Open Sans" size="25" weight="400" italic="0" color="#626262" subset=""]Insert your content here[/google_font]', 'highlight' : '[highlight background="" color=""]Insert your content here[/highlight]', 'hr' : '[hr height="30" style="default" line="default" themecolor="1"]', 'icon' : '[icon type="icon-lamp"]', 'icon_bar' : '[icon_bar icon="icon-lamp" link="" target="_blank" size="" social=""]', 'icon_block' : '[icon_block icon="icon-lamp" align="" color="" size="25"]', 'idea' : '[idea]Insert your content here[/idea]', 'image' : '[image src="" align="" caption="" link="" link_image="" target="" alt="" border="0" greyscale="0" animate=""]', 'popup' : '[popup title="Title" padding="0" button="0"]Insert your popup content here[/popup]', 'progress_icons' : '[progress_icons icon="icon-heart-line" count="5" active="3" background=""]', 'share_box' : '[share_box]', 'table' : '<table><thead><tr><th>Column 1 heading</th><th>Column 2 heading</th><th>Column 3 heading</th></tr></thead><tbody><tr><td>Row 1 col 1 content</td><td>Row 1 col 2 content</td><td>Row 1 col 3 content</td></tr><tr><td>Row 2 col 1 content</td><td>Row 2 col 2 content</td><td>Row 2 col 3 content</td></tr></tbody></table>', 'tooltip' : '[tooltip hint="Insert your hint here"]Insert your content here[/tooltip]', 'tooltip_image' : '[tooltip_image hint="Insert your hint here" image=""]Insert your content here[/tooltip_image]', }; // jquery.ui ================================================= desktop.sortable({ cursor : 'move', forcePlaceholderSize : true, placeholder : 'mfn-placeholder', items : '.mfn-row', opacity : 0.9 }); desktop.find('.mfn-sortable').sortable({ connectWith : '.mfn-sortable', cursor : 'move', forcePlaceholderSize : true, placeholder : 'mfn-placeholder', items : '.mfn-item', opacity : 0.9, receive : mfnSortableReceive }); // section =================================================== // add section ----------------------------------------------- jQuery('.mfn-row-add-btn').click(function(){ var clone = jQuery('#mfn-rows .mfn-row').clone(true); clone.find('.mfn-sortable').sortable({ connectWith : '.mfn-sortable', cursor : 'move', forcePlaceholderSize : true, placeholder : 'mfn-placeholder', items : '.mfn-item', opacity : 0.9, receive : mfnSortableReceive }); clone.hide() .find('.mfn-element-content > input').each(function() { jQuery(this).attr('name',jQuery(this).attr('class')+'[]'); }); sectionID.val(sectionID.val()*1+1); clone .find('.mfn-row-id').val(sectionID.val()); desktop.append(clone).find(".mfn-row").fadeIn(500); }); // clone section --------------------------------------------- jQuery('.mfn-row .mfn-row-clone').click(function(){ var element = jQuery(this).closest('.mfn-element'); // sortable destroy, clone & init for cloned element element.find('.mfn-sortable').sortable('destroy'); var clone = element.clone(true); mfnSortableInit(element); mfnSortableInit(clone); sectionID.val(sectionID.val()*1+1); clone .find('.mfn-row-id, .mfn-item-parent').val(sectionID.val()); element.after(clone); }); // add item list toggle --------------------------------------- jQuery('.mfn-item-add-btn').click(function(){ var parent = jQuery(this).parent(); if( parent.hasClass('focus') ){ parent.removeClass('focus'); } else { jQuery('.mfn-item-add').removeClass('focus'); parent.addClass('focus'); } }); // add item --------------------------------------------------- jQuery('.mfn-item-add-list a').click(function(){ jQuery(this).closest('.mfn-item-add').removeClass('focus'); var parentDesktop = jQuery(this).parents('.mfn-row').find('.mfn-droppable'); var targetSectionID = jQuery(this).parents('.mfn-row').find('.mfn-row-id').val(); var item = jQuery(this).attr('class'); var clone = jQuery('#mfn-items').find('div.mfn-item-'+ item ).clone(true); clone .hide() .find('.mfn-element-content input').each(function() { jQuery(this).attr('name',jQuery(this).attr('class')+'[]'); }); clone.find('.mfn-item-parent').val(targetSectionID); parentDesktop.append(clone).find(".mfn-item").fadeIn(500); }); // item ======================================================= // increase item size -------------------------------------- jQuery('.mfn-item-size-inc').click(function(){ var item = jQuery(this).closest('.mfn-item'); var item_type = item.find('.mfn-item-type').val(); var item_sizes = items[item_type]; for( var i = 0; i < item_sizes.length-1; i++ ){ if( ! item.hasClass( classes[item_sizes[i]] ) ) continue; item .removeClass( classes[item_sizes[i]] ) .addClass( classes[item_sizes[i+1]] ) .find('.mfn-item-size').val( item_sizes[i+1] ); item.find('.mfn-item-desc').text( item_sizes[i+1] ); break; } }); // decrease size ---------------------------------------------- jQuery('.mfn-item-size-dec').click(function(){ var item = jQuery(this).closest('.mfn-item'); var item_type = item.find('.mfn-item-type').val(); var item_sizes = items[item_type]; for( var i = 1; i < item_sizes.length; i++ ){ if( ! item.hasClass( classes[item_sizes[i]] ) ) continue; item .removeClass( classes[item_sizes[i]] ) .addClass( classes[item_sizes[i-1]] ) .find('.mfn-item-size').val( item_sizes[i-1]); item.find('.mfn-item-desc').text( item_sizes[i-1] ); break; } }); // clone item --------------------------------------------- jQuery('.mfn-item .mfn-item-clone').click(function(){ var element = jQuery(this).closest('.mfn-element'); var clone = element.clone(true); element.after(clone); }); // element =================================================== // delete element -------------------------------------------- jQuery('.mfn-element-delete').click(function(){ var item = jQuery(this).closest('.mfn-element'); if( confirm( "You are about to delete this element.\nIt can not be restored at a later time! Continue?" ) ){ item.fadeOut(500,function(){jQuery(this).remove();}); } else { return false; } }); // helper - switch editor ------------------------------------ jQuery('#mfn-popup').on('click', '.mfn-switch-editor', function(e) { e.preventDefault(); if( tinymce.get('mfn-editor') ) { var tinyHTML = tinymce.get('mfn-editor').getContent(); // Fix | HTML Tags 1/2 tinymce.execCommand('mceRemoveEditor', false, 'mfn-editor'); jQuery('#mfn-editor').val( tinyHTML ); // Fix | HTML Tags 2/2 } else { tinymce.execCommand('mceAddEditor', false, 'mfn-editor'); } }); var source_item = ''; var source_top = ''; // popup - edit ----------------------------------------------- jQuery('.mfn-element-edit').click(function(){ source_top = jQuery(this).offset().top; // hide Publish/Update button jQuery('#publish').fadeOut(500); jQuery('#vc_navbar').fadeOut(500); jQuery('#mfn-content, .form-table').fadeOut(50); source_item = jQuery(this).closest('.mfn-element'); var clone_meta = source_item.children('.mfn-element-meta').clone(true); jQuery('#mfn-popup') .append(clone_meta) .fadeIn(500); // FIX | Chrome 43.0.2357.65 (64-bit) jQuery('#mfn-popup textarea').each(function(){ var chromeFix = jQuery(this).val(); jQuery(this).html( chromeFix + ' ' ); //jQuery(this).val( chromeFix ); }); // scroll if( jQuery('#mfn-wrapper').length > 0 ){ var adjustment = 30; jQuery('html, body').animate({ scrollTop: jQuery('#mfn-wrapper').offset().top - adjustment }, 500); } source_item.children('.mfn-element-meta').remove(); // mce - editor --------------- jQuery('#mfn-popup textarea.editor').attr('id','mfn-editor'); try { jQuery('.wp-switch-editor.switch-html').click(); jQuery('.wp-switch-editor.switch-tmce').click(); tinymce.execCommand('mceAddEditor', true, 'mfn-editor'); } catch (err) { // console.log(err); } jQuery('#mfn-popup .mce-tinymce .mce-i-wp_more, #mfn-popup .mce-tinymce .mce-i-dfw, #mfn-popup .mce-tinymce .mce_woocommerce_shortcodes_button, #mfn-popup .mce-tinymce .mce_revslider') .closest('.mce-btn').remove(); // removed since Be 4.5, restored since Be 7.3 jQuery('#mfn-popup .mce-tinymce').closest('td').prepend('<a href="#" class="mfn-switch-editor"">Visual / HTML<span>may remove some tags</span></a>'); // end: mce - editor ---------- }); // popup - close ---------------------------------------------- jQuery('#mfn-popup .mfn-popup-close, #mfn-popup .mfn-popup-save').click(function(){ // mce - editor --------------- try { if( tinymce.get('mfn-editor') ){ jQuery('#mfn-editor').html( tinymce.get('mfn-editor').getContent() ); tinymce.execCommand('mceRemoveEditor', false, 'mfn-editor'); } else { jQuery('#mfn-editor').html( jQuery('#mfn-editor').val() ); } } catch (err) { // console.log(err); } jQuery('.mfn-switch-editor').remove(); jQuery('#mfn-editor').removeAttr('id'); // end: mce - editor ---------- // destroy sortable for fields 'tabs' if( jQuery('#mfn-popup .tabs-ul.ui-sortable').length ){ jQuery('#mfn-popup .tabs-ul.ui-sortable').sortable('destroy'); } // hide Publish/Update button jQuery('#publish').fadeIn(500); jQuery('#vc_navbar').fadeIn(500); jQuery('#mfn-content, .form-table').fadeIn(500); var popup = jQuery('#mfn-popup'); var clone = popup.find('.mfn-element-meta').clone(true); source_item.append(clone); popup.fadeOut(50); setTimeout(function(){ popup.find('.mfn-element-meta').remove(); },50); // scroll if( source_top ){ var adjustment = 40; if( jQuery('.vc_subnav-fixed').length > 0 ) adjustment = 96; jQuery('html, body').animate({ scrollTop: source_top - adjustment }, 500); } }); // go to top =================================================== jQuery('#mfn-go-to-top').click(function(){ jQuery('html, body').animate({ scrollTop: 0 }, 500); }); // post formats ================================================ jQuery("#post-formats-select label.post-format-standard").text('Standard, Horizontal Image'); jQuery("#post-formats-select label.post-format-image").text('Vertical Image'); // migrate ========================================================= // show/hide jQuery('#mfn-migrate .btn-exp').click(function(){ alert('Please remember to Publish/Update your post before Export.'); jQuery('.migrate-wrapper ').hide(); jQuery('.export-wrapper').show(); }); jQuery('#mfn-migrate .btn-imp').click(function(){ jQuery('.migrate-wrapper ').hide(); jQuery('.import-wrapper').show(); }); jQuery('#mfn-migrate .btn-tem').click(function(){ jQuery('.migrate-wrapper ').hide(); jQuery('.templates-wrapper').show(); }); // copy to clipboard jQuery('#mfn-items-export').click(function(){ jQuery(this).select(); }); // import jQuery('#mfn-migrate .btn-import').click(function(){ var el = jQuery(this).siblings('#mfn-items-import'); el.attr('name',el.attr('id')); jQuery('#publish').click(); }); // template jQuery('#mfn-migrate .btn-template').click(function(){ var el = jQuery(this).siblings('#mfn-items-import-template'); el.attr('name',el.attr('id')); jQuery('#publish').click(); }); // seo ========================================================= jQuery('#wp-content-wrap .wp-editor-tabs').prepend('<a class="wp-switch-editor switch-seo" id="content-seo">Builder &raquo; SEO</a>'); jQuery('#content-seo').click(function(){ if( confirm( "This option is useful for plugins like Yoast SEO to analize post content when you use Muffin Builder.\nIt will collect content from Muffin Builder Elements and copy it into the WordPress Editor.\n\nCurrent Editor Content will be replaced.\nYou can hide the content if you turn \"Hide the content\" option ON.\n\nPlease remember to Publish/Update your post before & after use of this option.\nContinue?" ) ){ var items_decoded = jQuery('#mfn-items-seo-data').val(); console.log(items_decoded); jQuery('#content-html').click(); jQuery('#content').val( items_decoded ).text( items_decoded ); } else { return false; } }); // Textarea | Shortcodes ======================================== // Helper | Wrap Selected Text OR Insert Into Carret ------------ function wrapText(textArea, openTag, closeTag){ var len = textArea.val().length; var start = textArea[0].selectionStart; var end = textArea[0].selectionEnd; var selectedText = textArea.val().substring(start, end); var replacement = openTag + selectedText + closeTag; textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len)); } // Add Shortcode | Menu ----------------------------------------- jQuery('.mfn-sc-add-btn').click(function(){ var parent = jQuery(this).parent(); if( parent.hasClass('focus') ){ parent.removeClass('focus'); } else { jQuery('.mfn-sc-add').removeClass('focus'); parent.addClass('focus'); } }); // Insert Shortcode ------------------------------------------------ jQuery('.mfn-sc-add-list a').click(function(){ jQuery(this).closest('.mfn-sc-add').removeClass('focus'); var sc = jQuery(this).attr('data-rel'); if( sc ){ var shortcode = shortcodes[sc]; var textarea = jQuery(this).closest('td').find('textarea'); wrapText( textarea, shortcode, '' ); } }); // Insert HTML Tag ------------------------------------------------ jQuery('.mfn-sc-tools a').click(function(){ var open = jQuery(this).attr('data-open'); var close = jQuery(this).attr('data-close'); var open = open.replace( /X/g, '"' ); if( close ){ open = '<'+ open + '>'; close = '</'+ close + '>'; } else { open = '<'+ open + ' />'; close = ''; } var textarea = jQuery(this).closest('td').find('textarea'); wrapText( textarea, open, close ); }); } /* --------------------------------------------------------------------------- * Clone fix (textarea, select) * --------------------------------------------------------------------------- */ (function (original) { jQuery.fn.clone = function(){ var result = original.apply (this, arguments), my_textareas = this.find('textarea:not(.editor), select'), result_textareas = result.find('textarea:not(.editor), select'); for (var i = 0, l = my_textareas.length; i < l; ++i){ jQuery(result_textareas[i]).val( jQuery(my_textareas[i]).val() ); } return result; }; })(jQuery.fn.clone); /* --------------------------------------------------------------------------- * jQuery(document).ready * --------------------------------------------------------------------------- */ jQuery(document).ready(function(){ mfnBuilder(); }); /* --------------------------------------------------------------------------- * jQuery(document).mouseup * --------------------------------------------------------------------------- */ jQuery(document).mouseup(function(e) { if (jQuery(".mfn-item-add").has(e.target).length === 0){ jQuery(".mfn-item-add").removeClass('focus'); } if (jQuery(".mfn-sc-add").has(e.target).length === 0){ jQuery(".mfn-sc-add").removeClass('focus'); } });
ehsangolshani/mohsenGMD-website
wp-content/themes/betheme/functions/js/mfn.builder.js
JavaScript
gpl-2.0
21,172
/* * Copyright (C) 2012-2013 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ /** * TODO: * - use Observable here, so we can use event driven operations later */ #include "settings/AdvancedSettings.h" #include "settings/lib/Setting.h" #include "settings/Settings.h" #include "guilib/GUIWindowManager.h" #include "dialogs/GUIDialogYesNo.h" #include "dialogs/GUIDialogOK.h" #include "music/tags/MusicInfoTag.h" #include "utils/log.h" #include "Util.h" #include "utils/StringUtils.h" #include "threads/SingleLock.h" #include "PVRChannelGroupsContainer.h" #include "pvr/PVRDatabase.h" #include "pvr/PVRManager.h" #include "pvr/addons/PVRClients.h" #include "epg/EpgContainer.h" using namespace PVR; using namespace EPG; CPVRChannelGroup::CPVRChannelGroup(void) : m_bRadio(false), m_iGroupType(PVR_GROUP_TYPE_DEFAULT), m_iGroupId(-1), m_bLoaded(false), m_bChanged(false), m_bUsingBackendChannelOrder(false), m_bSelectedGroup(false), m_bPreventSortAndRenumber(false) { } CPVRChannelGroup::CPVRChannelGroup(bool bRadio, unsigned int iGroupId, const CStdString &strGroupName) : m_bRadio(bRadio), m_iGroupType(PVR_GROUP_TYPE_DEFAULT), m_iGroupId(iGroupId), m_strGroupName(strGroupName), m_bLoaded(false), m_bChanged(false), m_bUsingBackendChannelOrder(false), m_bSelectedGroup(false), m_bPreventSortAndRenumber(false) { } CPVRChannelGroup::CPVRChannelGroup(const PVR_CHANNEL_GROUP &group) : m_bRadio(group.bIsRadio), m_iGroupType(PVR_GROUP_TYPE_DEFAULT), m_iGroupId(-1), m_strGroupName(group.strGroupName), m_bLoaded(false), m_bChanged(false), m_bUsingBackendChannelOrder(false), m_bSelectedGroup(false), m_bPreventSortAndRenumber(false) { } CPVRChannelGroup::~CPVRChannelGroup(void) { Unload(); } bool CPVRChannelGroup::operator==(const CPVRChannelGroup& right) const { return (m_bRadio == right.m_bRadio && m_iGroupType == right.m_iGroupType && m_iGroupId == right.m_iGroupId && m_strGroupName.Equals(right.m_strGroupName)); } bool CPVRChannelGroup::operator!=(const CPVRChannelGroup &right) const { return !(*this == right); } CPVRChannelGroup::CPVRChannelGroup(const CPVRChannelGroup &group) { m_bRadio = group.m_bRadio; m_iGroupType = group.m_iGroupType; m_iGroupId = group.m_iGroupId; m_strGroupName = group.m_strGroupName; m_bLoaded = group.m_bLoaded; m_bChanged = group.m_bChanged; m_bUsingBackendChannelOrder = group.m_bUsingBackendChannelOrder; m_bUsingBackendChannelNumbers = group.m_bUsingBackendChannelNumbers; for (int iPtr = 0; iPtr < group.Size(); iPtr++) m_members.push_back(group.m_members.at(iPtr)); } bool CPVRChannelGroup::Load(void) { /* make sure this container is empty before loading */ Unload(); m_bUsingBackendChannelOrder = CSettings::Get().GetBool("pvrmanager.backendchannelorder"); m_bUsingBackendChannelNumbers = CSettings::Get().GetBool("pvrmanager.usebackendchannelnumbers"); int iChannelCount = m_iGroupId > 0 ? LoadFromDb() : 0; CLog::Log(LOGDEBUG, "PVRChannelGroup - %s - %d channels loaded from the database for group '%s'", __FUNCTION__, iChannelCount, m_strGroupName.c_str()); if (!Update()) { CLog::Log(LOGERROR, "PVRChannelGroup - %s - failed to update channels", __FUNCTION__); return false; } if (Size() - iChannelCount > 0) { CLog::Log(LOGDEBUG, "PVRChannelGroup - %s - %d channels added from clients to group '%s'", __FUNCTION__, Size() - iChannelCount, m_strGroupName.c_str()); } SortAndRenumber(); m_bLoaded = true; return true; } void CPVRChannelGroup::Unload(void) { CSingleLock lock(m_critSection); m_members.clear(); } bool CPVRChannelGroup::Update(void) { if (GroupType() == PVR_GROUP_TYPE_USER_DEFINED || !CSettings::Get().GetBool("pvrmanager.syncchannelgroups")) return true; CPVRChannelGroup PVRChannels_tmp(m_bRadio, m_iGroupId, m_strGroupName); PVRChannels_tmp.SetPreventSortAndRenumber(); PVRChannels_tmp.LoadFromClients(); return UpdateGroupEntries(PVRChannels_tmp); } bool CPVRChannelGroup::SetChannelNumber(const CPVRChannel &channel, unsigned int iChannelNumber) { bool bReturn(false); CSingleLock lock(m_critSection); for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++) { if (*m_members.at(iChannelPtr).channel == channel) { if (m_members.at(iChannelPtr).iChannelNumber != iChannelNumber) { m_bChanged = true; bReturn = true; m_members.at(iChannelPtr).iChannelNumber = iChannelNumber; } break; } } return bReturn; } bool CPVRChannelGroup::MoveChannel(unsigned int iOldChannelNumber, unsigned int iNewChannelNumber, bool bSaveInDb /* = true */) { if (iOldChannelNumber == iNewChannelNumber) return true; bool bReturn(false); CSingleLock lock(m_critSection); /* make sure the list is sorted by channel number */ SortByChannelNumber(); /* old channel number out of range */ if (iOldChannelNumber > m_members.size()) return bReturn; /* new channel number out of range */ if (iNewChannelNumber < 1) return bReturn; if (iNewChannelNumber > m_members.size()) iNewChannelNumber = m_members.size(); /* move the channel in the list */ PVRChannelGroupMember entry = m_members.at(iOldChannelNumber - 1); m_members.erase(m_members.begin() + iOldChannelNumber - 1); m_members.insert(m_members.begin() + iNewChannelNumber - 1, entry); /* renumber the list */ Renumber(); m_bChanged = true; if (bSaveInDb) bReturn = Persist(); else bReturn = true; CLog::Log(LOGNOTICE, "CPVRChannelGroup - %s - %s channel '%s' moved to channel number '%d'", __FUNCTION__, (m_bRadio ? "radio" : "tv"), entry.channel->ChannelName().c_str(), iNewChannelNumber); return true; } bool CPVRChannelGroup::SetChannelIconPath(CPVRChannelPtr channel, const std::string& strIconPath) { if (CFile::Exists(strIconPath)) { channel->SetIconPath(strIconPath, g_advancedSettings.m_bPVRAutoScanIconsUserSet); return true; } return false; } void CPVRChannelGroup::SearchAndSetChannelIcons(bool bUpdateDb /* = false */) { if (CSettings::Get().GetString("pvrmenu.iconpath").empty()) return; CPVRDatabase *database = GetPVRDatabase(); if (!database) return; CSingleLock lock(m_critSection); for (unsigned int ptr = 0; ptr < m_members.size(); ptr++) { PVRChannelGroupMember groupMember = m_members.at(ptr); /* skip if an icon is already set */ if (!groupMember.channel->IconPath().empty()) continue; CStdString strBasePath = CSettings::Get().GetString("pvrmenu.iconpath"); CStdString strSanitizedChannelName = CUtil::MakeLegalFileName(groupMember.channel->ClientChannelName()); CStdString strIconPath = strBasePath + strSanitizedChannelName; StringUtils::ToLower(strSanitizedChannelName); CStdString strIconPathLower = strBasePath + strSanitizedChannelName; CStdString strIconPathUid; strIconPathUid = StringUtils::Format("%08d", groupMember.channel->UniqueID()); strIconPathUid = URIUtils::AddFileToFolder(strBasePath, strIconPathUid); SetChannelIconPath(groupMember.channel, strIconPath + ".tbn") || SetChannelIconPath(groupMember.channel, strIconPath + ".jpg") || SetChannelIconPath(groupMember.channel, strIconPath + ".png") || SetChannelIconPath(groupMember.channel, strIconPathLower + ".tbn") || SetChannelIconPath(groupMember.channel, strIconPathLower + ".jpg") || SetChannelIconPath(groupMember.channel, strIconPathLower + ".png") || SetChannelIconPath(groupMember.channel, strIconPathUid + ".tbn") || SetChannelIconPath(groupMember.channel, strIconPathUid + ".jpg") || SetChannelIconPath(groupMember.channel, strIconPathUid + ".png"); if (bUpdateDb) groupMember.channel->Persist(); /* TODO: start channel icon scraper here if nothing was found */ } } /********** sort methods **********/ struct sortByClientChannelNumber { bool operator()(const PVRChannelGroupMember &channel1, const PVRChannelGroupMember &channel2) { return channel1.channel->ClientChannelNumber() < channel2.channel->ClientChannelNumber(); } }; struct sortByChannelNumber { bool operator()(const PVRChannelGroupMember &channel1, const PVRChannelGroupMember &channel2) { return channel1.iChannelNumber < channel2.iChannelNumber; } }; bool CPVRChannelGroup::SortAndRenumber(void) { if (PreventSortAndRenumber()) return true; CSingleLock lock(m_critSection); if (m_bUsingBackendChannelOrder) SortByClientChannelNumber(); else SortByChannelNumber(); bool bReturn = Renumber(); ResetChannelNumberCache(); return bReturn; } void CPVRChannelGroup::SortByClientChannelNumber(void) { CSingleLock lock(m_critSection); if (!PreventSortAndRenumber()) sort(m_members.begin(), m_members.end(), sortByClientChannelNumber()); } void CPVRChannelGroup::SortByChannelNumber(void) { CSingleLock lock(m_critSection); if (!PreventSortAndRenumber()) sort(m_members.begin(), m_members.end(), sortByChannelNumber()); } /********** getters **********/ CPVRChannelPtr CPVRChannelGroup::GetByClient(int iUniqueChannelId, int iClientID) const { CSingleLock lock(m_critSection); for (unsigned int ptr = 0; ptr < m_members.size(); ptr++) { PVRChannelGroupMember groupMember = m_members.at(ptr); if (groupMember.channel->UniqueID() == iUniqueChannelId && groupMember.channel->ClientID() == iClientID) return groupMember.channel; } CPVRChannelPtr empty; return empty; } CPVRChannelPtr CPVRChannelGroup::GetByChannelID(int iChannelID) const { CSingleLock lock(m_critSection); for (unsigned int ptr = 0; ptr < m_members.size(); ptr++) { PVRChannelGroupMember groupMember = m_members.at(ptr); if (groupMember.channel->ChannelID() == iChannelID) return groupMember.channel; } CPVRChannelPtr empty; return empty; } CPVRChannelPtr CPVRChannelGroup::GetByChannelEpgID(int iEpgID) const { CSingleLock lock(m_critSection); for (unsigned int ptr = 0; ptr < m_members.size(); ptr++) { PVRChannelGroupMember groupMember = m_members.at(ptr); if (groupMember.channel->EpgID() == iEpgID) return groupMember.channel; } CPVRChannelPtr empty; return empty; } CPVRChannelPtr CPVRChannelGroup::GetByUniqueID(int iUniqueID) const { CSingleLock lock(m_critSection); for (unsigned int ptr = 0; ptr < m_members.size(); ptr++) { PVRChannelGroupMember groupMember = m_members.at(ptr); if (groupMember.channel->UniqueID() == iUniqueID) return groupMember.channel; } CPVRChannelPtr empty; return empty; } CFileItemPtr CPVRChannelGroup::GetLastPlayedChannel(unsigned int iCurrentChannel /* = -1 */) const { CSingleLock lock(m_critSection); time_t tCurrentLastWatched(0), tMaxLastWatched(0); if (iCurrentChannel > 0) { CPVRChannelPtr channel = GetByChannelID(iCurrentChannel); if (channel.get()) { CDateTime::GetCurrentDateTime().GetAsTime(tMaxLastWatched); channel->SetLastWatched(tMaxLastWatched); channel->Persist(); } } CPVRChannelPtr returnChannel; for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++) { PVRChannelGroupMember groupMember = m_members.at(iChannelPtr); if (g_PVRClients->IsConnectedClient(groupMember.channel->ClientID()) && groupMember.channel->LastWatched() > 0 && (tMaxLastWatched == 0 || groupMember.channel->LastWatched() < tMaxLastWatched) && (tCurrentLastWatched == 0 || groupMember.channel->LastWatched() > tCurrentLastWatched)) { returnChannel = groupMember.channel; tCurrentLastWatched = returnChannel->LastWatched(); } } if (returnChannel) { CFileItemPtr retVal = CFileItemPtr(new CFileItem(*returnChannel)); return retVal; } CFileItemPtr retVal = CFileItemPtr(new CFileItem); return retVal; } unsigned int CPVRChannelGroup::GetChannelNumber(const CPVRChannel &channel) const { unsigned int iReturn = 0; CSingleLock lock(m_critSection); unsigned int iSize = m_members.size(); for (unsigned int iChannelPtr = 0; iChannelPtr < iSize; iChannelPtr++) { PVRChannelGroupMember member = m_members.at(iChannelPtr); if (member.channel->ChannelID() == channel.ChannelID()) { iReturn = member.iChannelNumber; break; } } return iReturn; } CFileItemPtr CPVRChannelGroup::GetByChannelNumber(unsigned int iChannelNumber) const { CSingleLock lock(m_critSection); for (unsigned int ptr = 0; ptr < m_members.size(); ptr++) { PVRChannelGroupMember groupMember = m_members.at(ptr); if (groupMember.iChannelNumber == iChannelNumber) { CFileItemPtr retVal = CFileItemPtr(new CFileItem(*groupMember.channel)); return retVal; } } CFileItemPtr retVal = CFileItemPtr(new CFileItem); return retVal; } CFileItemPtr CPVRChannelGroup::GetByChannelUpDown(const CFileItem &channel, bool bChannelUp) const { if (channel.HasPVRChannelInfoTag()) { CSingleLock lock(m_critSection); int iChannelIndex = GetIndex(*channel.GetPVRChannelInfoTag()); bool bGotChannel(false); while (!bGotChannel) { if (bChannelUp) iChannelIndex++; else iChannelIndex--; if (iChannelIndex >= (int)m_members.size()) iChannelIndex = 0; else if (iChannelIndex < 0) iChannelIndex = m_members.size() - 1; CFileItemPtr current = GetByIndex(iChannelIndex); if (!current || *current->GetPVRChannelInfoTag() == *channel.GetPVRChannelInfoTag()) break; if (!current->GetPVRChannelInfoTag()->IsHidden()) return current; } } CFileItemPtr retVal(new CFileItem); return retVal; } CFileItemPtr CPVRChannelGroup::GetByIndex(unsigned int iIndex) const { CSingleLock lock(m_critSection); if (iIndex < m_members.size()) { CFileItemPtr retVal = CFileItemPtr(new CFileItem(*m_members.at(iIndex).channel)); return retVal; } CFileItemPtr retVal = CFileItemPtr(new CFileItem); return retVal; } int CPVRChannelGroup::GetIndex(const CPVRChannel &channel) const { int iIndex(-1); CSingleLock lock(m_critSection); for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++) { if (*m_members.at(iChannelPtr).channel == channel) { iIndex = iChannelPtr; break; } } return iIndex; } int CPVRChannelGroup::GetMembers(CFileItemList &results, bool bGroupMembers /* = true */) const { int iOrigSize = results.Size(); CSingleLock lock(m_critSection); const CPVRChannelGroup* channels = bGroupMembers ? this : g_PVRChannelGroups->GetGroupAll(m_bRadio).get(); for (unsigned int iChannelPtr = 0; iChannelPtr < channels->m_members.size(); iChannelPtr++) { CPVRChannelPtr channel = channels->m_members.at(iChannelPtr).channel; if (!channel) continue; if (bGroupMembers || !IsGroupMember(*channel)) { CFileItemPtr pFileItem(new CFileItem(*channel)); results.Add(pFileItem); } } return results.Size() - iOrigSize; } CPVRChannelGroupPtr CPVRChannelGroup::GetNextGroup(void) const { return g_PVRChannelGroups->Get(m_bRadio)->GetNextGroup(*this); } CPVRChannelGroupPtr CPVRChannelGroup::GetPreviousGroup(void) const { return g_PVRChannelGroups->Get(m_bRadio)->GetPreviousGroup(*this); } /********** private methods **********/ int CPVRChannelGroup::LoadFromDb(bool bCompress /* = false */) { CPVRDatabase *database = GetPVRDatabase(); if (!database) return -1; int iChannelCount = Size(); database->Get(*this); return Size() - iChannelCount; } bool CPVRChannelGroup::LoadFromClients(void) { /* get the channels from the backends */ return g_PVRClients->GetChannelGroupMembers(this) == PVR_ERROR_NO_ERROR; } bool CPVRChannelGroup::AddAndUpdateChannels(const CPVRChannelGroup &channels, bool bUseBackendChannelNumbers) { bool bReturn(false); bool bPreventSortAndRenumber(PreventSortAndRenumber()); CSingleLock lock(m_critSection); SetPreventSortAndRenumber(); /* go through the channel list and check for new channels. channels will only by updated in CPVRChannelGroupInternal to prevent dupe updates */ for (unsigned int iChannelPtr = 0; iChannelPtr < channels.m_members.size(); iChannelPtr++) { PVRChannelGroupMember member = channels.m_members.at(iChannelPtr); if (!member.channel) continue; /* check whether this channel is known in the internal group */ CPVRChannelPtr existingChannel = g_PVRChannelGroups->GetGroupAll(m_bRadio)->GetByClient(member.channel->UniqueID(), member.channel->ClientID()); if (!existingChannel) continue; /* if it's found, add the channel to this group */ if (!IsGroupMember(*existingChannel)) { int iChannelNumber = bUseBackendChannelNumbers ? member.channel->ClientChannelNumber() : 0; AddToGroup(*existingChannel, iChannelNumber); bReturn = true; CLog::Log(LOGINFO,"PVRChannelGroup - %s - added %s channel '%s' at position %d in group '%s'", __FUNCTION__, m_bRadio ? "radio" : "TV", existingChannel->ChannelName().c_str(), iChannelNumber, GroupName().c_str()); } } SetPreventSortAndRenumber(bPreventSortAndRenumber); SortAndRenumber(); return bReturn; } bool CPVRChannelGroup::RemoveDeletedChannels(const CPVRChannelGroup &channels) { bool bReturn(false); CSingleLock lock(m_critSection); /* check for deleted channels */ for (int iChannelPtr = m_members.size() - 1; iChannelPtr >= 0; iChannelPtr--) { CPVRChannelPtr channel = m_members.at(iChannelPtr).channel; if (!channel) continue; if (channels.GetByClient(channel->UniqueID(), channel->ClientID()) == NULL) { /* channel was not found */ CLog::Log(LOGINFO,"PVRChannelGroup - %s - deleted %s channel '%s' from group '%s'", __FUNCTION__, m_bRadio ? "radio" : "TV", channel->ChannelName().c_str(), GroupName().c_str()); /* remove this channel from all non-system groups if this is the internal group */ if (IsInternalGroup()) { g_PVRChannelGroups->Get(m_bRadio)->RemoveFromAllGroups(*channel); /* since it was not found in the internal group, it was deleted from the backend */ channel->Delete(); } m_members.erase(m_members.begin() + iChannelPtr); m_bChanged = true; bReturn = true; } } return bReturn; } bool CPVRChannelGroup::UpdateGroupEntries(const CPVRChannelGroup &channels) { bool bReturn(false); bool bChanged(false); bool bRemoved(false); CSingleLock lock(m_critSection); /* sort by client channel number if this is the first time or if pvrmanager.backendchannelorder is true */ bool bUseBackendChannelNumbers(m_members.size() == 0 || m_bUsingBackendChannelOrder); CPVRDatabase *database = GetPVRDatabase(); if (!database) return bReturn; bRemoved = RemoveDeletedChannels(channels); bChanged = AddAndUpdateChannels(channels, bUseBackendChannelNumbers) || bRemoved; if (bChanged) { /* renumber to make sure all channels have a channel number. new channels were added at the back, so they'll get the highest numbers */ bool bRenumbered = SortAndRenumber(); SetChanged(); lock.Leave(); NotifyObservers(HasNewChannels() || bRemoved || bRenumbered ? ObservableMessageChannelGroupReset : ObservableMessageChannelGroup); bReturn = Persist(); } else { bReturn = true; } return bReturn; } void CPVRChannelGroup::RemoveInvalidChannels(void) { bool bDelete(false); CSingleLock lock(m_critSection); for (unsigned int ptr = 0; ptr < m_members.size(); ptr--) { bDelete = false; CPVRChannelPtr channel = m_members.at(ptr).channel; if (channel->IsVirtual()) continue; if (m_members.at(ptr).channel->ClientChannelNumber() <= 0) { CLog::Log(LOGERROR, "PVRChannelGroup - %s - removing invalid channel '%s' from client '%i': no valid client channel number", __FUNCTION__, channel->ChannelName().c_str(), channel->ClientID()); bDelete = true; } if (!bDelete && channel->UniqueID() <= 0) { CLog::Log(LOGERROR, "PVRChannelGroup - %s - removing invalid channel '%s' from client '%i': no valid unique ID", __FUNCTION__, channel->ChannelName().c_str(), channel->ClientID()); bDelete = true; } /* remove this channel from all non-system groups if this is the internal group */ if (bDelete) { if (IsInternalGroup()) { g_PVRChannelGroups->Get(m_bRadio)->RemoveFromAllGroups(*channel); channel->Delete(); } else { m_members.erase(m_members.begin() + ptr); } m_bChanged = true; } } } bool CPVRChannelGroup::RemoveFromGroup(const CPVRChannel &channel) { bool bReturn(false); CSingleLock lock(m_critSection); for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++) { if (channel == *m_members.at(iChannelPtr).channel) { // TODO notify observers m_members.erase(m_members.begin() + iChannelPtr); bReturn = true; m_bChanged = true; break; } } Renumber(); return bReturn; } bool CPVRChannelGroup::AddToGroup(CPVRChannel &channel, int iChannelNumber /* = 0 */) { CSingleLock lock(m_critSection); bool bReturn(false); if (!CPVRChannelGroup::IsGroupMember(channel)) { if (iChannelNumber <= 0 || iChannelNumber > (int) m_members.size() + 1) iChannelNumber = m_members.size() + 1; CPVRChannelPtr realChannel = (IsInternalGroup()) ? GetByClient(channel.UniqueID(), channel.ClientID()) : g_PVRChannelGroups->GetGroupAll(m_bRadio)->GetByClient(channel.UniqueID(), channel.ClientID()); if (realChannel) { PVRChannelGroupMember newMember = { realChannel, (unsigned int)iChannelNumber }; m_members.push_back(newMember); m_bChanged = true; SortAndRenumber(); // TODO notify observers bReturn = true; } } return bReturn; } bool CPVRChannelGroup::IsGroupMember(const CPVRChannel &channel) const { bool bReturn(false); CSingleLock lock(m_critSection); for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++) { if (channel == *m_members.at(iChannelPtr).channel) { bReturn = true; break; } } return bReturn; } bool CPVRChannelGroup::IsGroupMember(int iChannelId) const { bool bReturn(false); CSingleLock lock(m_critSection); for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++) { if (iChannelId == m_members.at(iChannelPtr).channel->ChannelID()) { bReturn = true; break; } } return bReturn; } bool CPVRChannelGroup::SetGroupName(const CStdString &strGroupName, bool bSaveInDb /* = false */) { bool bReturn(false); CSingleLock lock(m_critSection); if (m_strGroupName != strGroupName) { /* update the name */ m_strGroupName = strGroupName; m_bChanged = true; // SetChanged(); /* persist the changes */ if (bSaveInDb) Persist(); bReturn = true; } return bReturn; } bool CPVRChannelGroup::Persist(void) { bool bReturn(true); CSingleLock lock(m_critSection); if (!HasChanges()) return bReturn; if (CPVRDatabase *database = GetPVRDatabase()) { CLog::Log(LOGDEBUG, "CPVRChannelGroup - %s - persisting channel group '%s' with %d channels", __FUNCTION__, GroupName().c_str(), (int) m_members.size()); m_bChanged = false; lock.Leave(); bReturn = database->Persist(*this); } else { bReturn = false; } return bReturn; } bool CPVRChannelGroup::Renumber(void) { bool bReturn(false); unsigned int iChannelNumber(0); bool bUseBackendChannelNumbers(CSettings::Get().GetBool("pvrmanager.usebackendchannelnumbers") && g_PVRClients->EnabledClientAmount() == 1); if (PreventSortAndRenumber()) return true; CSingleLock lock(m_critSection); for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++) { unsigned int iCurrentChannelNumber; if (m_members.at(iChannelPtr).channel->IsHidden()) iCurrentChannelNumber = 0; else if (bUseBackendChannelNumbers) iCurrentChannelNumber = m_members.at(iChannelPtr).channel->ClientChannelNumber(); else iCurrentChannelNumber = ++iChannelNumber; if (m_members.at(iChannelPtr).iChannelNumber != iCurrentChannelNumber) { bReturn = true; m_bChanged = true; } m_members.at(iChannelPtr).iChannelNumber = iCurrentChannelNumber; } SortByChannelNumber(); ResetChannelNumberCache(); return bReturn; } void CPVRChannelGroup::ResetChannelNumberCache(void) { CSingleLock lock(m_critSection); if (!m_bSelectedGroup) return; /* reset the channel number cache */ if (!IsInternalGroup()) g_PVRChannelGroups->GetGroupAll(m_bRadio)->ResetChannelNumbers(); /* set all channel numbers on members of this group */ for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++) m_members.at(iChannelPtr).channel->SetCachedChannelNumber(m_members.at(iChannelPtr).iChannelNumber); } bool CPVRChannelGroup::HasChangedChannels(void) const { bool bReturn(false); CSingleLock lock(m_critSection); for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++) { if (m_members.at(iChannelPtr).channel->IsChanged()) { bReturn = true; break; } } return bReturn; } bool CPVRChannelGroup::HasNewChannels(void) const { bool bReturn(false); CSingleLock lock(m_critSection); for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++) { if (m_members.at(iChannelPtr).channel->ChannelID() <= 0) { bReturn = true; break; } } return bReturn; } bool CPVRChannelGroup::HasChanges(void) const { CSingleLock lock(m_critSection); return m_bChanged || HasNewChannels() || HasChangedChannels(); } void CPVRChannelGroup::ResetChannelNumbers(void) { CSingleLock lock(m_critSection); for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++) m_members.at(iChannelPtr).channel->SetCachedChannelNumber(0); } void CPVRChannelGroup::OnSettingChanged(const CSetting *setting) { if (setting == NULL) return; /* TODO: while pvr manager is starting up do accept setting changes. */ if(!g_PVRManager.IsStarted()) { CLog::Log(LOGWARNING, "CPVRChannelGroup setting change ignored while PVRManager is starting\n"); return; } const std::string &settingId = setting->GetId(); if (settingId == "pvrmanager.backendchannelorder" || settingId == "pvrmanager.usebackendchannelnumbers") { CSingleLock lock(m_critSection); bool bUsingBackendChannelOrder = CSettings::Get().GetBool("pvrmanager.backendchannelorder"); bool bUsingBackendChannelNumbers = CSettings::Get().GetBool("pvrmanager.usebackendchannelnumbers"); bool bChannelNumbersChanged = m_bUsingBackendChannelNumbers != bUsingBackendChannelNumbers; bool bChannelOrderChanged = m_bUsingBackendChannelOrder != bUsingBackendChannelOrder; m_bUsingBackendChannelOrder = bUsingBackendChannelOrder; m_bUsingBackendChannelNumbers = bUsingBackendChannelNumbers; lock.Leave(); /* check whether this channel group has to be renumbered */ if (bChannelOrderChanged || bChannelNumbersChanged) { CLog::Log(LOGDEBUG, "CPVRChannelGroup - %s - renumbering group '%s' to use the backend channel order and/or numbers", __FUNCTION__, m_strGroupName.c_str()); SortAndRenumber(); Persist(); } } } bool CPVRPersistGroupJob::DoWork(void) { return m_group->Persist(); } int CPVRChannelGroup::GetEPGSearch(CFileItemList &results, const EpgSearchFilter &filter) { int iInitialSize = results.Size(); /* get filtered results from all tables */ g_EpgContainer.GetEPGSearch(results, filter); /* remove duplicate entries */ if (filter.m_bPreventRepeats) EpgSearchFilter::RemoveDuplicates(results); /* filter recordings */ if (filter.m_bIgnorePresentRecordings) EpgSearchFilter::FilterRecordings(results); /* filter timers */ if (filter.m_bIgnorePresentTimers) EpgSearchFilter::FilterTimers(results); return results.Size() - iInitialSize; } int CPVRChannelGroup::GetEPGNow(CFileItemList &results) { int iInitialSize = results.Size(); CSingleLock lock(m_critSection); for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++) { CPVRChannelPtr channel = m_members.at(iChannelPtr).channel; CEpg *epg = channel->GetEPG(); if (!epg || !epg->HasValidEntries() || m_members.at(iChannelPtr).channel->IsHidden()) continue; CEpgInfoTag epgNow; if (!epg->InfoTagNow(epgNow)) continue; CFileItemPtr entry(new CFileItem(epgNow)); entry->SetLabel2(epgNow.StartAsLocalTime().GetAsLocalizedTime(StringUtils::EmptyString, false)); entry->SetPath(channel->ChannelName()); entry->SetArt("thumb", channel->IconPath()); results.Add(entry); } return results.Size() - iInitialSize; } int CPVRChannelGroup::GetEPGNext(CFileItemList &results) { int iInitialSize = results.Size(); CSingleLock lock(m_critSection); for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++) { CPVRChannelPtr channel = m_members.at(iChannelPtr).channel; CEpg *epg = channel->GetEPG(); if (!epg || !epg->HasValidEntries() || m_members.at(iChannelPtr).channel->IsHidden()) continue; CEpgInfoTag epgNow; if (!epg->InfoTagNext(epgNow)) continue; CFileItemPtr entry(new CFileItem(epgNow)); entry->SetLabel2(epgNow.StartAsLocalTime().GetAsLocalizedTime(StringUtils::EmptyString, false)); entry->SetPath(channel->ChannelName()); entry->SetArt("thumb", channel->IconPath()); results.Add(entry); } return results.Size() - iInitialSize; } int CPVRChannelGroup::GetEPGAll(CFileItemList &results) { int iInitialSize = results.Size(); CSingleLock lock(m_critSection); for (unsigned int iChannelPtr = 0; iChannelPtr < m_members.size(); iChannelPtr++) { if (m_members.at(iChannelPtr).channel && !m_members.at(iChannelPtr).channel->IsHidden()) { CEpg* epg = m_members.at(iChannelPtr).channel->GetEPG(); if (epg) { // XXX channel pointers aren't set in some occasions. this works around the issue, but is not very nice epg->SetChannel(m_members.at(iChannelPtr).channel); epg->Get(results); } } } return results.Size() - iInitialSize; } CDateTime CPVRChannelGroup::GetEPGDate(EpgDateType epgDateType) const { CDateTime date; CSingleLock lock(m_critSection); for (std::vector<PVRChannelGroupMember>::const_iterator it = m_members.begin(); it != m_members.end(); it++) { if (it->channel && !it->channel->IsHidden()) { CEpg* epg = it->channel->GetEPG(); if (epg) { CDateTime epgDate; switch (epgDateType) { case EPG_FIRST_DATE: epgDate = epg->GetFirstDate(); if (epgDate.IsValid() && (!date.IsValid() || epgDate < date)) date = epgDate; break; case EPG_LAST_DATE: epgDate = epg->GetLastDate(); if (epgDate.IsValid() && (!date.IsValid() || epgDate > date)) date = epgDate; break; } } } } return date; } CDateTime CPVRChannelGroup::GetFirstEPGDate(void) const { return GetEPGDate(EPG_FIRST_DATE); } CDateTime CPVRChannelGroup::GetLastEPGDate(void) const { return GetEPGDate(EPG_LAST_DATE); } int CPVRChannelGroup::Size(void) const { return m_members.size(); } int CPVRChannelGroup::GroupID(void) const { return m_iGroupId; } void CPVRChannelGroup::SetGroupID(int iGroupId) { if (iGroupId >= 0) m_iGroupId = iGroupId; } void CPVRChannelGroup::SetGroupType(int iGroupType) { m_iGroupType = iGroupType; } int CPVRChannelGroup::GroupType(void) const { return m_iGroupType; } CStdString CPVRChannelGroup::GroupName(void) const { CSingleLock lock(m_critSection); CStdString strReturn(m_strGroupName); return strReturn; } bool CPVRChannelGroup::PreventSortAndRenumber(void) const { CSingleLock lock(m_critSection); return m_bPreventSortAndRenumber; } void CPVRChannelGroup::SetPreventSortAndRenumber(bool bPreventSortAndRenumber /* = true */) { CSingleLock lock(m_critSection); m_bPreventSortAndRenumber = bPreventSortAndRenumber; } bool CPVRChannelGroup::UpdateChannel(const CFileItem &item, bool bHidden, bool bVirtual, bool bEPGEnabled, bool bParentalLocked, int iEPGSource, int iChannelNumber, const CStdString &strChannelName, const CStdString &strIconPath, const CStdString &strStreamURL) { if (!item.HasPVRChannelInfoTag()) return false; CSingleLock lock(m_critSection); /* get the real channel from the group */ CPVRChannelPtr channel = GetByUniqueID(item.GetPVRChannelInfoTag()->UniqueID()); if (!channel) return false; channel->SetChannelName(strChannelName); channel->SetHidden(bHidden); channel->SetLocked(bParentalLocked); channel->SetIconPath(strIconPath); if (bVirtual) channel->SetStreamURL(strStreamURL); if (iEPGSource == 0) channel->SetEPGScraper("client"); // TODO add other scrapers channel->SetEPGEnabled(bEPGEnabled); /* set new values in the channel tag */ if (bHidden) { SortByChannelNumber(); // or previous changes will be overwritten RemoveFromGroup(*channel); } else { SetChannelNumber(*channel, iChannelNumber); } return true; } bool CPVRChannelGroup::ToggleChannelLocked(const CFileItem &item) { if (!item.HasPVRChannelInfoTag()) return false; CSingleLock lock(m_critSection); /* get the real channel from the group */ CPVRChannelPtr channel = GetByUniqueID(item.GetPVRChannelInfoTag()->UniqueID()); if (!channel) return false; channel->SetLocked(!channel->IsLocked()); return true; } void CPVRChannelGroup::SetSelectedGroup(bool bSetTo) { CSingleLock lock(m_critSection); m_bSelectedGroup = bSetTo; } bool CPVRChannelGroup::IsSelectedGroup(void) const { CSingleLock lock(m_critSection); return m_bSelectedGroup; } bool CPVRChannelGroup::CreateChannelEpgs(bool bForce /* = false */) { /* used only by internal channel groups */ return true; }
gripped/xbmc
xbmc/pvr/channels/PVRChannelGroup.cpp
C++
gpl-2.0
35,348
/* * quickstampmanager.cpp * Copyright 2010-2011, Stefan Beller <stefanbeller@googlemail.com> * * This file is part of Tiled. * * 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 "quickstampmanager.h" #include "abstracttool.h" #include "bucketfilltool.h" #include "mapdocument.h" #include "map.h" #include "stampbrush.h" #include "tilelayer.h" #include "tileselectiontool.h" #include "tileset.h" #include "tilesetmanager.h" #include "toolmanager.h" using namespace Tiled; using namespace Tiled::Internal; QuickStampManager *QuickStampManager::mInstance = 0; QuickStampManager *QuickStampManager::instance() { if (!mInstance) mInstance = new QuickStampManager; return mInstance; } void QuickStampManager::deleteInstance() { delete mInstance; mInstance = 0; } QuickStampManager::QuickStampManager() : mMapDocument(0) { mQuickStamps.resize(keys().length()); } QuickStampManager::~QuickStampManager() { cleanQuickStamps(); } void QuickStampManager::saveQuickStamp(int index) { if (!mMapDocument) return; const Map *map = mMapDocument->map(); // The source of the saved stamp depends on which tool is selected AbstractTool *selectedTool = ToolManager::instance()->selectedTool(); TileLayer *copy = 0; if (dynamic_cast<StampBrush*>(selectedTool)) { TileLayer *stamp = (static_cast<StampBrush*>(selectedTool))->stamp(); if (!stamp) return; copy = static_cast<TileLayer*>(stamp->clone()); } else if (dynamic_cast<TileSelectionTool*>(selectedTool)) { const TileLayer *tileLayer = dynamic_cast<TileLayer*>(mMapDocument->currentLayer()); if (!tileLayer) return; const QRegion &selection = mMapDocument->tileSelection(); if (selection.isEmpty()) return; copy = tileLayer->copy(selection.translated(-tileLayer->x(), -tileLayer->y())); } else if (dynamic_cast<BucketFillTool*>(selectedTool)) { TileLayer *stamp = (static_cast<BucketFillTool*>(selectedTool))->stamp(); if (!stamp) return; copy = static_cast<TileLayer*>(stamp->clone()); } if (!copy) return; Map *copyMap = new Map(map->orientation(), copy->width(), copy->height(), map->tileWidth(), map->tileHeight()); copyMap->addLayer(copy); // Add tileset references to map and tileset manager TilesetManager *tilesetManager = TilesetManager::instance(); foreach (Tileset *tileset, copy->usedTilesets()) { copyMap->addTileset(tileset); tilesetManager->addReference(tileset); } eraseQuickStamp(index); mQuickStamps.replace(index, copyMap); } void QuickStampManager::cleanQuickStamps() { for (int i = 0; i < mQuickStamps.size(); i++) eraseQuickStamp(i); } void QuickStampManager::eraseQuickStamp(int index) { if (Map *quickStamp = mQuickStamps.at(index)) { // Decrease reference to tilesets TilesetManager *tilesetManager = TilesetManager::instance(); tilesetManager->removeReferences(quickStamp->tilesets()); delete quickStamp; } } void QuickStampManager::selectQuickStamp(int index) { if (!mMapDocument) return; if (Map *stampMap = mQuickStamps.at(index)) { mMapDocument->unifyTilesets(stampMap); emit setStampBrush(static_cast<TileLayer*>(stampMap->layerAt(0))); } } void QuickStampManager::setMapDocument(MapDocument *mapDocument) { mMapDocument = mapDocument; }
ppiecuch/tiled
src/tiled/quickstampmanager.cpp
C++
gpl-2.0
4,231
<?php // PukiWiki - Yet another WikiWikiWeb clone // $Id: lastmod.inc.php,v 1.3 2005/01/31 13:03:41 henoheno Exp $ // // Lastmod plugin - Show lastmodifled date of the page // Originally written by Reimy, 2003 function plugin_lastmod_inline() { global $vars, $WikiName, $BracketName; $args = func_get_args(); if (!isset($vars['page'])) return false; $page = $args[0]; if ($page == ''){ $page = $vars['page']; // Default: page itself } else { if (preg_match("/^($WikiName|$BracketName)$/", strip_bracket($page))) { $page = get_fullname(strip_bracket($page), $vars['page']); } else { return FALSE; } } if (! is_page($page)) return FALSE; return format_date(get_filetime($page)); } /* End of file lastmod.inc.php */ /* Location: ./wiki-common/plugin/lastmod.inc.php */
mikoim/pukiwiki_adv
wiki-common/plugin/lastmod.inc.php
PHP
gpl-2.0
796
/****************************************************************************** * * Copyright (C) 2009-2015 by Joenio Costa. * * Permission to use, copy, modify, and distribute this software and its * documentation under the terms of the GNU General Public License is hereby * granted. No representations are made about the suitability of this software * for any purpose. It is provided "as is" without express or implied warranty. * See the GNU General Public License for more details. * * Documents produced by Doxygen are derivative works derived from the * input used in their production; they are not affected by this license. * */ /** @file * @brief Code parse based on doxyapp by Dimitri van Heesch * */ #include <stdlib.h> #include <unistd.h> #include "doxygen.h" #include "outputgen.h" #include "parserintf.h" #include "classlist.h" #include "config.h" #include "filedef.h" #include "util.h" #include "filename.h" #include "arguments.h" #include "memberlist.h" #include "types.h" #include <string> #include <cstdlib> #include <sstream> #include <map> class Doxyparse : public CodeOutputInterface { public: Doxyparse(FileDef *fd) : m_fd(fd) {} ~Doxyparse() {} // these are just null functions, they can be used to produce a syntax highlighted // and cross-linked version of the source code, but who needs that anyway ;-) void codify(const char *) {} void writeCodeLink(const char *,const char *,const char *,const char *,const char *) {} void startCodeLine() {} void endCodeLine() {} void startCodeAnchor(const char *) {} void endCodeAnchor() {} void startFontClass(const char *) {} void endFontClass() {} void writeCodeAnchor(const char *) {} void writeLineNumber(const char *,const char *,const char *,int) {} virtual void writeTooltip(const char *,const DocLinkInfo &, const char *,const char *,const SourceLinkInfo &, const SourceLinkInfo &) {} void startCodeLine(bool) {} void setCurrentDoc(Definition *,const char *,bool) {} void addWord(const char *,bool) {} void linkableSymbol(int l, const char *sym, Definition *symDef, Definition *context) { if (!symDef) { // in this case we have a local or external symbol // TODO record use of external symbols // TODO must have a way to differentiate external symbols from local variables } } private: FileDef *m_fd; }; static bool is_c_code = true; static std::map<std::string, bool> modules; static std::string current_module; static void findXRefSymbols(FileDef *fd) { // get the interface to a parser that matches the file extension ParserInterface *pIntf=Doxygen::parserManager->getParser(fd->getDefFileExtension()); // get the programming language from the file name SrcLangExt lang = getLanguageFromFileName(fd->name()); // reset the parsers state pIntf->resetCodeParserState(); // create a new backend object Doxyparse *parse = new Doxyparse(fd); // parse the source code pIntf->parseCode(*parse, 0, fileToString(fd->absFilePath()), lang, FALSE, 0, fd); // dismiss the object. delete parse; } static bool ignoreStaticExternalCall(MemberDef *context, MemberDef *md) { if (md->isStatic()) { if(md->getFileDef()) { if(md->getFileDef()->getFileBase() == context->getFileDef()->getFileBase()) // TODO ignore prefix of file return false; else return true; } else { return false; } } else { return false; } } static void printFile(std::string file) { printf("%s:\n", file.c_str()); } static void printModule(std::string module) { current_module = module; printf(" %s:\n", module.c_str()); } static void printClassInformation(std::string information) { printf(" informations: %s\n", information.c_str()); } static void printInheritance(std::string base_class) { printf(" inherits: %s\n", base_class.c_str()); } static void printDefines() { if (! modules[current_module]) { printf(" defines:\n"); } modules[current_module] = true; } static void printDefinition(std::string type, std::string signature, int line) { printf(" - %s:\n", signature.c_str()); printf(" type: %s\n", type.c_str()); printf(" line: %d\n", line); } static void printProtection(std::string protection) { printf(" protection: %s\n", protection.c_str()); } static void printNumberOfLines(int lines) { printf(" lines_of_code: %d\n", lines); } static void printNumberOfArguments(int arguments) { printf(" parameters: %d\n", arguments); } static void printUses() { printf(" uses:\n"); } static void printReferenceTo(std::string type, std::string signature, std::string defined_in) { printf(" - %s:\n", signature.c_str()); printf(" type: %s\n", type.c_str()); printf(" defined_in: %s\n", defined_in.c_str()); } static int isPartOfCStruct(MemberDef * md) { return is_c_code && md->getClassDef() != NULL; } std::string functionSignature(MemberDef* md) { std::string signature = md->name().data(); if(md->isFunction()){ ArgumentList *argList = md->argumentList(); ArgumentListIterator iterator(*argList); signature += "("; Argument * argument = iterator.toFirst(); if(argument != NULL) { signature += argument->type.data(); for(++iterator; (argument = iterator.current()) ;++iterator){ signature += std::string(",") + argument->type.data(); } } signature += ")"; } return signature; } static void referenceTo(MemberDef* md) { std::string type = md->memberTypeName().data(); std::string defined_in = ""; std::string signature = ""; if (isPartOfCStruct(md)) { signature = md->getClassDef()->name().data() + std::string("::") + functionSignature(md); defined_in = md->getClassDef()->getFileDef()->getFileBase().data(); } else { signature = functionSignature(md); if (md->getClassDef()) { defined_in = md->getClassDef()->name().data(); } else if (md->getFileDef()) { defined_in = md->getFileDef()->getFileBase().data(); } } printReferenceTo(type, signature, defined_in); } void cModule(ClassDef* cd) { MemberList* ml = cd->getMemberList(MemberListType_variableMembers); if (ml) { MemberListIterator mli(*ml); MemberDef* md; for (mli.toFirst(); (md=mli.current()); ++mli) { printDefinition("variable", cd->name().data() + std::string("::") + md->name().data(), md->getDefLine()); if (md->protection() == Public) { printProtection("public"); } } } } void functionInformation(MemberDef* md) { int size = md->getEndBodyLine() - md->getStartBodyLine() + 1; printNumberOfLines(size); ArgumentList *argList = md->argumentList(); printNumberOfArguments(argList->count()); MemberSDict *defDict = md->getReferencesMembers(); if (defDict) { MemberSDict::Iterator msdi(*defDict); MemberDef *rmd; printUses(); for (msdi.toFirst(); (rmd=msdi.current()); ++msdi) { if (rmd->definitionType() == Definition::TypeMember && !ignoreStaticExternalCall(md, rmd)) { referenceTo(rmd); } } } } static void lookupSymbol(Definition *d) { if (d->definitionType() == Definition::TypeMember) { MemberDef *md = (MemberDef *)d; std::string type = md->memberTypeName().data(); std::string signature = functionSignature(md); printDefinition(type, signature, md->getDefLine()); if (md->protection() == Public) { printProtection("protection public"); } if (md->isFunction()) { functionInformation(md); } } } void listMembers(MemberList *ml) { if (ml) { MemberListIterator mli(*ml); MemberDef *md; printDefines(); for (mli.toFirst(); (md=mli.current()); ++mli) { lookupSymbol((Definition*) md); } } } void listAllMembers(ClassDef* cd) { // methods listMembers(cd->getMemberList(MemberListType_functionMembers)); // constructors listMembers(cd->getMemberList(MemberListType_constructors)); // attributes listMembers(cd->getMemberList(MemberListType_variableMembers)); } static void classInformation(ClassDef* cd) { if (is_c_code) { cModule(cd); } else { printModule(cd->name().data()); BaseClassList* baseClasses = cd->baseClasses(); if (baseClasses) { BaseClassListIterator bci(*baseClasses); BaseClassDef* bcd; for (bci.toFirst(); (bcd = bci.current()); ++bci) { printInheritance(bcd->classDef->name().data()); } } if(cd->isAbstract()) { printClassInformation("abstract class"); } listAllMembers(cd); } } static bool checkLanguage(std::string& filename, std::string extension) { if (filename.find(extension, filename.size() - extension.size()) != std::string::npos) { return true; } else { return false; } } /* Detects the programming language of the project. Actually, we only care * about whether it is a C project or not. */ static void detectProgrammingLanguage(FileNameListIterator& fnli) { FileName* fn; for (fnli.toFirst(); (fn=fnli.current()); ++fnli) { std::string filename = fn->fileName(); if ( checkLanguage(filename, ".cc") || checkLanguage(filename, ".cxx") || checkLanguage(filename, ".cpp") || checkLanguage(filename, ".java") ) { is_c_code = false; } } } static void listSymbols() { // iterate over the input files FileNameListIterator fnli(*Doxygen::inputNameList); FileName *fn; detectProgrammingLanguage(fnli); // for each file for (fnli.toFirst(); (fn=fnli.current()); ++fnli) { FileNameIterator fni(*fn); FileDef *fd; for (; (fd=fni.current()); ++fni) { printFile(fd->absFilePath().data()); MemberList *ml = fd->getMemberList(MemberListType_allMembersList); if (ml && ml->count() > 0) { printModule(fd->getFileBase().data()); listMembers(ml); } ClassSDict *classes = fd->getClassSDict(); if (classes) { ClassSDict::Iterator cli(*classes); ClassDef *cd; for (cli.toFirst(); (cd = cli.current()); ++cli) { classInformation(cd); } } } } // TODO print external symbols referenced } int main(int argc,char **argv) { if (argc < 2) { printf("Usage: %s [source_file | source_dir]\n",argv[0]); exit(1); } // initialize data structures initDoxygen(); // setup the non-default configuration options // we need a place to put intermediate files std::ostringstream tmpdir; tmpdir << "/tmp/doxyparse-" << getpid(); Config_getString("OUTPUT_DIRECTORY")= tmpdir.str().c_str(); // enable HTML (fake) output to omit warning about missing output format Config_getBool("GENERATE_HTML")=TRUE; // disable latex output Config_getBool("GENERATE_LATEX")=FALSE; // be quiet Config_getBool("QUIET")=TRUE; // turn off warnings Config_getBool("WARNINGS")=FALSE; Config_getBool("WARN_IF_UNDOCUMENTED")=FALSE; Config_getBool("WARN_IF_DOC_ERROR")=FALSE; // Extract as much as possible Config_getBool("EXTRACT_ALL")=TRUE; Config_getBool("EXTRACT_STATIC")=TRUE; Config_getBool("EXTRACT_PRIVATE")=TRUE; Config_getBool("EXTRACT_LOCAL_METHODS")=TRUE; // Extract source browse information, needed // to make doxygen gather the cross reference info Config_getBool("SOURCE_BROWSER")=TRUE; // find functions call between modules Config_getBool("CALL_GRAPH")=TRUE; // loop recursive over input files Config_getBool("RECURSIVE")=TRUE; // set the input Config_getList("INPUT").clear(); for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-") == 0) { char filename[1024]; while (1) { scanf("%s[^\n]", filename); if (feof(stdin)) { break; } Config_getList("INPUT").append(filename); } } else { Config_getList("INPUT").append(argv[i]); } } if (Config_getList("INPUT").isEmpty()) { exit(0); } // check and finalize the configuration checkConfiguration(); adjustConfiguration(); // parse the files parseInput(); // iterate over the input files FileNameListIterator fnli(*Doxygen::inputNameList); FileName *fn; // for each file with a certain name for (fnli.toFirst();(fn=fnli.current());++fnli) { FileNameIterator fni(*fn); FileDef *fd; // for each file definition for (;(fd=fni.current());++fni) { // get the references (linked and unlinked) found in this file findXRefSymbols(fd); } } // remove temporary files if (!Doxygen::objDBFileName.isEmpty()) unlink(Doxygen::objDBFileName); if (!Doxygen::entryDBFileName.isEmpty()) unlink(Doxygen::entryDBFileName); // clean up after us rmdir(Config_getString("OUTPUT_DIRECTORY")); listSymbols(); std::string cleanup_command = "rm -rf "; cleanup_command += tmpdir.str(); system(cleanup_command.c_str()); exit(0); }
artur-kink/doxygen
addon/doxyparse/doxyparse.cpp
C++
gpl-2.0
13,038
""" Contains functionality common across all repository-related managers. = Working Directories = Working directories are as staging or temporary file storage by importers and distributors. Each directory is unique to the repository and plugin combination. The directory structure for plugin working directories is as follows: <pulp_storage>/working/<repo_id>/[importers|distributors]/<plugin_type_id> For example, for importer "foo" and repository "bar": /var/lib/pulp/working/bar/importers/foo The rationale is to simplify cleanup on repository delete; the repository's working directory is simply deleted. """ import os from pulp.common import dateutils from pulp.server import config as pulp_config from pulp.plugins.model import Repository, RelatedRepository, RepositoryGroup, \ RelatedRepositoryGroup def _ensure_tz_specified(time_stamp): """ Check a datetime that came from the database to ensure it has a timezone specified in UTC Mongo doesn't include the TZ info so if no TZ is set this assumes UTC. :param time_stamp: a datetime object to ensure has UTC tzinfo specified :type time_stamp: datetime.datetime :return: The time_stamp with a timezone specified :rtype: datetime.datetime """ if time_stamp: time_stamp = dateutils.to_utc_datetime(time_stamp, no_tz_equals_local_tz=False) return time_stamp def to_transfer_repo(repo_data): """ Converts the given database representation of a repository into a plugin repository transfer object, including any other fields that need to be included. @param repo_data: database representation of a repository @type repo_data: dict @return: transfer object used in many plugin API calls @rtype: pulp.plugins.model.Repository} """ r = Repository(repo_data['id'], repo_data['display_name'], repo_data['description'], repo_data['notes'], content_unit_counts=repo_data['content_unit_counts'], last_unit_added=_ensure_tz_specified(repo_data.get('last_unit_added')), last_unit_removed=_ensure_tz_specified(repo_data.get('last_unit_removed'))) return r def to_related_repo(repo_data, configs): """ Converts the given database representation of a repository into a plugin's representation of a related repository. The list of configurations for the repository's plugins will be included in the returned type. @param repo_data: database representation of a repository @type repo_data: dict @param configs: list of configurations for all relevant plugins on the repo @type configs: list @return: transfer object used in many plugin API calls @rtype: pulp.plugins.model.RelatedRepository """ r = RelatedRepository(repo_data['id'], configs, repo_data['display_name'], repo_data['description'], repo_data['notes']) return r def repository_working_dir(repo_id, mkdir=True): """ Determines the repository's working directory. Individual plugin working directories will be placed under this. If the mkdir argument is set to true, the directory will be created as part of this call. See the module-level docstrings for more information on the directory structure. @param mkdir: if true, this call will create the directory; otherwise the full path will just be generated @type mkdir: bool @return: full path on disk @rtype: str """ working_dir = os.path.join(_repo_working_dir(), repo_id) if mkdir and not os.path.exists(working_dir): os.makedirs(working_dir) return working_dir def importer_working_dir(importer_type_id, repo_id, mkdir=True): """ Determines the working directory for an importer to use for a repository. If the mkdir argument is set to true, the directory will be created as part of this call. See the module-level docstrings for more information on the directory structure. @param mkdir: if true, this call will create the directory; otherwise the full path will just be generated @type mkdir: bool @return: full path on disk to the directory the importer can use for the given repository @rtype: str """ repo_working_dir = repository_working_dir(repo_id, mkdir) working_dir = os.path.join(repo_working_dir, 'importers', importer_type_id) if mkdir and not os.path.exists(working_dir): os.makedirs(working_dir) return working_dir def distributor_working_dir(distributor_type_id, repo_id, mkdir=True): """ Determines the working directory for a distributor to use for a repository. If the mkdir argument is set to true, the directory will be created as part of this call. See the module-level docstrings for more information on the directory structure. @param mkdir: if true, this call will create the directory; otherwise the full path will just be generated @type mkdir: bool @return: full path on disk to the directory the distributor can use for the given repository @rtype: str """ repo_working_dir = repository_working_dir(repo_id, mkdir) working_dir = os.path.join(repo_working_dir, 'distributors', distributor_type_id) if mkdir and not os.path.exists(working_dir): os.makedirs(working_dir) return working_dir def to_transfer_repo_group(group_data): """ Converts the given database representation of a repository group into a plugin transfer object. @param group_data: database representation of the group @type group_data: dict @return: transfer object used in plugin calls @rtype: pulp.plugins.model.RepositoryGroup """ g = RepositoryGroup(group_data['id'], group_data['display_name'], group_data['description'], group_data['notes'], group_data['repo_ids']) return g def to_related_repo_group(group_data, configs): """ Converts the given database representation of a repository group into a plugin transfer object. The list of configurations for the requested group plugins are included in the returned type. @param group_data: database representation of the group @type group_data: dict @param configs: list of plugin configurations to include @type configs: list @return: transfer object used in plugin calls @rtype: pulp.plugins.model.RelatedRepositoryGroup """ g = RelatedRepositoryGroup(group_data['id'], configs, group_data['display_name'], group_data['description'], group_data['notes']) return g def repo_group_working_dir(group_id, mkdir=True): """ Determines the repo group's working directory. Individual plugin working directories will be placed under this. If the mkdir argument is set to true, the directory will be created as part of this call. @param group_id: identifies the repo group @type group_id: str @param mkdir: if true, the call will create the directory; otherwise the full path will just be generated and returned @type mkdir: bool @return: full path on disk @rtype: str """ working_dir = os.path.join(_repo_group_working_dir(), group_id) if mkdir and not os.path.exists(working_dir): os.makedirs(working_dir) return working_dir def group_importer_working_dir(importer_type_id, group_id, mkdir=True): """ Determines the working directory for an importer to use for a repository group. If the mkdir argument is set to true, the directory will be created as part of this call. @param mkdir: if true, the call will create the directory; otherwise the full path will just be generated and returned @type mkdir: bool @return: full path on disk @rtype: str """ group_working_dir = repo_group_working_dir(group_id, mkdir) working_dir = os.path.join(group_working_dir, 'importers', importer_type_id) if mkdir and not os.path.exists(working_dir): os.makedirs(working_dir) return working_dir def group_distributor_working_dir(distributor_type_id, group_id, mkdir=True): """ Determines the working directory for an importer to use for a repository group. If the mkdir argument is set to true, the directory will be created as part of this call. @param mkdir: if true, the call will create the directory; otherwise the full path will just be generated and returned @type mkdir: bool @return: full path on disk @rtype: str """ group_working_dir = repo_group_working_dir(group_id, mkdir) working_dir = os.path.join(group_working_dir, 'distributors', distributor_type_id) if mkdir and not os.path.exists(working_dir): os.makedirs(working_dir) return working_dir def _working_dir_root(): storage_dir = pulp_config.config.get('server', 'storage_dir') dir_root = os.path.join(storage_dir, 'working') return dir_root def _repo_working_dir(): dir = os.path.join(_working_dir_root(), 'repos') return dir def _repo_group_working_dir(): dir = os.path.join(_working_dir_root(), 'repo_groups') return dir
beav/pulp
server/pulp/server/managers/repo/_common.py
Python
gpl-2.0
9,312
<?php /** * @version $Id: rokcomments.php 18916 2014-02-20 21:04:02Z rhuk $ * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2014 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only */ // no direct access defined('_JEXEC') or die('Restricted access'); //$mainframe->registerEvent('onPrepareContent', 'plgContentRokComments'); class plgContentRokComments extends JPlugin { public $domain; public $subdomain; public $postid; public $url; public $path; public $devmode; public $commenticon; public $account; public $width; public $postcount; public $host; public $commentpage = false; /** * Page break plugin * * <b>Usage:</b> * <code>{rokcomments}</code> * @param $context * @param $row * @param $params * @param int $page * * @return bool */ function onContentAfterTitle($context, &$row, &$params, $page = 0) { $option = strtolower(JFactory::getApplication()->input->get('option')); $view = JFactory::getApplication()->input->get('view'); $itemid = JFactory::getApplication()->input->getInt('Itemid'); // return is not active if(JPluginHelper::isEnabled('content','rokcomments')==false || $row == null) return; // only works for content if (!preg_match('/^com_content/', $context)) return; // Get Plugin info $user = JFactory::getUser(); $plgname = "rokcomments"; $plugin = JPluginHelper::getPlugin('content', $plgname); $document = JFactory::getDocument(); $pluginParams = new JRegistry($plugin->params); $r_id = $row->id; $r_catid = $row->catid; $r_slug = $row->slug; $r_alias = $row->alias; if ($view == 'article') $this->commentpage = true; if (!$this->commentpage) { $text = $row->introtext; } else { $text = $row->text; } $regex = '#{rokcomments(-count)?}#s'; $option = JFactory::getApplication()->input->get('option'); $system = $pluginParams->get('system', 'intensedebate'); $method = $pluginParams->get('method', 'id'); $catids = $pluginParams->get('categories', ''); $menuids = $pluginParams->get('menus', ''); $tagmode = $pluginParams->get('tagmode', 0); $showcount = $pluginParams->get('showcount', 1); $fb_appid = $pluginParams->get('fb-appid', ''); $fb_moderatorid = $pluginParams->get('fb-modid', ''); $lf_siteid = $pluginParams->get('lf-siteid',''); //set vars $this->domain = $pluginParams->get('js-domain'); $this->subdomain = $pluginParams->get('d-subdomain'); $this->devmode = $pluginParams->get('d-devmode', 0); $this->account = $pluginParams->get('id-account'); $this->commenticon = " " . $pluginParams->get('showicon', 'rk-icon'); $this->width = $pluginParams->get('fb-width', '500'); $this->postcount = $pluginParams->get('fb-postcount',10); //setup appropriate accounts if ($system == 'facebook') $this->account = $fb_appid; if ($system == 'livefyre') { $this->account = $lf_siteid; $tagmode = 4; //liveryre seems to only like full URL for articleid } //add some css $document->addStyleSheet(JURI::base() . "plugins/content/rokcomments/css/rokcomments.css"); //url $baseurl = (!empty($_SERVER['HTTPS'])) ? "https://" . $_SERVER['HTTP_HOST'] : "http://" . $_SERVER['HTTP_HOST']; if ($_SERVER['SERVER_PORT'] != "80") $baseurl .= ":" . $_SERVER['SERVER_PORT']; $this->host = $_SERVER['HTTP_HOST']; $this->path = JRoute::_(ContentHelperRoute::getArticleRoute($r_slug, $r_catid)); $this->url = $baseurl . $this->path; // handle tag style switch ($tagmode) { case 1: $postid = $r_slug; break; case 2: $postid = $this->path; break; case 3: $postid = $r_id; break; case 4: $postid = $this->url; break; default: $postid = $r_alias; } //sepcial case for ID if ($system == "intensedebate") { $postid = str_replace(array("-", ":"), array("_", "_"), $postid); } $this->postid = $postid; // get array of category ids if (is_array($catids)) { $categories = $catids; } elseif ($catids == '') { $categories[] = $r_catid; } else { $categories[] = $catids; } $categories = $this->_getChildCategories($categories); // get array of menus ids if (is_array($menuids)) { $menus = $menuids; } elseif ($menuids == '') { $menus[] = $itemid; } else { $menus[] = $menuids; } // check to make sure we are where we should be if ($method == 'code') { if (!(strpos($text, '{rokcomments') !== false)) { $text = preg_replace($regex, '', $text); $this->_setContentText($row,$text); return; } } else { // remove rokcomments code if in there $text = preg_replace($regex, '', $text); if (!(in_array($r_catid, $categories) || in_array($itemid, $menus))) { $this->_setContentText($row,$text); return; } } // remove the count if both codes are visible - that makes no sense if (strpos($text,'{rokcomments}') !== false && strpos($text,'{rokcomments-count}') !== false) { $text = str_replace('{rokcomments-count}','',$text); } // check to make sure commentcount should be shown if (!$this->commentpage and $showcount == 0) return; if ($system == 'disqus') { // disqus if ($this->commentpage == false) { $output = "<div class=\"rk-commentcount{rk-icon}\"><a class=\"rokcomment-counter\" href=\"{post-url}#disqus_thread\" title=\"Comments\">Comments</a></div>\n"; if (!defined('ROKCOMMENT_COUNT')) { $headscript = ' <script type="text/javascript"> var disqus_shortname = "{subdomain}"; var disqus_developer = {devmode}; var disqus_identifier = "{post-id}"; var disqus_url = "{post-url}"; (function () { var s = document.createElement("script"); s.async = true; s.type = "text/javascript"; s.src = "http://" + disqus_shortname + ".disqus.com/count.js"; (document.getElementsByTagName("HEAD")[0] || document.getElementsByTagName("BODY")[0]).appendChild(s); }()); </script>'; $headscript = $this->_replaceText($headscript); $document->addCustomTag($headscript); define('ROKCOMMENT_COUNT', true); } } else { $output = ' <div id="disqus_thread"></div> <script type="text/javascript"> var disqus_shortname = "{subdomain}"; var disqus_developer = {devmode}; var disqus_identifier = "{post-id}"; var disqus_url = "{post-url}"; (function() { var dsq = document.createElement("script"); dsq.type = "text/javascript"; dsq.async = true; dsq.src = "http://" + disqus_shortname + ".disqus.com/embed.js"; (document.getElementsByTagName("head")[0] || document.getElementsByTagName("body")[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> <a href="http://disqus.com" class="dsq-brlink">blog comments powered by <span class="logo-disqus">Disqus</span></a>'; } } elseif ($system == 'jskit') { // js-kit if ($this->commentpage == false) { if (!defined('ROKCOMMENT_COUNT')) { $headscript = " <script type='text/javascript'> window.addEvent('domready', function(){ var jskitScript = document.createElement('script'); jskitScript.setAttribute('charset','utf-8'); jskitScript.setAttribute('type','text/javascript'); jskitScript.setAttribute('src','http://js-kit.com/for/{domain}/comments-count.js'); var b = document.getElementsByTagName('body')[0]; b.appendChild(jskitScript); }); </script>"; $headscript = $this->_replaceText($headscript); $document->addCustomTag($headscript); define('ROKCOMMENT_COUNT', 1); } $output = '<div class="rk-commentcount{rk-icon}"><a href="{post-path}">Comments (<span class="js-kit-comments-count" uniq="{post-path}">0</span>)</a></div>'; } else { $output = '<div style="margin-top:25px;" class="js-kit-comments" permalink="{post-url}" path=""></div><script src="http://js-kit.com/for/{domain}/comments.js"></script>'; } } elseif ($system == 'facebook') { // facebook comments if ($this->commentpage == false) { $output = '<iframe src="http://www.facebook.com/plugins/comments.php?href={post-url}&permalink=1" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:130px; height:16px;" allowTransparency="true"></iframe> '; } else { $headscript = ' <meta property="fb:admins" content="'.$fb_moderatorid.'"/> <meta property="fb:app_id" content="'.$this->account.'"/> '; $document->addCustomTag($headscript); $output = ' <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId={account}"; fjs.parentNode.insertBefore(js, fjs); }(document, "script", "facebook-jssdk"));</script> <div class="fb-comments" data-href="{post-url}" data-num-posts="{postcount}" data-width="{width}"></div>'; } } elseif ($system == 'livefyre') { // livefyre comments if ($this->commentpage == false) { if (!defined('ROKCOMMENT_COUNT')) { $headscript = ' <script type="text/javascript" src="http://zor.livefyre.com/wjs/v1.0/javascripts/CommentCount.js"></script>'; $document->addCustomTag($headscript); define('ROKCOMMENT_COUNT', 1); } $output = ' <div class="rk-commentcount{rk-icon}"> <span class="livefyre-commentcount" data-lf-site-id="{account}" data-lf-article-id="{post-id}">0 Comments </span> </div>'; } else { $output = " <!-- START: Livefyre Embed --> <div id='livefyre-comments'></div> <script type='text/javascript' src='http://zor.livefyre.com/wjs/v3.0/javascripts/livefyre.js'></script> <script type='text/javascript'> (function () { var articleId = '{post-id}'; fyre.conv.load({}, [{ el: 'livefyre-comments', network: 'livefyre.com', siteId: '{account}', articleId: articleId, signed: false, collectionMeta: { articleId: articleId, url: fyre.conv.load.makeCollectionUrl(), } }], function() {}); }()); </script> <!-- END: Livefyre Embed -->"; } } else { // intense debate if ($this->commentpage == false) { $output = ' <script type="text/javascript"> var idcomments_acct = "{account}";var idcomments_post_id = "{post-id}";var idcomments_post_url = "{post-url}"; </script> <div class="rk-commentcount{rk-icon}"> <script type="text/javascript" src="http://www.intensedebate.com/js/genericLinkWrapperV2.js"></script> </div>'; } else { $output = ' <script type="text/javascript"> var idcomments_acct = "{account}";var idcomments_post_id = "{post-id}";var idcomments_post_url = "{post-url}"; </script> <span id="IDCommentsPostTitle" style="display:none"></span> <script type="text/javascript" src="http://www.intensedebate.com/js/genericCommentWrapperV2.js"></script>'; } } $output = $this->_replaceText($output); if ($method == 'code') { $text = preg_replace($regex, $output, $text); } else { $text .= $output; } $this->_setContentText($row,$text); return; } protected function _replaceText($output) { $search = array('{subdomain}', '{post-id}', '{post-url}', '{post-path}', '{devmode}', '{rk-icon}', '{domain}', '{account}', '{width}', '{postcount}', '{host}'); $replace = array($this->subdomain, $this->postid, $this->url, $this->path, $this->devmode, $this->commenticon, $this->domain, $this->account, $this->width, $this->postcount, $this->host); $output = str_replace($search, $replace, $output); return $output; } protected function _setContentText(&$row,$text) { if (!$this->commentpage) { $row->introtext = $text; } else { $row->text = $text; } return; } protected function _getChildCategories($catids) { $app = JFactory::getApplication(); $appParams = $app->getParams(); $access = !JComponentHelper::getParams('com_content')->get('show_noauth'); // Get an instance of the generic categories model if(class_exists('JModelLegacy')){ $categories = JModelLegacy::getInstance('Categories', 'ContentModel', array('ignore_request' => true)); } else { $categories = JModel::getInstance('Categories', 'ContentModel', array('ignore_request' => true)); } $categories->setState('params', $appParams); $levels = 9999; $categories->setState('filter.get_children', $levels); $categories->setState('filter.published', 1); $categories->setState('filter.access', $access); $additional_catids = array(); foreach ($catids as $catid) { $categories->setState('filter.parentId', $catid); $recursive = true; $items = $categories->getItems($recursive); if($items) { foreach ($items as $category) { $condition = (($category->level - $categories->getParent()->level) <= $levels); if ($condition) { $additional_catids[] = $category->id; } } } } $catids = array_unique(array_merge($catids, $additional_catids)); return $catids; } }
0111001101111010/hackforchange_website_template
plugins/content/rokcomments/rokcomments.php
PHP
gpl-2.0
16,710
INTERFACE [arm]: #include "kmem.h" class Page_table; class Kmem_space : public Kmem { public: static void init(); static void init_hw(); static Page_table *kdir(); private: static Page_table *_kdir; }; //--------------------------------------------------------------------------- IMPLEMENTATION [arm]: #include <cassert> #include <panic.h> #include "console.h" #include "pagetable.h" #include "kmem.h" #include "kip_init.h" #include "mem_unit.h" #include <cstdio> char kernel_page_directory[sizeof(Page_table)] __attribute__((aligned(0x4000))); Page_table *Kmem_space::_kdir = (Page_table*)&kernel_page_directory; IMPLEMENT inline Page_table *Kmem_space::kdir() { return _kdir; } // initialze the kernel space (page table) IMPLEMENT void Kmem_space::init() { Page_table::init(); Mem_unit::clean_vdcache(); }
MicroTrustRepos/microkernel
src/kernel/fiasco/src/kern/arm/kmem_space.cpp
C++
gpl-2.0
834
#define H2D_REPORT_WARN #define H2D_REPORT_INFO #define H2D_REPORT_VERBOSE #define H2D_REPORT_FILE "application.log" #include "hermes2d.h" using namespace RefinementSelectors; // This example solves adaptively the electric field in a simplified microwave oven. // The waves are generated using a harmonic surface current on the right-most edge. // (Such small cavity is present in every microwave oven). There is a circular // load located in the middle of the main cavity, defined through a different // permittivity -- see function in_load(...). One can either use a mesh that is // aligned to the load via curvilinear elements (ALIGN_MESH = true), or an unaligned // mesh (ALIGN_MESH = false). Convergence graphs are saved both wrt. the dof number // and cpu time. // // PDE: time-harmonic Maxwell's equations; // there is circular load in the middle of the large cavity, whose permittivity // is different from the rest of the domain. // // Domain: square cavity with another small square cavity attached from outside // on the right. // // Meshes: you can either use "oven_load_circle.mesh" containing curved elements // aligned with the circular load, or "oven_load_square.mesh" which is not // aligned. // // BC: perfect conductor on the boundary except for the right-most edge of the small // cavity, where a harmonic surface current is prescribed // // The following parameters can be changed: const int INIT_REF_NUM = 0; // Number of initial uniform mesh refinements. const int P_INIT = 2; // Initial polynomial degree. NOTE: The meaning is different from // standard continuous elements in the space H1. Here, P_INIT refers // to the maximum poly order of the tangential component, and polynomials // of degree P_INIT + 1 are present in element interiors. P_INIT = 0 // is for Whitney elements. const bool ALIGN_MESH = true; // if ALIGN_MESH == true, curvilinear elements aligned with the // circular load are used, otherwise one uses a non-aligned mesh. const double THRESHOLD = 0.3; // This is a quantitative parameter of the adapt(...) function and // it has different meanings for various adaptive strategies (see below). const int STRATEGY = 0; // Adaptive strategy: // STRATEGY = 0 ... refine elements until sqrt(THRESHOLD) times total // error is processed. If more elements have similar errors, refine // all to keep the mesh symmetric. // STRATEGY = 1 ... refine all elements whose error is larger // than THRESHOLD times maximum element error. // STRATEGY = 2 ... refine all elements whose error is larger // than THRESHOLD. // More adaptive strategies can be created in adapt_ortho_h1.cpp. const CandList CAND_LIST = H2D_HP_ANISO; // Predefined list of element refinement candidates. Possible values are // H2D_P_ISO, H2D_P_ANISO, H2D_H_ISO, H2D_H_ANISO, H2D_HP_ISO, // H2D_HP_ANISO_H, H2D_HP_ANISO_P, H2D_HP_ANISO. // See the User Documentation for details. const int MESH_REGULARITY = -1; // Maximum allowed level of hanging nodes: // MESH_REGULARITY = -1 ... arbitrary level hangning nodes (default), // MESH_REGULARITY = 1 ... at most one-level hanging nodes, // MESH_REGULARITY = 2 ... at most two-level hanging nodes, etc. // Note that regular meshes are not supported, this is due to // their notoriously bad performance. const double CONV_EXP = 1.0; // Default value is 1.0. This parameter influences the selection of // cancidates in hp-adaptivity. See get_optimal_refinement() for details. const double ERR_STOP = 2.0; // Stopping criterion for adaptivity (rel. error tolerance between the // reference mesh and coarse mesh solution in percent). const int NDOF_STOP = 60000; // Adaptivity process stops when the number of degrees of freedom grows // over this limit. This is to prevent h-adaptivity to go on forever. MatrixSolverType matrix_solver = SOLVER_UMFPACK; // Possibilities: SOLVER_UMFPACK, SOLVER_PETSC, // SOLVER_MUMPS, and more are coming. // Problem parameters. const double e_0 = 8.8541878176 * 1e-12; const double mu_0 = 1.256 * 1e-6; const double e_r = 1.0; const double mu_r = 1.0; const double rho = 3820.0; const double Cp = 7.531000; const double freq = 1.0*2450000000.0; const double omega = 2 * M_PI * freq; const double c = 1 / sqrt(e_0 * mu_0); const double kappa = 2 * M_PI * freq * sqrt(e_0 * mu_0); const double J = 0.0000033333; // Boundary condition types. BCType bc_types(int marker) { if (marker == 2) return BC_ESSENTIAL; // perfect conductor BC else return BC_NATURAL; // impedance BC } // Essential (Dirichlet) boundary condition values. scalar essential_bc_values(int ess_bdy_marker, double x, double y) { return 0; } // Geometry of the load. bool in_load(double x, double y) { double cx = -0.152994121; double cy = 0.030598824; double r = 0.043273273; if (sqr(cx - x) + sqr(cy - y) < sqr(r)) return true; else return false; } // Gamma as a function of x, y. double gam(int marker, double x, double y) { if (ALIGN_MESH && marker == 1) return 0.03; if (!ALIGN_MESH && in_load(x,y)) { double cx = -0.152994121; double cy = 0.030598824; double r = sqrt(sqr(cx - x) + sqr(cy - y)); return (0.03 + 1)/2.0 - (0.03 - 1) * atan(10.0*(r - 0.043273273)) / M_PI; } return 0.0; } double gam(int marker, Ord x, Ord y) { return 0.0; } // Relative permittivity as a function of x, y. double er(int marker, double x, double y) { if (ALIGN_MESH && marker == 1) return 7.5; if (!ALIGN_MESH && in_load(x,y)) { double cx = -0.152994121; double cy = 0.030598824; double r = sqrt(sqr(cx - x) + sqr(cy - y)); return (7.5 + 1)/2.0 - (7.5 - 1) * atan(10.0*(r - 0.043273273)) / M_PI; } return 1.0; } double er(int marker, Ord x, Ord y) { return 1.0; } // Weak forms. #include "forms.cpp" int main(int argc, char* argv[]) { // Load the mesh. Mesh mesh; H2DReader mloader; if (ALIGN_MESH) mloader.load("oven_load_circle.mesh", &mesh); else mloader.load("oven_load_square.mesh", &mesh); // Perform initial mesh refinemets. for (int i=0; i < INIT_REF_NUM; i++) mesh.refine_all_elements(); // Create an Hcurl space. HcurlSpace space(&mesh, bc_types, essential_bc_values, P_INIT); // Initialize the weak formulation. WeakForm wf; wf.add_matrix_form(callback(bilinear_form)); wf.add_vector_form_surf(callback(linear_form_surf)); // Initialize refinements selector. HcurlProjBasedSelector selector(CAND_LIST, CONV_EXP, H2DRS_DEFAULT_ORDER); // Initialize adaptivity parameters. double to_be_processed = 0; AdaptivityParamType apt(ERR_STOP, NDOF_STOP, THRESHOLD, STRATEGY, MESH_REGULARITY, to_be_processed, H2D_TOTAL_ERROR_REL, H2D_ELEMENT_ERROR_REL); // Geometry and position of visualization windows. WinGeom* sln_win_geom = new WinGeom(0, 355, 900, 300); WinGeom* mesh_win_geom = new WinGeom(0, 0, 900, 300); // Adaptivity loop. Solution *sln = new Solution(); Solution *ref_sln = new Solution(); bool verbose = true; // Print info during adaptivity. bool is_complex = true; solve_linear_adapt(&space, &wf, NULL, matrix_solver, H2D_HCURL_NORM, sln, ref_sln, Tuple<WinGeom *>(sln_win_geom), Tuple<WinGeom *>(mesh_win_geom), &selector, &apt, verbose, Tuple<ExactSolution *>(), is_complex); // Wait for all views to be closed. View::wait(); return 0; }
certik/hermes2d
examples/waveguide/main.cpp
C++
gpl-2.0
8,583
package com.ullarah.urocket.task; import com.ullarah.urocket.RocketInit; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Particle; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import java.util.Map; import java.util.UUID; public class StationParticles { public void task() { Plugin plugin = Bukkit.getPluginManager().getPlugin(RocketInit.pluginName); plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, () -> plugin.getServer().getScheduler().runTask(plugin, () -> { if (!RocketInit.rocketRepair.isEmpty()) for (Map.Entry<UUID, Location> repairStation : RocketInit.rocketRepair.entrySet()) { Player player = Bukkit.getPlayer(repairStation.getKey()); float x = (float) (repairStation.getValue().getBlockX() + 0.5); float y = (float) (repairStation.getValue().getBlockY() + 0.5); float z = (float) (repairStation.getValue().getBlockZ() + 0.5); player.getWorld().spawnParticle(Particle.PORTAL, x, y, z, 1, 0, 0, 0, 1); } }), 0, 0); } }
RobotoRaccoon/MinecraftPlugins
uRocket/src/main/java/com/ullarah/urocket/task/StationParticles.java
Java
gpl-2.0
1,271
#include <string> #include <vector> #include <set> #include <map> #include <algorithm> #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <limits.h> #include "elf.h" using namespace std; #ifdef MIPSEL /* The lemote fuloong 2f kernel defconfig sets a page size of 16KB */ const unsigned int pageSize = 4096*4; #else const unsigned int pageSize = 4096; #endif static bool debugMode = false; static bool forceRPath = false; static string fileName; off_t fileSize, maxSize; unsigned char * contents = 0; #define ElfFileParams class Elf_Ehdr, class Elf_Phdr, class Elf_Shdr, class Elf_Addr, class Elf_Off, class Elf_Dyn, class Elf_Sym #define ElfFileParamNames Elf_Ehdr, Elf_Phdr, Elf_Shdr, Elf_Addr, Elf_Off, Elf_Dyn, Elf_Sym template<ElfFileParams> class ElfFile { Elf_Ehdr * hdr; vector<Elf_Phdr> phdrs; vector<Elf_Shdr> shdrs; bool littleEndian; bool changed; bool isExecutable; typedef string SectionName; typedef map<SectionName, string> ReplacedSections; ReplacedSections replacedSections; string sectionNames; /* content of the .shstrtab section */ /* Align on 4 or 8 bytes boundaries on 32- or 64-bit platforms respectively. */ unsigned int sectionAlignment; vector<SectionName> sectionsByOldIndex; public: ElfFile() { changed = false; sectionAlignment = sizeof(Elf_Off); } bool isChanged() { return changed; } void parse(); private: struct CompPhdr { ElfFile * elfFile; bool operator ()(const Elf_Phdr & x, const Elf_Phdr & y) { if (x.p_type == PT_PHDR) return true; if (y.p_type == PT_PHDR) return false; return elfFile->rdi(x.p_paddr) < elfFile->rdi(y.p_paddr); } }; friend struct CompPhdr; void sortPhdrs(); struct CompShdr { ElfFile * elfFile; bool operator ()(const Elf_Shdr & x, const Elf_Shdr & y) { return elfFile->rdi(x.sh_offset) < elfFile->rdi(y.sh_offset); } }; friend struct CompShdr; void sortShdrs(); void shiftFile(unsigned int extraPages, Elf_Addr startPage); string getSectionName(const Elf_Shdr & shdr); Elf_Shdr & findSection(const SectionName & sectionName); Elf_Shdr * findSection2(const SectionName & sectionName); unsigned int findSection3(const SectionName & sectionName); string & replaceSection(const SectionName & sectionName, unsigned int size); void writeReplacedSections(Elf_Off & curOff, Elf_Addr startAddr, Elf_Off startOffset); void rewriteHeaders(Elf_Addr phdrAddress); void rewriteSectionsLibrary(); void rewriteSectionsExecutable(); public: void rewriteSections(); string getInterpreter(); void setInterpreter(const string & newInterpreter); typedef enum { rpPrint, rpShrink, rpSet } RPathOp; void modifyRPath(RPathOp op, string newRPath); void removeNeeded(set<string> libs); private: /* Convert an integer in big or little endian representation (as specified by the ELF header) to this platform's integer representation. */ template<class I> I rdi(I i); /* Convert back to the ELF representation. */ template<class I> I wri(I & t, unsigned long long i) { t = rdi((I) i); return i; } }; /* !!! G++ creates broken code if this function is inlined, don't know why... */ template<ElfFileParams> template<class I> I ElfFile<ElfFileParamNames>::rdi(I i) { I r = 0; if (littleEndian) { for (unsigned int n = 0; n < sizeof(I); ++n) { r |= ((I) *(((unsigned char *) &i) + n)) << (n * 8); } } else { for (unsigned int n = 0; n < sizeof(I); ++n) { r |= ((I) *(((unsigned char *) &i) + n)) << ((sizeof(I) - n - 1) * 8); } } return r; } /* Ugly: used to erase DT_RUNPATH when using --force-rpath. */ #define DT_IGNORE 0x00726e67 static void debug(const char * format, ...) { if (debugMode) { va_list ap; va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); } } static void error(string msg) { if (errno) perror(msg.c_str()); else fprintf(stderr, "%s\n", msg.c_str()); exit(1); } static void growFile(off_t newSize) { if (newSize > maxSize) error("maximum file size exceeded"); if (newSize <= fileSize) return; if (newSize > fileSize) memset(contents + fileSize, 0, newSize - fileSize); fileSize = newSize; } static void readFile(string fileName, mode_t * fileMode) { struct stat st; if (stat(fileName.c_str(), &st) != 0) error("stat"); fileSize = st.st_size; *fileMode = st.st_mode; maxSize = fileSize + 8 * 1024 * 1024; contents = (unsigned char *) malloc(fileSize + maxSize); if (!contents) abort(); int fd = open(fileName.c_str(), O_RDONLY); if (fd == -1) error("open"); if (read(fd, contents, fileSize) != fileSize) error("read"); close(fd); } static void checkPointer(void * p, unsigned int size) { unsigned char * q = (unsigned char *) p; assert(q >= contents && q + size <= contents + fileSize); } template<ElfFileParams> void ElfFile<ElfFileParamNames>::parse() { isExecutable = false; /* Check the ELF header for basic validity. */ if (fileSize < (off_t) sizeof(Elf_Ehdr)) error("missing ELF header"); hdr = (Elf_Ehdr *) contents; if (memcmp(hdr->e_ident, ELFMAG, SELFMAG) != 0) error("not an ELF executable"); littleEndian = contents[EI_DATA] == ELFDATA2LSB; if (rdi(hdr->e_type) != ET_EXEC && rdi(hdr->e_type) != ET_DYN) error("wrong ELF type"); if ((off_t) (rdi(hdr->e_phoff) + rdi(hdr->e_phnum) * rdi(hdr->e_phentsize)) > fileSize) error("missing program headers"); if ((off_t) (rdi(hdr->e_shoff) + rdi(hdr->e_shnum) * rdi(hdr->e_shentsize)) > fileSize) error("missing section headers"); if (rdi(hdr->e_phentsize) != sizeof(Elf_Phdr)) error("program headers have wrong size"); /* Copy the program and section headers. */ for (int i = 0; i < rdi(hdr->e_phnum); ++i) { phdrs.push_back(* ((Elf_Phdr *) (contents + rdi(hdr->e_phoff)) + i)); if (rdi(phdrs[i].p_type) == PT_INTERP) isExecutable = true; } for (int i = 0; i < rdi(hdr->e_shnum); ++i) shdrs.push_back(* ((Elf_Shdr *) (contents + rdi(hdr->e_shoff)) + i)); /* Get the section header string table section (".shstrtab"). Its index in the section header table is given by e_shstrndx field of the ELF header. */ unsigned int shstrtabIndex = rdi(hdr->e_shstrndx); assert(shstrtabIndex < shdrs.size()); unsigned int shstrtabSize = rdi(shdrs[shstrtabIndex].sh_size); char * shstrtab = (char * ) contents + rdi(shdrs[shstrtabIndex].sh_offset); checkPointer(shstrtab, shstrtabSize); assert(shstrtabSize > 0); assert(shstrtab[shstrtabSize - 1] == 0); sectionNames = string(shstrtab, shstrtabSize); sectionsByOldIndex.resize(hdr->e_shnum); for (unsigned int i = 1; i < rdi(hdr->e_shnum); ++i) sectionsByOldIndex[i] = getSectionName(shdrs[i]); } template<ElfFileParams> void ElfFile<ElfFileParamNames>::sortPhdrs() { /* Sort the segments by offset. */ CompPhdr comp; comp.elfFile = this; sort(phdrs.begin(), phdrs.end(), comp); } template<ElfFileParams> void ElfFile<ElfFileParamNames>::sortShdrs() { /* Translate sh_link mappings to section names, since sorting the sections will invalidate the sh_link fields. */ map<SectionName, SectionName> linkage; for (unsigned int i = 1; i < rdi(hdr->e_shnum); ++i) if (rdi(shdrs[i].sh_link) != 0) linkage[getSectionName(shdrs[i])] = getSectionName(shdrs[rdi(shdrs[i].sh_link)]); /* Idem for sh_info on certain sections. */ map<SectionName, SectionName> info; for (unsigned int i = 1; i < rdi(hdr->e_shnum); ++i) if (rdi(shdrs[i].sh_info) != 0 && (rdi(shdrs[i].sh_type) == SHT_REL || rdi(shdrs[i].sh_type) == SHT_RELA)) info[getSectionName(shdrs[i])] = getSectionName(shdrs[rdi(shdrs[i].sh_info)]); /* Idem for the index of the .shstrtab section in the ELF header. */ SectionName shstrtabName = getSectionName(shdrs[rdi(hdr->e_shstrndx)]); /* Sort the sections by offset. */ CompShdr comp; comp.elfFile = this; sort(shdrs.begin(), shdrs.end(), comp); /* Restore the sh_link mappings. */ for (unsigned int i = 1; i < rdi(hdr->e_shnum); ++i) if (rdi(shdrs[i].sh_link) != 0) wri(shdrs[i].sh_link, findSection3(linkage[getSectionName(shdrs[i])])); /* And the st_info mappings. */ for (unsigned int i = 1; i < rdi(hdr->e_shnum); ++i) if (rdi(shdrs[i].sh_info) != 0 && (rdi(shdrs[i].sh_type) == SHT_REL || rdi(shdrs[i].sh_type) == SHT_RELA)) wri(shdrs[i].sh_info, findSection3(info[getSectionName(shdrs[i])])); /* And the .shstrtab index. */ wri(hdr->e_shstrndx, findSection3(shstrtabName)); } static void writeFile(string fileName, mode_t fileMode) { string fileName2 = fileName + "_patchelf_tmp"; int fd = open(fileName2.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0700); if (fd == -1) error("open"); if (write(fd, contents, fileSize) != fileSize) error("write"); if (close(fd) != 0) error("close"); if (chmod(fileName2.c_str(), fileMode) != 0) error("chmod"); if (rename(fileName2.c_str(), fileName.c_str()) != 0) error("rename"); } static unsigned int roundUp(unsigned int n, unsigned int m) { return ((n - 1) / m + 1) * m; } template<ElfFileParams> void ElfFile<ElfFileParamNames>::shiftFile(unsigned int extraPages, Elf_Addr startPage) { /* Move the entire contents of the file `extraPages' pages further. */ unsigned int oldSize = fileSize; unsigned int shift = extraPages * pageSize; growFile(fileSize + extraPages * pageSize); memmove(contents + extraPages * pageSize, contents, oldSize); memset(contents + sizeof(Elf_Ehdr), 0, shift - sizeof(Elf_Ehdr)); /* Adjust the ELF header. */ wri(hdr->e_phoff, sizeof(Elf_Ehdr)); wri(hdr->e_shoff, rdi(hdr->e_shoff) + shift); /* Update the offsets in the section headers. */ for (int i = 1; i < rdi(hdr->e_shnum); ++i) wri(shdrs[i].sh_offset, rdi(shdrs[i].sh_offset) + shift); /* Update the offsets in the program headers. */ for (int i = 0; i < rdi(hdr->e_phnum); ++i) { wri(phdrs[i].p_offset, rdi(phdrs[i].p_offset) + shift); if (rdi(phdrs[i].p_align) != 0 && (rdi(phdrs[i].p_vaddr) - rdi(phdrs[i].p_offset)) % rdi(phdrs[i].p_align) != 0) { debug("changing alignment of program header %d from %d to %d\n", i, rdi(phdrs[i].p_align), pageSize); wri(phdrs[i].p_align, pageSize); } } /* Add a segment that maps the new program/section headers and PT_INTERP segment into memory. Otherwise glibc will choke. */ phdrs.resize(rdi(hdr->e_phnum) + 1); wri(hdr->e_phnum, rdi(hdr->e_phnum) + 1); Elf_Phdr & phdr = phdrs[rdi(hdr->e_phnum) - 1]; wri(phdr.p_type, PT_LOAD); wri(phdr.p_offset, 0); wri(phdr.p_vaddr, wri(phdr.p_paddr, startPage)); wri(phdr.p_filesz, wri(phdr.p_memsz, shift)); wri(phdr.p_flags, PF_R | PF_W); wri(phdr.p_align, pageSize); } template<ElfFileParams> string ElfFile<ElfFileParamNames>::getSectionName(const Elf_Shdr & shdr) { return string(sectionNames.c_str() + rdi(shdr.sh_name)); } template<ElfFileParams> Elf_Shdr & ElfFile<ElfFileParamNames>::findSection(const SectionName & sectionName) { Elf_Shdr * shdr = findSection2(sectionName); if (!shdr) error("cannot find section " + sectionName); return *shdr; } template<ElfFileParams> Elf_Shdr * ElfFile<ElfFileParamNames>::findSection2(const SectionName & sectionName) { unsigned int i = findSection3(sectionName); return i ? &shdrs[i] : 0; } template<ElfFileParams> unsigned int ElfFile<ElfFileParamNames>::findSection3(const SectionName & sectionName) { for (unsigned int i = 1; i < rdi(hdr->e_shnum); ++i) if (getSectionName(shdrs[i]) == sectionName) return i; return 0; } template<ElfFileParams> string & ElfFile<ElfFileParamNames>::replaceSection(const SectionName & sectionName, unsigned int size) { ReplacedSections::iterator i = replacedSections.find(sectionName); string s; if (i != replacedSections.end()) { s = string(i->second); } else { Elf_Shdr & shdr = findSection(sectionName); s = string((char *) contents + rdi(shdr.sh_offset), rdi(shdr.sh_size)); } s.resize(size); replacedSections[sectionName] = s; return replacedSections[sectionName]; } template<ElfFileParams> void ElfFile<ElfFileParamNames>::writeReplacedSections(Elf_Off & curOff, Elf_Addr startAddr, Elf_Off startOffset) { /* Overwrite the old section contents with 'X's. Do this *before* writing the new section contents (below) to prevent clobbering previously written new section contents. */ for (ReplacedSections::iterator i = replacedSections.begin(); i != replacedSections.end(); ++i) { string sectionName = i->first; Elf_Shdr & shdr = findSection(sectionName); memset(contents + rdi(shdr.sh_offset), 'X', rdi(shdr.sh_size)); } for (ReplacedSections::iterator i = replacedSections.begin(); i != replacedSections.end(); ++i) { string sectionName = i->first; Elf_Shdr & shdr = findSection(sectionName); debug("rewriting section `%s' from offset 0x%x (size %d) to offset 0x%x (size %d)\n", sectionName.c_str(), rdi(shdr.sh_offset), rdi(shdr.sh_size), curOff, i->second.size()); memcpy(contents + curOff, (unsigned char *) i->second.c_str(), i->second.size()); /* Update the section header for this section. */ wri(shdr.sh_offset, curOff); wri(shdr.sh_addr, startAddr + (curOff - startOffset)); wri(shdr.sh_size, i->second.size()); wri(shdr.sh_addralign, sectionAlignment); /* If this is the .interp section, then the PT_INTERP segment must be sync'ed with it. */ if (sectionName == ".interp") { for (unsigned int j = 0; j < phdrs.size(); ++j) if (rdi(phdrs[j].p_type) == PT_INTERP) { phdrs[j].p_offset = shdr.sh_offset; phdrs[j].p_vaddr = phdrs[j].p_paddr = shdr.sh_addr; phdrs[j].p_filesz = phdrs[j].p_memsz = shdr.sh_size; } } /* If this is the .dynamic section, then the PT_DYNAMIC segment must be sync'ed with it. */ if (sectionName == ".dynamic") { for (unsigned int j = 0; j < phdrs.size(); ++j) if (rdi(phdrs[j].p_type) == PT_DYNAMIC) { phdrs[j].p_offset = shdr.sh_offset; phdrs[j].p_vaddr = phdrs[j].p_paddr = shdr.sh_addr; phdrs[j].p_filesz = phdrs[j].p_memsz = shdr.sh_size; } } curOff += roundUp(i->second.size(), sectionAlignment); } replacedSections.clear(); } template<ElfFileParams> void ElfFile<ElfFileParamNames>::rewriteSectionsLibrary() { /* For dynamic libraries, we just place the replacement sections at the end of the file. They're mapped into memory by a PT_LOAD segment located directly after the last virtual address page of other segments. */ Elf_Addr startPage = 0; for (unsigned int i = 0; i < phdrs.size(); ++i) { Elf_Addr thisPage = roundUp(rdi(phdrs[i].p_vaddr) + rdi(phdrs[i].p_memsz), pageSize); if (thisPage > startPage) startPage = thisPage; } debug("last page is 0x%llx\n", (unsigned long long) startPage); /* Compute the total space needed for the replaced sections and the program headers. */ off_t neededSpace = (phdrs.size() + 1) * sizeof(Elf_Phdr); for (ReplacedSections::iterator i = replacedSections.begin(); i != replacedSections.end(); ++i) neededSpace += roundUp(i->second.size(), sectionAlignment); debug("needed space is %d\n", neededSpace); size_t startOffset = roundUp(fileSize, pageSize); growFile(startOffset + neededSpace); /* Even though this file is of type ET_DYN, it could actually be an executable. For instance, Gold produces executables marked ET_DYN. In that case we can still hit the kernel bug that necessitated rewriteSectionsExecutable(). However, such executables also tend to start at virtual address 0, so rewriteSectionsExecutable() won't work because it doesn't have any virtual address space to grow downwards into. As a workaround, make sure that the virtual address of our new PT_LOAD segment relative to the first PT_LOAD segment is equal to its offset; otherwise we hit the kernel bug. This may require creating a hole in the executable. The bigger the size of the uninitialised data segment, the bigger the hole. */ if (isExecutable) { if (startOffset >= startPage) { debug("shifting new PT_LOAD segment by %d bytes to work around a Linux kernel bug\n", startOffset - startPage); } else { size_t hole = startPage - startOffset; /* Print a warning, because the hole could be very big. */ fprintf(stderr, "warning: working around a Linux kernel bug by creating a hole of %zu bytes in ‘%s’\n", hole, fileName.c_str()); assert(hole % pageSize == 0); /* !!! We could create an actual hole in the file here, but it's probably not worth the effort. */ growFile(fileSize + hole); startOffset += hole; } startPage = startOffset; } /* Add a segment that maps the replaced sections and program headers into memory. */ phdrs.resize(rdi(hdr->e_phnum) + 1); wri(hdr->e_phnum, rdi(hdr->e_phnum) + 1); Elf_Phdr & phdr = phdrs[rdi(hdr->e_phnum) - 1]; wri(phdr.p_type, PT_LOAD); wri(phdr.p_offset, startOffset); wri(phdr.p_vaddr, wri(phdr.p_paddr, startPage)); wri(phdr.p_filesz, wri(phdr.p_memsz, neededSpace)); wri(phdr.p_flags, PF_R | PF_W); wri(phdr.p_align, pageSize); /* Write out the replaced sections. */ Elf_Off curOff = startOffset + phdrs.size() * sizeof(Elf_Phdr); writeReplacedSections(curOff, startPage, startOffset); assert((off_t) curOff == startOffset + neededSpace); /* Move the program header to the start of the new area. */ wri(hdr->e_phoff, startOffset); rewriteHeaders(startPage); } template<ElfFileParams> void ElfFile<ElfFileParamNames>::rewriteSectionsExecutable() { /* Sort the sections by offset, otherwise we won't correctly find all the sections before the last replaced section. */ sortShdrs(); /* What is the index of the last replaced section? */ unsigned int lastReplaced = 0; for (unsigned int i = 1; i < rdi(hdr->e_shnum); ++i) { string sectionName = getSectionName(shdrs[i]); if (replacedSections.find(sectionName) != replacedSections.end()) { debug("using replaced section `%s'\n", sectionName.c_str()); lastReplaced = i; } } assert(lastReplaced != 0); debug("last replaced is %d\n", lastReplaced); /* Try to replace all sections before that, as far as possible. Stop when we reach an irreplacable section (such as one of type SHT_PROGBITS). These cannot be moved in virtual address space since that would invalidate absolute references to them. */ assert(lastReplaced + 1 < shdrs.size()); /* !!! I'm lazy. */ size_t startOffset = rdi(shdrs[lastReplaced + 1].sh_offset); Elf_Addr startAddr = rdi(shdrs[lastReplaced + 1].sh_addr); string prevSection; for (unsigned int i = 1; i <= lastReplaced; ++i) { Elf_Shdr & shdr(shdrs[i]); string sectionName = getSectionName(shdr); debug("looking at section `%s'\n", sectionName.c_str()); /* !!! Why do we stop after a .dynstr section? I can't remember! */ if ((rdi(shdr.sh_type) == SHT_PROGBITS && sectionName != ".interp") || prevSection == ".dynstr") { startOffset = rdi(shdr.sh_offset); startAddr = rdi(shdr.sh_addr); lastReplaced = i - 1; break; } else { if (replacedSections.find(sectionName) == replacedSections.end()) { debug("replacing section `%s' which is in the way\n", sectionName.c_str()); replaceSection(sectionName, rdi(shdr.sh_size)); } } prevSection = sectionName; } debug("first reserved offset/addr is 0x%x/0x%llx\n", startOffset, (unsigned long long) startAddr); assert(startAddr % pageSize == startOffset % pageSize); Elf_Addr firstPage = startAddr - startOffset; debug("first page is 0x%llx\n", (unsigned long long) firstPage); /* Right now we assume that the section headers are somewhere near the end, which appears to be the case most of the time. Therefore they're not accidentally overwritten by the replaced sections. !!! Fix this. */ assert((off_t) rdi(hdr->e_shoff) >= startOffset); /* Compute the total space needed for the replaced sections, the ELF header, and the program headers. */ size_t neededSpace = sizeof(Elf_Ehdr) + phdrs.size() * sizeof(Elf_Phdr); for (ReplacedSections::iterator i = replacedSections.begin(); i != replacedSections.end(); ++i) neededSpace += roundUp(i->second.size(), sectionAlignment); debug("needed space is %d\n", neededSpace); /* If we need more space at the start of the file, then grow the file by the minimum number of pages and adjust internal offsets. */ if (neededSpace > startOffset) { /* We also need an additional program header, so adjust for that. */ neededSpace += sizeof(Elf_Phdr); debug("needed space is %d\n", neededSpace); unsigned int neededPages = roundUp(neededSpace - startOffset, pageSize) / pageSize; debug("needed pages is %d\n", neededPages); if (neededPages * pageSize > firstPage) error("virtual address space underrun!"); firstPage -= neededPages * pageSize; startOffset += neededPages * pageSize; shiftFile(neededPages, firstPage); } /* Clear out the free space. */ Elf_Off curOff = sizeof(Elf_Ehdr) + phdrs.size() * sizeof(Elf_Phdr); debug("clearing first %d bytes\n", startOffset - curOff); memset(contents + curOff, 0, startOffset - curOff); /* Write out the replaced sections. */ writeReplacedSections(curOff, firstPage, 0); assert((off_t) curOff == neededSpace); rewriteHeaders(firstPage + rdi(hdr->e_phoff)); } template<ElfFileParams> void ElfFile<ElfFileParamNames>::rewriteSections() { if (replacedSections.empty()) return; for (ReplacedSections::iterator i = replacedSections.begin(); i != replacedSections.end(); ++i) debug("replacing section `%s' with size %d\n", i->first.c_str(), i->second.size()); if (rdi(hdr->e_type) == ET_DYN) { debug("this is a dynamic library\n"); rewriteSectionsLibrary(); } else if (rdi(hdr->e_type) == ET_EXEC) { debug("this is an executable\n"); rewriteSectionsExecutable(); } else error("unknown ELF type"); } template<ElfFileParams> void ElfFile<ElfFileParamNames>::rewriteHeaders(Elf_Addr phdrAddress) { /* Rewrite the program header table. */ /* If there is a segment for the program header table, update it. (According to the ELF spec, it must be the first entry.) */ if (rdi(phdrs[0].p_type) == PT_PHDR) { phdrs[0].p_offset = hdr->e_phoff; wri(phdrs[0].p_vaddr, wri(phdrs[0].p_paddr, phdrAddress)); wri(phdrs[0].p_filesz, wri(phdrs[0].p_memsz, phdrs.size() * sizeof(Elf_Phdr))); } sortPhdrs(); for (unsigned int i = 0; i < phdrs.size(); ++i) * ((Elf_Phdr *) (contents + rdi(hdr->e_phoff)) + i) = phdrs[i]; /* Rewrite the section header table. For neatness, keep the sections sorted. */ assert(rdi(hdr->e_shnum) == shdrs.size()); sortShdrs(); for (unsigned int i = 1; i < rdi(hdr->e_shnum); ++i) * ((Elf_Shdr *) (contents + rdi(hdr->e_shoff)) + i) = shdrs[i]; /* Update all those nasty virtual addresses in the .dynamic section. Note that not all executables have .dynamic sections (e.g., those produced by klibc's klcc). */ Elf_Shdr * shdrDynamic = findSection2(".dynamic"); if (shdrDynamic) { Elf_Dyn * dyn = (Elf_Dyn *) (contents + rdi(shdrDynamic->sh_offset)); unsigned int d_tag; for ( ; (d_tag = rdi(dyn->d_tag)) != DT_NULL; dyn++) if (d_tag == DT_STRTAB) dyn->d_un.d_ptr = findSection(".dynstr").sh_addr; else if (d_tag == DT_STRSZ) dyn->d_un.d_val = findSection(".dynstr").sh_size; else if (d_tag == DT_SYMTAB) dyn->d_un.d_ptr = findSection(".dynsym").sh_addr; else if (d_tag == DT_HASH) dyn->d_un.d_ptr = findSection(".hash").sh_addr; else if (d_tag == DT_GNU_HASH) dyn->d_un.d_ptr = findSection(".gnu.hash").sh_addr; else if (d_tag == DT_JMPREL) { Elf_Shdr * shdr = findSection2(".rel.plt"); if (!shdr) shdr = findSection2(".rela.plt"); /* 64-bit Linux, x86-64 */ if (!shdr) shdr = findSection2(".rela.IA_64.pltoff"); /* 64-bit Linux, IA-64 */ if (!shdr) error("cannot find section corresponding to DT_JMPREL"); dyn->d_un.d_ptr = shdr->sh_addr; } else if (d_tag == DT_REL) { /* !!! hack! */ Elf_Shdr * shdr = findSection2(".rel.dyn"); /* no idea if this makes sense, but it was needed for some program */ if (!shdr) shdr = findSection2(".rel.got"); if (!shdr) error("cannot find .rel.dyn or .rel.got"); dyn->d_un.d_ptr = shdr->sh_addr; } else if (d_tag == DT_RELA) dyn->d_un.d_ptr = findSection(".rela.dyn").sh_addr; /* PPC Linux */ else if (d_tag == DT_VERNEED) dyn->d_un.d_ptr = findSection(".gnu.version_r").sh_addr; else if (d_tag == DT_VERSYM) dyn->d_un.d_ptr = findSection(".gnu.version").sh_addr; } /* Rewrite the .dynsym section. It contains the indices of the sections in which symbols appear, so these need to be remapped. */ for (unsigned int i = 1; i < rdi(hdr->e_shnum); ++i) { if (rdi(shdrs[i].sh_type) != SHT_SYMTAB && rdi(shdrs[i].sh_type) != SHT_DYNSYM) continue; debug("rewriting symbol table section %d\n", i); for (size_t entry = 0; (entry + 1) * sizeof(Elf_Sym) <= rdi(shdrs[i].sh_size); entry++) { Elf_Sym * sym = (Elf_Sym *) (contents + rdi(shdrs[i].sh_offset) + entry * sizeof(Elf_Sym)); unsigned int shndx = rdi(sym->st_shndx); if (shndx != SHN_UNDEF && shndx < SHN_LORESERVE) { if (shndx >= sectionsByOldIndex.size()) { fprintf(stderr, "warning: entry %d in symbol table refers to a non-existent section, skipping\n", shndx); continue; } string section = sectionsByOldIndex.at(shndx); assert(!section.empty()); unsigned int newIndex = findSection3(section); // inefficient //debug("rewriting symbol %d: index = %d (%s) -> %d\n", entry, shndx, section.c_str(), newIndex); wri(sym->st_shndx, newIndex); /* Rewrite st_value. FIXME: we should do this for all types, but most don't actually change. */ if (ELF32_ST_TYPE(rdi(sym->st_info)) == STT_SECTION) wri(sym->st_value, rdi(shdrs[newIndex].sh_addr)); } } } } static void setSubstr(string & s, unsigned int pos, const string & t) { assert(pos + t.size() <= s.size()); copy(t.begin(), t.end(), s.begin() + pos); } template<ElfFileParams> string ElfFile<ElfFileParamNames>::getInterpreter() { Elf_Shdr & shdr = findSection(".interp"); return string((char *) contents + rdi(shdr.sh_offset), rdi(shdr.sh_size)); } template<ElfFileParams> void ElfFile<ElfFileParamNames>::setInterpreter(const string & newInterpreter) { string & section = replaceSection(".interp", newInterpreter.size() + 1); setSubstr(section, 0, newInterpreter + '\0'); changed = true; } static void concatToRPath(string & rpath, const string & path) { if (!rpath.empty()) rpath += ":"; rpath += path; } template<ElfFileParams> void ElfFile<ElfFileParamNames>::modifyRPath(RPathOp op, string newRPath) { Elf_Shdr & shdrDynamic = findSection(".dynamic"); /* !!! We assume that the virtual address in the DT_STRTAB entry of the dynamic section corresponds to the .dynstr section. */ Elf_Shdr & shdrDynStr = findSection(".dynstr"); char * strTab = (char *) contents + rdi(shdrDynStr.sh_offset); /* Find the DT_STRTAB entry in the dynamic section. */ Elf_Dyn * dyn = (Elf_Dyn *) (contents + rdi(shdrDynamic.sh_offset)); Elf_Addr strTabAddr = 0; for ( ; rdi(dyn->d_tag) != DT_NULL; dyn++) if (rdi(dyn->d_tag) == DT_STRTAB) strTabAddr = rdi(dyn->d_un.d_ptr); if (!strTabAddr) error("strange: no string table"); assert(strTabAddr == rdi(shdrDynStr.sh_addr)); /* Walk through the dynamic section, look for the RPATH/RUNPATH entry. According to the ld.so docs, DT_RPATH is obsolete, we should use DT_RUNPATH. DT_RUNPATH has two advantages: it can be overriden by LD_LIBRARY_PATH, and it's scoped (the DT_RUNPATH for an executable or library doesn't affect the search path for libraries used by it). DT_RPATH is ignored if DT_RUNPATH is present. The binutils `ld' still generates only DT_RPATH, unless you use its `--enable-new-dtag' option, in which case it generates a DT_RPATH and DT_RUNPATH pointing at the same string. */ static vector<string> neededLibs; dyn = (Elf_Dyn *) (contents + rdi(shdrDynamic.sh_offset)); Elf_Dyn * dynRPath = 0, * dynRunPath = 0; char * rpath = 0; for ( ; rdi(dyn->d_tag) != DT_NULL; dyn++) { if (rdi(dyn->d_tag) == DT_RPATH) { dynRPath = dyn; /* Only use DT_RPATH if there is no DT_RUNPATH. */ if (!dynRunPath) rpath = strTab + rdi(dyn->d_un.d_val); } else if (rdi(dyn->d_tag) == DT_RUNPATH) { dynRunPath = dyn; rpath = strTab + rdi(dyn->d_un.d_val); } else if (rdi(dyn->d_tag) == DT_NEEDED) neededLibs.push_back(string(strTab + rdi(dyn->d_un.d_val))); } if (op == rpPrint) { printf("%s\n", rpath ? rpath : ""); return; } if (op == rpShrink && !rpath) { debug("no RPATH to shrink\n"); return; } /* For each directory in the RPATH, check if it contains any needed library. */ if (op == rpShrink) { static vector<bool> neededLibFound(neededLibs.size(), false); newRPath = ""; char * pos = rpath; while (*pos) { char * end = strchr(pos, ':'); if (!end) end = strchr(pos, 0); /* Get the name of the directory. */ string dirName(pos, end - pos); if (*end == ':') ++end; pos = end; /* Non-absolute entries are allowed (e.g., the special "$ORIGIN" hack). */ if (dirName[0] != '/') { concatToRPath(newRPath, dirName); continue; } /* For each library that we haven't found yet, see if it exists in this directory. */ bool libFound = false; for (unsigned int j = 0; j < neededLibs.size(); ++j) if (!neededLibFound[j]) { string libName = dirName + "/" + neededLibs[j]; struct stat st; if (stat(libName.c_str(), &st) == 0) { neededLibFound[j] = true; libFound = true; } } if (!libFound) debug("removing directory `%s' from RPATH\n", dirName.c_str()); else concatToRPath(newRPath, dirName); } } if (string(rpath ? rpath : "") == newRPath) return; changed = true; /* Zero out the previous rpath to prevent retained dependencies in Nix. */ unsigned int rpathSize = 0; if (rpath) { rpathSize = strlen(rpath); memset(rpath, 'X', rpathSize); } debug("new rpath is `%s'\n", newRPath.c_str()); if (!forceRPath && dynRPath && !dynRunPath) { /* convert DT_RPATH to DT_RUNPATH */ dynRPath->d_tag = DT_RUNPATH; dynRunPath = dynRPath; dynRPath = 0; } if (forceRPath && dynRPath && dynRunPath) { /* convert DT_RUNPATH to DT_RPATH */ dynRunPath->d_tag = DT_IGNORE; } if (newRPath.size() <= rpathSize) { strcpy(rpath, newRPath.c_str()); return; } /* Grow the .dynstr section to make room for the new RPATH. */ debug("rpath is too long, resizing...\n"); string & newDynStr = replaceSection(".dynstr", rdi(shdrDynStr.sh_size) + newRPath.size() + 1); setSubstr(newDynStr, rdi(shdrDynStr.sh_size), newRPath + '\0'); /* Update the DT_RUNPATH and DT_RPATH entries. */ if (dynRunPath || dynRPath) { if (dynRunPath) dynRunPath->d_un.d_val = shdrDynStr.sh_size; if (dynRPath) dynRPath->d_un.d_val = shdrDynStr.sh_size; } else { /* There is no DT_RUNPATH entry in the .dynamic section, so we have to grow the .dynamic section. */ string & newDynamic = replaceSection(".dynamic", rdi(shdrDynamic.sh_size) + sizeof(Elf_Dyn)); unsigned int idx = 0; for ( ; rdi(((Elf_Dyn *) newDynamic.c_str())[idx].d_tag) != DT_NULL; idx++) ; debug("DT_NULL index is %d\n", idx); /* Shift all entries down by one. */ setSubstr(newDynamic, sizeof(Elf_Dyn), string(newDynamic, 0, sizeof(Elf_Dyn) * (idx + 1))); /* Add the DT_RUNPATH entry at the top. */ Elf_Dyn newDyn; wri(newDyn.d_tag, forceRPath ? DT_RPATH : DT_RUNPATH); newDyn.d_un.d_val = shdrDynStr.sh_size; setSubstr(newDynamic, 0, string((char *) &newDyn, sizeof(Elf_Dyn))); } } template<ElfFileParams> void ElfFile<ElfFileParamNames>::removeNeeded(set<string> libs) { if (libs.empty()) return; Elf_Shdr & shdrDynamic = findSection(".dynamic"); Elf_Shdr & shdrDynStr = findSection(".dynstr"); char * strTab = (char *) contents + rdi(shdrDynStr.sh_offset); Elf_Dyn * dyn = (Elf_Dyn *) (contents + rdi(shdrDynamic.sh_offset)); Elf_Dyn * last = dyn; for ( ; rdi(dyn->d_tag) != DT_NULL; dyn++) { if (rdi(dyn->d_tag) == DT_NEEDED) { char * name = strTab + rdi(dyn->d_un.d_val); if (libs.find(name) != libs.end()) { debug("removing DT_NEEDED entry `%s'\n", name); changed = true; } else { debug("keeping DT_NEEDED entry `%s'\n", name); *last++ = *dyn; } } else *last++ = *dyn; } memset(last, 0, sizeof(Elf_Dyn) * (dyn - last)); } static bool printInterpreter = false; static string newInterpreter; static bool shrinkRPath = false; static bool setRPath = false; static bool printRPath = false; static string newRPath; static set<string> neededLibsToRemove; template<class ElfFile> static void patchElf2(ElfFile & elfFile, mode_t fileMode) { elfFile.parse(); if (printInterpreter) printf("%s\n", elfFile.getInterpreter().c_str()); if (newInterpreter != "") elfFile.setInterpreter(newInterpreter); if (printRPath) elfFile.modifyRPath(elfFile.rpPrint, ""); if (shrinkRPath) elfFile.modifyRPath(elfFile.rpShrink, ""); else if (setRPath) elfFile.modifyRPath(elfFile.rpSet, newRPath); elfFile.removeNeeded(neededLibsToRemove); if (elfFile.isChanged()){ elfFile.rewriteSections(); writeFile(fileName, fileMode); } } static void patchElf() { if (!printInterpreter && !printRPath) debug("patching ELF file `%s'\n", fileName.c_str()); mode_t fileMode; readFile(fileName, &fileMode); /* Check the ELF header for basic validity. */ if (fileSize < (off_t) sizeof(Elf32_Ehdr)) error("missing ELF header"); if (memcmp(contents, ELFMAG, SELFMAG) != 0) error("not an ELF executable"); if (contents[EI_CLASS] == ELFCLASS32 && contents[EI_VERSION] == EV_CURRENT) { ElfFile<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr, Elf32_Addr, Elf32_Off, Elf32_Dyn, Elf32_Sym> elfFile; patchElf2(elfFile, fileMode); } else if (contents[EI_CLASS] == ELFCLASS64 && contents[EI_VERSION] == EV_CURRENT) { ElfFile<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr, Elf64_Addr, Elf64_Off, Elf64_Dyn, Elf64_Sym> elfFile; patchElf2(elfFile, fileMode); } else { error("ELF executable is not 32/64-bit, little/big-endian, version 1"); } } void showHelp(const string & progName) { fprintf(stderr, "syntax: %s\n\ [--set-interpreter FILENAME]\n\ [--print-interpreter]\n\ [--set-rpath RPATH]\n\ [--shrink-rpath]\n\ [--print-rpath]\n\ [--force-rpath]\n\ [--remove-needed LIBRARY]\n\ [--debug]\n\ [--version]\n\ FILENAME\n", progName.c_str()); } int main(int argc, char * * argv) { if (argc <= 1) { showHelp(argv[0]); return 1; } if (getenv("PATCHELF_DEBUG") != 0) debugMode = true; int i; for (i = 1; i < argc; ++i) { string arg(argv[i]); if (arg == "--set-interpreter" || arg == "--interpreter") { if (++i == argc) error("missing argument"); newInterpreter = argv[i]; } else if (arg == "--print-interpreter") { printInterpreter = true; } else if (arg == "--shrink-rpath") { shrinkRPath = true; } else if (arg == "--set-rpath") { if (++i == argc) error("missing argument"); setRPath = true; newRPath = argv[i]; } else if (arg == "--print-rpath") { printRPath = true; } else if (arg == "--force-rpath") { /* Generally we prefer to emit DT_RUNPATH instead of DT_RPATH, as the latter is obsolete. However, there is a slight semantic difference: DT_RUNPATH is "scoped", it only affects the executable or library in question, not its recursive imports. So maybe you really want to force the use of DT_RPATH. That's what this option does. Without it, DT_RPATH (if encountered) is converted to DT_RUNPATH, and if neither is present, a DT_RUNPATH is added. With it, DT_RPATH isn't converted to DT_RUNPATH, and if neither is present, a DT_RPATH is added. */ forceRPath = true; } else if (arg == "--remove-needed") { if (++i == argc) error("missing argument"); neededLibsToRemove.insert(argv[i]); } else if (arg == "--debug") { debugMode = true; } else if (arg == "--help") { showHelp(argv[0]); return 0; } else if (arg == "--version") { printf(PACKAGE_STRING "\n"); return 0; } else break; } if (i == argc) error("missing filename"); fileName = argv[i]; patchElf(); return 0; }
dotfloat/restrife
strife-ve-src/patchelf/src/patchelf.cc
C++
gpl-2.0
40,724
package org.gradle.sample; import android.app.Activity; import android.os.Bundle; import android.content.Intent; import android.widget.TextView; import com.google.common.collect.Lists; import java.lang.String; import java.util.Arrays; public class ShowPeopleActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String message = "People:"; Iterable<Person> people = Lists.newArrayList(new Person("fred")); for (Person person : people) { message += "\n * "; message += person.getName(); } TextView textView = new TextView(this); textView.setTextSize(20); textView.setText(message); setContentView(textView); } }
rex-xxx/mt6572_x201
tools/build/testapps/dependencies/src/main/java/org/gradle/sample/ShowPeopleActivity.java
Java
gpl-2.0
796
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2010-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.features.poller.remote.gwt.server.geocoding; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import net.simon04.jelementtree.ElementTree; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.opennms.features.poller.remote.gwt.client.GWTLatLng; /** * <p>NominatimGeocoder class.</p> * * @author ranger * @version $Id: $ * @since 1.8.1 */ public class NominatimGeocoder implements Geocoder { private static final Logger LOG = LoggerFactory.getLogger(NominatimGeocoder.class); private static final String GEOCODE_URL = "http://open.mapquestapi.com/nominatim/v1/search?format=xml"; private static final HttpClient m_httpClient = new DefaultHttpClient(); private String m_emailAddress; private String m_referer = null; /** * <p>Constructor for NominatimGeocoder.</p> * * @throws org.opennms.features.poller.remote.gwt.server.geocoding.GeocoderException if any. */ public NominatimGeocoder() throws GeocoderException { this(System.getProperty("gwt.geocoder.email")); } /** * <p>Constructor for NominatimGeocoder.</p> * * @param emailAddress a {@link java.lang.String} object. * @throws org.opennms.features.poller.remote.gwt.server.geocoding.GeocoderException if any. */ public NominatimGeocoder(final String emailAddress) throws GeocoderException { m_emailAddress = emailAddress; m_referer = System.getProperty("gwt.geocoder.referer"); if (m_emailAddress == null || m_emailAddress.equals("")) { throw new GeocoderException("you must configure gwt.geocoder.email to comply with the Nominatim terms of service (see http://wiki.openstreetmap.org/wiki/Nominatim)"); } } /** {@inheritDoc} */ @Override public GWTLatLng geocode(final String geolocation) throws GeocoderException { final HttpUriRequest method = new HttpGet(getUrl(geolocation)); method.addHeader("User-Agent", "OpenNMS-MapquestGeocoder/1.0"); if (m_referer != null) { method.addHeader("Referer", m_referer); } try { InputStream responseStream = m_httpClient.execute(method).getEntity().getContent(); final ElementTree tree = ElementTree.fromStream(responseStream); if (tree == null) { throw new GeocoderException("an error occurred connecting to the Nominatim geocoding service (no XML tree was found)"); } final List<ElementTree> places = tree.findAll("//place"); if (places.size() > 1) { LOG.warn("more than one location returned for query: {}", geolocation); } else if (places.size() == 0) { throw new GeocoderException("Nominatim returned an OK status code, but no places"); } final ElementTree place = places.get(0); Double latitude = Double.valueOf(place.getAttribute("lat")); Double longitude = Double.valueOf(place.getAttribute("lon")); return new GWTLatLng(latitude, longitude); } catch (GeocoderException e) { throw e; } catch (Throwable e) { throw new GeocoderException("unable to get lat/lng from Nominatim", e); } } private String getUrl(String geolocation) throws GeocoderException { try { return GEOCODE_URL + "&q=" + URLEncoder.encode(geolocation, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new GeocoderException("unable to URL-encode query string", e); } } }
rfdrake/opennms
features/remote-poller-gwt/src/main/java/org/opennms/features/poller/remote/gwt/server/geocoding/NominatimGeocoder.java
Java
gpl-2.0
4,707
/* * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * @bug 4930397 * @summary Make sure MemoryMXBean has two notification types. * @author Mandy Chung * * @modules java.management * @run main GetMBeanInfo */ import java.lang.management.*; import javax.management.*; public class GetMBeanInfo { private final static int EXPECTED_NOTIF_TYPES = 2; private static int count = 0; public static void main(String argv[]) throws Exception { final ObjectName objName; objName = new ObjectName(ManagementFactory.MEMORY_MXBEAN_NAME); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); MBeanInfo minfo = mbs.getMBeanInfo(objName); MBeanNotificationInfo[] notifs = minfo.getNotifications(); for (int i = 0; i < notifs.length; i++) { printNotifType(notifs[i]); } if (count != EXPECTED_NOTIF_TYPES) { throw new RuntimeException("Unexpected number of notification types" + " count = " + count + " expected = " + EXPECTED_NOTIF_TYPES); } } private static void printNotifType(MBeanNotificationInfo notif) { String[] types = notif.getNotifTypes(); for (int i = 0; i < types.length; i++) { System.out.println(types[i]); count++; } } }
universsky/openjdk
jdk/test/java/lang/management/MemoryMXBean/GetMBeanInfo.java
Java
gpl-2.0
2,409
// Copyright Oleg Maximenko 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://github.com/svgpp/svgpp for library home page. #pragma once #include <svgpp/definitions.hpp> #include <svgpp/utility/gil/common.hpp> #include <boost/gil/channel_algorithm.hpp> #include <boost/gil/color_base_algorithm.hpp> namespace svgpp { namespace gil_detail { namespace gil = boost::gil; template<class CompositeModeTag, class ChannelValue> struct composite_channel_fn; template<class CompositeModeTag, class ChannelValue> struct composite_alpha_fn; template<class ChannelValue> struct composite_arithmetic_channel_fn; // TODO: default implementation for non-8 bit channels // For signed channels we call unsigned analog, converting forward and back template<class CompositeModeTag> struct composite_channel_fn<CompositeModeTag, gil::bits8s> { gil::bits8s operator()(gil::bits8s channel_a, gil::bits8s channel_b, gil::bits8s alpha_a, gil::bits8s alpha_b) const { typedef gil::detail::channel_convert_to_unsigned<gil::bits8s> to_unsigned; typedef gil::detail::channel_convert_from_unsigned<gil::bits8s> from_unsigned; composite_channel_fn<CompositeModeTag, gil::bits8> converter_unsigned; return from_unsigned()(converter_unsigned( to_unsigned()(channel_a), to_unsigned()(channel_b), to_unsigned()(alpha_a), to_unsigned()(alpha_b))); } }; // Dca' = Sca + Dca x (1 - Sa) template<> struct composite_channel_fn<tag::value::over, gil::bits8> { gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const { return clamp_channel_bits8(channel_a + channel_b * (255 - alpha_a) / 255); } }; // Da' = Sa + Da - Sa x Da template<> struct composite_alpha_fn<tag::value::over, gil::bits8> { gil::bits8 operator()(int alpha_a, int alpha_b) const { return clamp_channel_bits8(alpha_a + alpha_b - alpha_a * alpha_b / 255); } }; // Dca' = Sca x Da template<> struct composite_channel_fn<tag::value::in, gil::bits8> { gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const { return channel_a * alpha_b / 255; } }; // Da' = Sa x Da template<> struct composite_alpha_fn<tag::value::in, gil::bits8> { gil::bits8 operator()(int alpha_a, int alpha_b) const { return alpha_a * alpha_b / 255; } }; // Dca' = Sca x (1 - Da) template<> struct composite_channel_fn<tag::value::out, gil::bits8> { gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const { return channel_a * alpha_a * (255 - alpha_b) / 65535; } }; // Da' = Sa x (1 - Da) template<> struct composite_alpha_fn<tag::value::out, gil::bits8> { gil::bits8 operator()(int alpha_a, int alpha_b) const { return alpha_a * (255 - alpha_b) / 255; } }; // Dca' = Sca x Da + Dca x (1 - Sa) template<> struct composite_channel_fn<tag::value::atop, gil::bits8> { gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const { return (channel_a * alpha_a + channel_b * (255 - alpha_a)) * alpha_b / 65535; } }; // Da' = Da template<> struct composite_alpha_fn<tag::value::atop, gil::bits8> { gil::bits8 operator()(gil::bits8 alpha_a, gil::bits8 alpha_b) const { return alpha_b; } }; // Dca' = Sca x (1 - Da) + Dca x (1 - Sa) template<> struct composite_channel_fn<tag::value::xor_, gil::bits8> { gil::bits8 operator()(int channel_a, int channel_b, int alpha_a, int alpha_b) const { return clamp_channel_bits8((channel_a * alpha_a * (255 - alpha_b) + channel_b * alpha_b * (255 - alpha_a)) / 65535); } }; // Da' = Sa + Da - 2 x Sa x Da template<> struct composite_alpha_fn<tag::value::xor_, gil::bits8> { gil::bits8 operator()(int alpha_a, int alpha_b) const { return clamp_channel_bits8((alpha_a + alpha_b - 2 * alpha_a * alpha_b) / 255); } }; // result = k1*i1*i2 + k2*i1 + k3*i2 + k4 template<> struct composite_arithmetic_channel_fn<gil::bits8> { template<class Coefficient> composite_arithmetic_channel_fn(Coefficient k1, Coefficient k2, Coefficient k3, Coefficient k4) : k1_(k1 * 255), k2_(k2 * 255), k3_(k3 * 255), k4_(k4 * 255) {} gil::bits8 operator()(int channel_a, int channel_b) const { return clamp_channel_bits8(k1_ * channel_a * channel_b / 65535 + k2_ * channel_a / 255 + k3_ * channel_b / 255 + k4_); } private: int k1_, k2_, k3_, k4_; }; } // namespace gil_detail namespace gil_utility { namespace gil = boost::gil; template<class CompositeModeTag> struct composite_pixel { template<class Color> Color operator()(const Color & pixa, const Color & pixb) const { typename gil::color_element_type<Color, gil::alpha_t>::type alpha_a = gil::get_color(pixa, gil::alpha_t()), alpha_b = gil::get_color(pixb, gil::alpha_t()); Color result; gil::get_color(result, gil::red_t()) = gil_detail::composite_channel_fn<CompositeModeTag, typename gil::color_element_type<Color, gil::red_t>::type>()( gil::get_color(pixa, gil::red_t()), gil::get_color(pixb, gil::red_t()), alpha_a, alpha_b); gil::get_color(result, gil::green_t()) = gil_detail::composite_channel_fn<CompositeModeTag, typename gil::color_element_type<Color, gil::green_t>::type>()( gil::get_color(pixa, gil::green_t()), gil::get_color(pixb, gil::green_t()), alpha_a, alpha_b); gil::get_color(result, gil::blue_t()) = gil_detail::composite_channel_fn<CompositeModeTag, typename gil::color_element_type<Color, gil::blue_t>::type>()( gil::get_color(pixa, gil::blue_t()), gil::get_color(pixb, gil::blue_t()), alpha_a, alpha_b); gil::get_color(result, gil::alpha_t()) = gil_detail::composite_alpha_fn<CompositeModeTag, typename gil::color_element_type<Color, gil::alpha_t>::type>()(alpha_a, alpha_b); return result; } }; template<class Color> struct composite_pixel_arithmetic { template<class Coefficient> composite_pixel_arithmetic(Coefficient k1, Coefficient k2, Coefficient k3, Coefficient k4) : r_(k1, k2, k3, k4) , g_(k1, k2, k3, k4) , b_(k1, k2, k3, k4) , a_(k1, k2, k3, k4) {} Color operator()(const Color & pixa, const Color & pixb) const { Color result; gil::get_color(result, gil::red_t()) = r_(gil::get_color(pixa, gil::red_t()) , gil::get_color(pixb, gil::red_t()) ); gil::get_color(result, gil::green_t()) = r_(gil::get_color(pixa, gil::green_t()) , gil::get_color(pixb, gil::green_t()) ); gil::get_color(result, gil::blue_t()) = r_(gil::get_color(pixa, gil::blue_t()) , gil::get_color(pixb, gil::blue_t()) ); gil::get_color(result, gil::alpha_t()) = r_(gil::get_color(pixa, gil::alpha_t()) , gil::get_color(pixb, gil::alpha_t()) ); return result; } private: gil_detail::composite_arithmetic_channel_fn<typename gil::color_element_type<Color, gil::red_t >::type> r_; gil_detail::composite_arithmetic_channel_fn<typename gil::color_element_type<Color, gil::green_t>::type> g_; gil_detail::composite_arithmetic_channel_fn<typename gil::color_element_type<Color, gil::blue_t >::type> b_; gil_detail::composite_arithmetic_channel_fn<typename gil::color_element_type<Color, gil::alpha_t>::type> a_; }; }}
asuradaimao/Walfas
includes/svgpp/utility/gil/composite.hpp
C++
gpl-2.0
7,303
package vn.edu.fpt.fts.classes; import java.io.Serializable; public class Route implements Serializable { private int active; private String category; private String createTime; private String destinationAddress; private String driverID; private String finishTime; private String notes; private int RouteID; private String startingAddress; private String startTime; private int weight; public Route() { // TODO Auto-generated constructor stub } public Route(int routeID, String startingAddress, String destinationAddress, String startTime, String finishTime, String notes, int weight, String createTime, int active, String driverID) { super(); this.RouteID = routeID; this.startingAddress = startingAddress; this.destinationAddress = destinationAddress; this.startTime = startTime; this.finishTime = finishTime; this.notes = notes; this.weight = weight; this.createTime = createTime; this.active = active; this.driverID = driverID; } public Route(String startingAddress, String destinationAddress, String startTime, String finishTime, String category) { // TODO Auto-generated constructor stub this.startingAddress = startingAddress; this.destinationAddress = destinationAddress; this.startTime = startTime; this.finishTime = finishTime; this.category = category; } public int getActive() { return active; } public String getCategory() { return category; } public String getCreateTime() { return createTime; } public String getDestinationAddress() { return destinationAddress; } public String getDriverID() { return driverID; } public String getFinishTime() { return finishTime; } public String getNotes() { return notes; } public int getRouteID() { return RouteID; } public String getStartingAddress() { return startingAddress; } public String getStartTime() { return startTime; } public int getWeight() { return weight; } public void setActive(int active) { this.active = active; } public void setCategory(String category) { this.category = category; } public void setCreateTime(String createTime) { this.createTime = createTime; } public void setDestinationAddress(String destinationAddress) { this.destinationAddress = destinationAddress; } public void setDriverID(String driverID) { this.driverID = driverID; } public void setFinishTime(String finishTime) { this.finishTime = finishTime; } public void setNotes(String notes) { this.notes = notes; } public void setRouteID(int routeID) { RouteID = routeID; } public void setStartingAddress(String startingAddress) { this.startingAddress = startingAddress; } public void setStartTime(String startTime) { this.startTime = startTime; } public void setWeight(int weight) { this.weight = weight; } }
buiduchuy/fts-g1-fuhcm
Code/Owner/OwnerApp/src/vn/edu/fpt/fts/classes/Route.java
Java
gpl-2.0
2,967
package com.lanyuan.mapper.base; import java.util.List; /** * 已经实现民基本的 增,删,改,查接口,不需要重复写 * 所有mapper都继承这个BaseMapper * @author lanyuan * @date 2015-4-26 * @Email: mmm333zzz520@163.com * @version 3.0v */ public interface BaseMapper { /** * 1:传入继承FormMap的子类对象,返回是一个List<T>集合<br/> * 2:调用findByPage接口,必须传入PageView对象! formMap.set("paging", pageView);<br/> * 1:根据多字段分页查询 <br/> * 3:如果是多个id,用","组成字符串. <br/> * 4:formMap.put("id","xxx") 或 formMap.put("id","xxx,xxx,xxx") <br/> * 5:formMap.put("name","xxx") 或 formMap.put("name","xxx,xxx,xxx") <br/> * 6:兼容模糊查询。 formMap.put("name","用户%") 或 formMap.put("name","%用户%") <br/> * 7:兼容排序查询 : formMap.put("$orderby","order by id desc"); * <b>author:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplanyuan</b><br/> * <b>date:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-26</b><br/> * <b>version:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b> * * @return <T> List<T> */ public <T> List<T> findByPage(T formMap); /** * * 1:自定义where查询条件,传入继承FormMap的子类对象,返回是一个List<T>集合<br/> * 2:返回查询条件数据,如不传入.则返回所有数据..如果附加条件.如下 <br/> * 3:formMap.put('where","id=XX and name= XX order by XX") <br/> * <b>author:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplanyuan</b><br/> * <b>date:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-26</b><br/> * <b>version:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b> * * @return <T> List<T> */ public <T> List<T> findByWhere(T formMap); /** * 1:更新数据<br/> * 2:传入继承FormMap的子类对象<br/> * <b>author:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplanyuan</b><br/> * <b>date:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-26</b><br/> * <b>version:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b> * * @return formMap * @throws Exception */ public void editEntity(Object formMap) throws Exception; /** * 1:根据多字段查询 <br/> * 2:传入继承FormMap的子类对象 <br/> * 3:如果是多个id,用","组成字符串. <br/> * 4:formMap.put("id","xxx") 或 formMap.put("id","xxx,xxx,xxx") <br/> * 5:formMap.put("name","xxx") 或 formMap.put("name","xxx,xxx,xxx") <br/> * 6:兼容模糊查询。 formMap.put("name","用户%") 或 formMap.put("name","%用户%") <br/> * 7:兼容排序查询 : formMap.put("$orderby","order by id desc"); * <b>author:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplanyuan</b><br/> * <b>date:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-26</b><br/> * <b>version:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b> * * @return List<T> */ public <T> List<T> findByNames(T formMap); /** * 1:根据某个字段查询数据 <br/> * <b>author:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplanyuan</b><br/> * <b>date:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-26</b><br/> * <b>version:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b> * * @return <T> List<T> */ public <T> List<T> findByAttribute(String key, String value, Class<T> clazz); /** * 1:根据某个字段删除数据 <br/> * <b>author:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplanyuan</b><br/> * <b>date:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-26</b><br/> * <b>version:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b> * * @throws Exception */ public void deleteByAttribute(String key, String value, Class clazz) throws Exception; /** * 1:传入继承FormMap的子类对象 <br/> * 2:保存数据,保存数据后返回子类对象的所有数据包括id..主建统一返回为id <br/> * <b>author:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplanyuan</b><br/> * <b>date:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-26</b><br/> * <b>version:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b> * * @throws Exception */ public void addEntity(Object formMap) throws Exception; /** * 1:批量保存数据,如果是mysql,在驱动连接加上&allowMultiQueries=true这个参数 <br/> * 2:传入继承FormMap的子类对象的一个list集合 <br/> * <b>author:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplanyuan</b><br/> * <b>date:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-26</b><br/> * <b>version:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b> * * @throws Exception */ @SuppressWarnings("rawtypes") public void batchSave(List formMap) throws Exception; /** * 1:根据多个字段删除 ,传入继承FormMap的子类对象<br/> * 2:如果是多个id值,用","组成字符串. <br/> * 3:formMap.put("id","xxx") 或 formMap.put("id","xxx,xxx,xxx")<br/> * 4:formMap.put("name","xxx") 或 formMap.put("name","xxx,xxx,xxx") <br/> * <b>author:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplanyuan</b><br/> * <b>date:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-26</b><br/> * <b>version:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b> * * @throws Exception */ public void deleteByNames(Object formMap) throws Exception; /** * 1:根据某个字段查询数据,返回一个对象,如果返回多个值,则异常 <br/> * <b>author:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplanyuan</b><br/> * <b>date:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-04-26</b><br/> * <b>version:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp3.0v</b> */ public <T> T findbyFrist(String key,String value,Class<T> clazz); /** * 1:获取表字段存在放缓存 <br/> * <b>author:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsplanyuan</b><br/> * <b>date:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp2015-12-01</b><br/> * <b>version:</b><br/> * <b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp4.0v</b> * * @return List<Map<?, ?>> */ public <T> List<T> initTableField(T formMap); }
xiaoweige1101/chuangyeyuan
src/main/java/com/lanyuan/mapper/base/BaseMapper.java
Java
gpl-2.0
6,568
// RU KOI8-R lang variables tinyMCE.addToLang('',{ paste_text_desc : '÷ÓÔÁ×ÉÔØ ËÁË ÐÒÏÓÔÏÊ ÔÅËÓÔ', paste_text_title : 'éÓÐÏÌØÚÕÊÔÅ CTRL+V ÄÌÑ ×ÓÔÁ×ËÉ ÔÅËÓÔÁ × ÏËÏÛËÏ.', paste_text_linebreaks : 'óÏÈÒÁÎÉÔØ ÐÅÒÅÎÏÓÙ ÓÔÒÏË', paste_word_desc : '÷ÓÔÁ×ÉÔØ ÉÚ Word', paste_word_title : 'éÓÐÏÌØÚÕÊÔÅ CTRL+V ÄÌÑ ×ÓÔÁ×ËÉ ÔÅËÓÔÁ × ÏËÏÛËÏ.', selectall_desc : '÷ÙÄÅÌÉÔØ ×Ó£' });
pzingg/saugus_elgg
_tinymce/jscripts/tiny_mce/plugins/paste/langs/ru_KOI8-R.js
JavaScript
gpl-2.0
376
/*************************************************************************** * (C) Copyright 2003-2012 - Stendhal * *************************************************************************** *************************************************************************** * * * 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. * * * ***************************************************************************/ package games.stendhal.server.core.scripting; import games.stendhal.server.entity.player.Player; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.List; import org.apache.log4j.Logger; /** * Manager for scripts written in Java. * * @author hendrik */ public class ScriptInJava extends ScriptingSandbox { private static Logger logger = Logger.getLogger(ScriptInJava.class); private Script script; private final String classname; /** * Creates a new script written in Java. * * @param scriptname Name of the script */ public ScriptInJava(final String scriptname) { super(scriptname); this.classname = "games.stendhal.server.script." + scriptname.substring(0, scriptname.length() - 6); } /** * Creates a new instance of this script. * * @throws MalformedURLException * @throws ClassNotFoundException * @throws SecurityException * @throws NoSuchMethodException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException * @throws InstantiationException */ private void newInstance() throws MalformedURLException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { // Create new class loader // with current dir as CLASSPATH final File file = new File("./data/script"); final ClassLoader loader = new URLClassLoader(new URL[] { file.toURI().toURL() }); // load class through new loader final Class< ? > aClass = loader.loadClass(classname); script = (Script) aClass.newInstance(); } /** * Initial load of this script. * * @param admin * the admin who load it or <code>null</code> on server start. * @param args * the arguments the admin specified or <code>null</code> on * server start. */ @Override public boolean load(final Player admin, final List<String> args) { final Class< ? >[] signature = new Class< ? >[] { Player.class, List.class, ScriptingSandbox.class }; final Object[] params = new Object[] { admin, args, this }; try { newInstance(); final Method[] methods = Script.class.getMethods(); for (final Method method : methods) { logger.debug(method); } final Method theMethod = Script.class.getMethod("load", signature); theMethod.invoke(script, params); } catch (final Exception e) { logger.debug(e, e); setMessage(e.toString()); return false; } return true; } @Override public boolean execute(final Player admin, final List<String> args) { final Class< ? >[] signature = new Class[] { Player.class, List.class }; final Object[] params = new Object[] { admin, args }; if (script == null) { return false; } try { preExecute(admin, args); final Method theMethod = script.getClass().getMethod("execute", signature); theMethod.invoke(script, params); } catch (final Exception e) { logger.error(e, e); setMessage(e.getMessage()); postExecute(admin, args, false); return false; } catch (final Error e) { logger.error(e, e); setMessage(e.getMessage()); postExecute(admin, args, false); return false; } postExecute(admin, args, true); return true; } /** * Executes this script. * * @param admin * the admin who load it or <code>null</code> on server start. * @param args * the arguments the admin specified or <code>null</code> on * server start. */ @Override public void unload(final Player admin, final List<String> args) { final Class< ? >[] signature = new Class< ? >[] { Player.class, List.class }; final Object[] params = new Object[] { admin, args }; try { final Method theMethod = script.getClass().getMethod("unload", signature); theMethod.invoke(script, params); } catch (final Exception e) { logger.error(e, e); setMessage(e.getMessage()); } super.unload(admin, args); } }
acsid/stendhal
src/games/stendhal/server/core/scripting/ScriptInJava.java
Java
gpl-2.0
4,942
<?php /******************************************************************************* ******************************************************************************* ** ** ** ** ** Copyright 2015-2017 JK Technosoft ** ** http://www.jktech.com ** ** ** ** ProActio 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; either version 2 of the License, or ** ** at your option) any later version. ** ** ** ** ProActio 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. ** ** ** ** See TNC.TXT for more information regarding the Terms and Conditions ** ** of use and alternative licensing options for this software. ** ** ** ** A copy of the GPL is in GPL.TXT which was provided with this package. ** ** ** ** See http://www.fsf.org for more information about the GPL. ** ** ** ** ** ******************************************************************************* ******************************************************************************* * * {program name} * * Known Bugs & Issues: * * * Author: * * JK Technosoft * http://www.jktech.com * August 11, 2015 * * * History: * */ include('profile.php'); $current=$_SESSION['dbid'];?> <div class="pad"> <div class="container"> <div class="row"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title"> <p>Disk Utilization</p></h3> </div> <div class="panel-body"> <table data-toggle="table" data-url="ajax/diskutil.php" data-query-params="queryParams" data-show-export="true" data-sort-order="desc" data-show-refresh="true" data-pagination="true" data-search="true" data-show-columns="true" id="tab1" > <thead> <tr> <th data-field="FILESYSTEM" > FILESYSTEM </th> <th data-field="1KBLOCKS" > SIZE (KB) </th> <th data-field="USED" > USED (KB) </th> <th data-field="AVAILABLE" > AVAILABLE (KB) </th> <th data-field="USED%" > USED % </th> <th data-field="MOUNTED" > MOUNTED ON </th> </tr> </thead> </table> </div> </div> </div> </div> </div> <script> $('#tab1').bootstrapTable({ formatNoMatches: function () { return '<img src="images/serverinaccessible.gif"></img>'; }, formatLoadingMessage: function () { return '<img src="/images/connectingser.gif"></img>'; } }); function queryParams() { return { dbuid:<?php echo "'$current'" ;?> }; } </script>
JKT-OSSCLUB/ProActio
Proactio Front/www/diskutil.php
PHP
gpl-2.0
3,799
/* mkvmerge -- utility for splicing together matroska files from component media subtypes Distributed under the GPL v2 see the file COPYING for details or visit http://www.gnu.org/copyleft/gpl.html definitions used in all programs, helper functions Written by Moritz Bunkus <moritz@bunkus.org>. */ #include "common/common_pch.h" #include <algorithm> #include <cstring> #ifdef SYS_WINDOWS # include <windows.h> #endif #include "common/command_line.h" #include "common/hacks.h" #include "common/json.h" #include "common/mm_io_x.h" #include "common/mm_write_buffer_io.h" #include "common/strings/editing.h" #include "common/strings/utf8.h" #include "common/translation.h" #include "common/version.h" namespace mtx { namespace cli { bool g_gui_mode = false; /** \brief Reads command line arguments from a file Each line contains exactly one command line argument or a comment. Arguments are converted to UTF-8 and appended to the array \c args. */ static void read_args_from_old_option_file(std::vector<std::string> &args, std::string const &filename) { mm_text_io_cptr mm_io; std::string buffer; bool skip_next; try { mm_io = std::make_shared<mm_text_io_c>(new mm_file_io_c(filename)); } catch (mtx::mm_io::exception &ex) { mxerror(boost::format(Y("The file '%1%' could not be opened for reading: %2%.\n")) % filename % ex); } skip_next = false; while (!mm_io->eof() && mm_io->getline2(buffer)) { if (skip_next) { skip_next = false; continue; } strip(buffer); if (buffer == "#EMPTY#") { args.push_back(""); continue; } if ((buffer[0] == '#') || (buffer[0] == 0)) continue; if (buffer == "--command-line-charset") { skip_next = true; continue; } args.push_back(unescape(buffer)); } } static void read_args_from_json_file(std::vector<std::string> &args, std::string const &filename) { std::string buffer; try { auto io = std::make_shared<mm_text_io_c>(new mm_file_io_c(filename)); io->read(buffer, io->get_size()); } catch (mtx::mm_io::exception &ex) { mxerror(boost::format(Y("The file '%1%' could not be opened for reading: %2%.\n")) % filename % ex); } try { auto doc = mtx::json::parse(buffer); auto skip_next = false; if (!doc.is_array()) throw std::domain_error{Y("JSON option files must contain a JSON array consisting solely of JSON strings")}; for (auto const &val : doc) { if (!val.is_string()) throw std::domain_error{Y("JSON option files must contain a JSON array consisting solely of JSON strings")}; if (skip_next) { skip_next = false; continue; } auto string = val.get<std::string>(); if (string == "--command-line-charset") skip_next = true; else args.push_back(string); } } catch (std::exception const &ex) { mxerror(boost::format("The JSON option file '%1%' contains an error: %2%.\n") % filename % ex.what()); } } static void read_args_from_file(std::vector<std::string> &args, std::string const &filename) { auto path = bfs::path{filename}; if (balg::to_lower_copy(path.extension().string()) == ".json") read_args_from_json_file(args, filename); else read_args_from_old_option_file(args, filename); } static std::vector<std::string> command_line_args_from_environment() { std::vector<std::string> all_args; auto process = [&all_args](std::string const &variable) { auto value = getenv((boost::format("%1%_OPTIONS") % variable).str().c_str()); if (value && value[0]) { auto args = split(value, " "); std::transform(args.begin(), args.end(), std::back_inserter(all_args), unescape); } }; process("MKVTOOLNIX"); process("MTX"); process(balg::to_upper_copy(get_program_name())); return all_args; } /** \brief Expand the command line parameters Takes each command line paramter, converts it to UTF-8, and reads more commands from command files if the argument starts with '@'. Puts all arguments into a new array. On Windows it uses the \c GetCommandLineW() function. That way it can also handle multi-byte input like Japanese file names. \param argc The number of arguments. This is the same argument that \c main normally receives. \param argv The arguments themselves. This is the same argument that \c main normally receives. \return An array of strings converted to UTF-8 containing all the command line arguments and any arguments read from option files. */ #if !defined(SYS_WINDOWS) std::vector<std::string> args_in_utf8(int argc, char **argv) { int i; std::vector<std::string> args = command_line_args_from_environment(); charset_converter_cptr cc_command_line = g_cc_stdio; for (i = 1; i < argc; i++) if (argv[i][0] == '@') read_args_from_file(args, &argv[i][1]); else { if (!strcmp(argv[i], "--command-line-charset")) { if ((i + 1) == argc) mxerror(Y("'--command-line-charset' is missing its argument.\n")); cc_command_line = charset_converter_c::init(!argv[i + 1] ? "" : argv[i + 1]); i++; } else args.push_back(cc_command_line->utf8(argv[i])); } return args; } #else // !defined(SYS_WINDOWS) std::vector<std::string> args_in_utf8(int, char **) { std::vector<std::string> args = command_line_args_from_environment(); std::string utf8; int num_args = 0; LPWSTR *arg_list = CommandLineToArgvW(GetCommandLineW(), &num_args); if (!arg_list) return args; int i; for (i = 1; i < num_args; i++) { auto arg = to_utf8(std::wstring{arg_list[i]}); if (arg[0] == '@') read_args_from_file(args, arg.substr(1)); else args.push_back(arg); } LocalFree(arg_list); return args; } #endif // !defined(SYS_WINDOWS) std::string g_usage_text, g_version_info; /** Handle command line arguments common to all programs Iterates over the list of command line arguments and handles the ones that are common to all programs. These include --output-charset, --redirect-output, --help, --version and --verbose along with their short counterparts. \param args A vector of strings containing the command line arguments. The ones that have been handled are removed from the vector. \param redirect_output_short The name of the short option that is recognized for --redirect-output. If left empty then no short version is accepted. \returns \c true if the locale has changed and the function should be called again and \c false otherwise. */ bool handle_common_args(std::vector<std::string> &args, const std::string &redirect_output_short) { size_t i = 0; while (args.size() > i) { if (args[i] == "--debug") { if ((i + 1) == args.size()) mxerror("Missing argument for '--debug'.\n"); debugging_c::request(args[i + 1]); args.erase(args.begin() + i, args.begin() + i + 2); } else if (args[i] == "--engage") { if ((i + 1) == args.size()) mxerror(Y("'--engage' lacks its argument.\n")); engage_hacks(args[i + 1]); args.erase(args.begin() + i, args.begin() + i + 2); } else if (args[i] == "--gui-mode") { g_gui_mode = true; args.erase(args.begin() + i, args.begin() + i + 1); } else ++i; } // First see if there's an output charset given. i = 0; while (args.size() > i) { if (args[i] == "--output-charset") { if ((i + 1) == args.size()) mxerror(Y("Missing argument for '--output-charset'.\n")); set_cc_stdio(args[i + 1]); args.erase(args.begin() + i, args.begin() + i + 2); } else ++i; } // Now let's see if the user wants the output redirected. i = 0; while (args.size() > i) { if ((args[i] == "--redirect-output") || (args[i] == "-r") || ((redirect_output_short != "") && (args[i] == redirect_output_short))) { if ((i + 1) == args.size()) mxerror(boost::format(Y("'%1%' is missing the file name.\n")) % args[i]); try { if (!stdio_redirected()) { mm_io_cptr file = mm_write_buffer_io_c::open(args[i + 1], 128 * 1024); file->write_bom(g_stdio_charset); redirect_stdio(file); } args.erase(args.begin() + i, args.begin() + i + 2); } catch(mtx::mm_io::exception &) { mxerror(boost::format(Y("Could not open the file '%1%' for directing the output.\n")) % args[i + 1]); } } else ++i; } // Check for the translations to use (if any). i = 0; while (args.size() > i) { if (args[i] == "--ui-language") { if ((i + 1) == args.size()) mxerror(Y("Missing argument for '--ui-language'.\n")); if (args[i + 1] == "list") { mxinfo(Y("Available translations:\n")); std::vector<translation_c>::iterator translation = translation_c::ms_available_translations.begin(); while (translation != translation_c::ms_available_translations.end()) { mxinfo(boost::format(" %1% (%2%)\n") % translation->get_locale() % translation->m_english_name); ++translation; } mxexit(); } if (-1 == translation_c::look_up_translation(args[i + 1])) mxerror(boost::format(Y("There is no translation available for '%1%'.\n")) % args[i + 1]); init_locales(args[i + 1]); args.erase(args.begin() + i, args.begin() + i + 2); return true; } else ++i; } // Last find the --help, --version, --check-for-updates arguments. i = 0; while (args.size() > i) { if ((args[i] == "-V") || (args[i] == "--version")) { mxinfo(boost::format("%1%\n") % g_version_info); mxexit(); } else if ((args[i] == "-v") || (args[i] == "--verbose")) { ++verbose; args.erase(args.begin() + i, args.begin() + i + 1); } else if ((args[i] == "-q") || (args[i] == "--quiet")) { verbose = 0; g_suppress_info = true; args.erase(args.begin() + i, args.begin() + i + 1); } else if ((args[i] == "-h") || (args[i] == "-?") || (args[i] == "--help")) display_usage(); else ++i; } return false; } void display_usage(int exit_code) { mxinfo(boost::format("%1%\n") % g_usage_text); mxexit(exit_code); } }}
timeraider4u/mkvtoolnix
src/common/command_line.cpp
C++
gpl-2.0
10,436
 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Ombi.Helpers; using TraktSharp; using TraktSharp.Entities; using TraktSharp.Enums; namespace Ombi.Api.Trakt { public class TraktApi : ITraktApi { private TraktClient Client { get; } private static readonly string Encrypted = "MTM0ZTU2ODM1MGY3NDI3NTExZTI1N2E2NTM0MDI2NjYwNDgwY2Y5YjkzYzc3ZjczNzhmMzQwNjAzYjY3MzgxZA=="; private readonly string _apiKey = StringCipher.DecryptString(Encrypted, "ApiKey"); public TraktApi() { Client = new TraktClient { Authentication = { ClientId = _apiKey, ClientSecret = "7beeb6f1c0c842341f6bd285adb86200cb810e431fff0a8a1ed7158af4cffbbb" } }; } public async Task<IEnumerable<TraktShow>> GetPopularShows(int? page = null, int? limitPerPage = null) { var popular = await Client.Shows.GetPopularShowsAsync(TraktExtendedOption.Full, page, limitPerPage); return popular; } public async Task<IEnumerable<TraktShow>> GetTrendingShows(int? page = null, int? limitPerPage = null) { var trendingShowsTop10 = await Client.Shows.GetTrendingShowsAsync(TraktExtendedOption.Full, page, limitPerPage); return trendingShowsTop10.Select(x => x.Show); } public async Task<IEnumerable<TraktShow>> GetAnticipatedShows(int? page = null, int? limitPerPage = null) { var anticipatedShows = await Client.Shows.GetAnticipatedShowsAsync(TraktExtendedOption.Full, page, limitPerPage); return anticipatedShows.Select(x => x.Show); } public async Task<TraktShow> GetTvExtendedInfo(string imdbId) { try { return await Client.Shows.GetShowAsync(imdbId, TraktExtendedOption.Full); } catch (Exception e) { // Ignore the exception since the information returned from this API is optional. Console.WriteLine($"Failed to retrieve extended tv information from Trakt. IMDbId: '{imdbId}'."); Console.WriteLine(e); } return null; } } }
tidusjar/Ombi
src/Ombi.Api.Trakt/TraktApi.cs
C#
gpl-2.0
2,341
<?php /** * @package Joomla.Platform * @subpackage User * * @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; jimport('joomla.access.access'); jimport('joomla.registry.registry'); /** * User class. Handles all application interaction with a user * * @package Joomla.Platform * @subpackage User * @since 11.1 */ class JUser extends JObject { /** * A cached switch for if this user has root access rights. * @var boolean */ protected $isRoot = null; /** * Unique id * @var int */ public $id = null; /** * The users real name (or nickname) * @var string */ public $name = null; /** * The login name * @var string */ public $username = null; /** * The email * @var string */ public $email = null; /** * MD5 encrypted password * @var string */ public $password = null; /** * Clear password, only available when a new password is set for a user * @var string */ public $password_clear = ''; /** * Description * @var string */ public $usertype = null; /** * Description * @var int */ public $block = null; /** * Description * @var int */ public $sendEmail = null; /** * Description * @var datetime */ public $registerDate = null; /** * Description * @var datetime */ public $lastvisitDate = null; /** * Description * @var string activation hash */ public $activation = null; /** * Description * @var string */ public $params = null; /** * Associative array of user names => group ids * * @since 11.1 * @var array */ public $groups = array(); /** * Description * @var boolean */ public $guest = null; /** * User parameters * @var object */ protected $_params = null; /** * Authorised access groups * @var array */ protected $_authGroups = null; /** * Authorised access levels * @var array */ protected $_authLevels = null; /** * Authorised access actions * @var array */ protected $_authActions = null; /** * Error message * @var string */ protected $_errorMsg = null; /** * Constructor activating the default information of the language * * @param integer $identifier The primary key of the user to load (optional). * * @return object JUser * @since 11.1 */ public function __construct($identifier = 0) { // Create the user parameters object $this->_params = new JRegistry; // Load the user if it exists if (!empty($identifier)) { $this->load($identifier); } else { //initialise $this->id = 0; $this->sendEmail = 0; $this->aid = 0; $this->guest = 1; } } /** * Returns the global User object, only creating it if it * doesn't already exist. * * @param integer $identifier The user to load - Can be an integer or string - If string, it is converted to ID automatically. * * @return object JUser The User object. * @since 11.1 */ public static function getInstance($identifier = 0) { static $instances; if (!isset ($instances)) { $instances = array (); } // Find the user id if (!is_numeric($identifier)) { jimport('joomla.user.helper'); if (!$id = JUserHelper::getUserId($identifier)) { JError::raiseWarning('SOME_ERROR_CODE', JText::sprintf('JLIB_USER_ERROR_ID_NOT_EXISTS', $identifier)); $retval = false; return $retval; } } else { $id = $identifier; } if (empty($instances[$id])) { $user = new JUser($id); $instances[$id] = $user; } return $instances[$id]; } /** * Method to get a parameter value * * @param string $key Parameter key * @param mixed $default Parameter default value * * @return mixed The value or the default if it did not exist * @since 11.1 */ public function getParam($key, $default = null) { return $this->_params->get($key, $default); } /** * Method to set a parameter * * @param string $key Parameter key * @param mixed $value Parameter value * * @return mixed Set parameter value * @since 11.1 */ public function setParam($key, $value) { return $this->_params->set($key, $value); } /** * Method to set a default parameter if it does not exist * * @param string $key Parameter key * @param mixed $value Parameter value * * @return mixed Set parameter value * @since 11.1 */ public function defParam($key, $value) { return $this->_params->def($key, $value); } /** * @deprecated 1.6 Use the authorise method instead. */ public function authorize($action, $assetname = null) { return $this->authorise($action, $assetname); } /** * Method to check JUser object authorisation against an access control * object and optionally an access extension object * * @param string $action The name of the action to check for permission. * @param string $assetname The name of the asset on which to perform the action. * * @return boolean True if authorised * @since 11.1 */ public function authorise($action, $assetname = null) { // Make sure we only check for core.admin once during the run. if ($this->isRoot === null) { $this->isRoot = false; // Check for the configuration file failsafe. $config = JFactory::getConfig(); $rootUser = $config->get('root_user'); // The root_user variable can be a numeric user ID or a username. if (is_numeric($rootUser) && $this->id > 0 && $this->id == $rootUser) { $this->isRoot = true; } else if ($this->username && $this->username == $rootUser) { $this->isRoot = true; } else { // Get all groups against which the user is mapped. $identities = $this->getAuthorisedGroups(); array_unshift($identities, $this->id * -1); if (JAccess::getAssetRules(1)->allow('core.admin', $identities)) { $this->isRoot = true; return true; } } } return $this->isRoot ? true : JAccess::check($this->id, $action, $assetname); } /** * @deprecated 1.6 Use the getAuthorisedViewLevels method instead. */ public function authorisedLevels() { return $this->getAuthorisedViewLevels(); } /** * Method to return a list of all categories that a user has permission for a given action * * @param string $component The component from which to retrieve the categories * @param string $action The name of the section within the component from which to retrieve the actions. * * @return array List of categories that this group can do this action to (empty array if none). Categories must be published. * @since 11.1 */ public function getAuthorisedCategories($component, $action) { // Brute force method: get all published category rows for the component and check each one // TODO: Modify the way permissions are stored in the db to allow for faster implementation and better scaling $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select('c.id AS id, a.name as asset_name') ->from('#__categories c') ->innerJoin('#__assets a ON c.asset_id = a.id') ->where('c.extension = ' . $db->quote($component)) ->where('c.published = 1'); $db->setQuery($query); $allCategories = $db->loadObjectList('id'); $allowedCategories = array(); foreach ($allCategories as $category) { if ($this->authorise($action, $category->asset_name)) { $allowedCategories[] = (int) $category->id; } } return $allowedCategories; } /** * Gets an array of the authorised access levels for the user * * @return array * @since 11.1 */ public function getAuthorisedViewLevels() { if ($this->_authLevels === null) { $this->_authLevels = array(); } if (empty($this->_authLevels)) { $this->_authLevels = JAccess::getAuthorisedViewLevels($this->id); } return $this->_authLevels; } /** * Gets an array of the authorised user groups * * @return array * @since 11.1 */ public function getAuthorisedGroups() { if ($this->_authGroups === null) { $this->_authGroups = array(); } if (empty($this->_authGroups)) { $this->_authGroups = JAccess::getGroupsByUser($this->id); } return $this->_authGroups; } /** * Pass through method to the table for setting the last visit date * * @param integer $timestamp The timestamp, defaults to 'now'. * * @return boolean True on success. * @since 11.1 */ public function setLastVisit($timestamp = null) { // Create the user table object $table = $this->getTable(); $table->load($this->id); return $table->setLastVisit($timestamp); } /** * Method to get the user parameters * * This function tries to load an XML file based on the users usertype. The filename of the xml * file is the same as the usertype. The functionals has a static variable to store the parameters * setup file base path. You can call this function statically to set the base path if needed. * * @param boolean $loadsetupfile If true, loads the parameters setup file. Default is false. * @param path $path Set the parameters setup file base path to be used to load the user parameters. * * @return object The user parameters object. * @since 11.1 */ public function getParameters($loadsetupfile = false, $path = null) { static $parampath; // Set a custom parampath if defined if (isset($path)) { $parampath = $path; } // Set the default parampath if not set already if (!isset($parampath)) { $parampath = JPATH_ADMINISTRATOR.'components/com_users/models'; } if ($loadsetupfile) { $type = str_replace(' ', '_', strtolower($this->usertype)); $file = $parampath.'/'.$type.'.xml'; if (!file_exists($file)) { $file = $parampath.'/'.'user.xml'; } $this->_params->loadSetupFile($file); } return $this->_params; } /** * Method to get the user parameters * * @param object $params The user parameters object * * @return void * @since 11.1 */ public function setParameters($params) { $this->_params = $params; } /** * Method to get the user table object * * This function uses a static variable to store the table name of the user table to * it instantiates. You can call this function statically to set the table name if * needed. * * @param string $type The user table name to be used * @param string $prefix The user table prefix to be used * * @return object The user table object * @since 11.1 */ public static function getTable($type = null, $prefix = 'JTable') { static $tabletype; // Set the default tabletype; if (!isset($tabletype)) { $tabletype['name'] = 'user'; $tabletype['prefix'] = 'JTable'; } // Set a custom table type is defined if (isset($type)) { $tabletype['name'] = $type; $tabletype['prefix'] = $prefix; } // Create the user table object return JTable::getInstance($tabletype['name'], $tabletype['prefix']); } /** * Method to bind an associative array of data to a user object * * @param array $array The associative array to bind to the object * * @return boolean True on success * @since 11.1 */ public function bind(& $array) { jimport('joomla.user.helper'); // Let's check to see if the user is new or not if (empty($this->id)) { // Check the password and create the crypted password if (empty($array['password'])) { $array['password'] = JUserHelper::genRandomPassword(); $array['password2'] = $array['password']; } // TODO: Backend controller checks the password, frontend doesn't but should. // Hence this code is required: if (isset($array['password2']) && $array['password'] != $array['password2']) { $this->setError(JText::_('JLIB_USER_ERROR_PASSWORD_NOT_MATCH')); return false; } $this->password_clear = JArrayHelper::getValue($array, 'password', '', 'string'); $salt = JUserHelper::genRandomPassword(32); $crypt = JUserHelper::getCryptedPassword($array['password'], $salt); $array['password'] = $crypt.':'.$salt; // Set the registration timestamp $this->set('registerDate', JFactory::getDate()->toMySQL()); // Check that username is not greater than 150 characters $username = $this->get('username'); if (strlen($username) > 150) { $username = substr($username, 0, 150); $this->set('username', $username); } // Check that password is not greater than 100 characters $password = $this->get('password'); if (strlen($password) > 100) { $password = substr($password, 0, 100); $this->set('password', $password); } } else { // Updating an existing user if (!empty($array['password'])) { if ($array['password'] != $array['password2']) { $this->setError(JText::_('JLIB_USER_ERROR_PASSWORD_NOT_MATCH')); return false; } $this->password_clear = JArrayHelper::getValue($array, 'password', '', 'string'); $salt = JUserHelper::genRandomPassword(32); $crypt = JUserHelper::getCryptedPassword($array['password'], $salt); $array['password'] = $crypt.':'.$salt; } else { $array['password'] = $this->password; } } // TODO: this will be deprecated as of the ACL implementation // $db = JFactory::getDbo(); if (array_key_exists('params', $array)) { $params = ''; $this->_params->loadArray($array['params']); if (is_array($array['params'])) { $params = (string)$this->_params; } else { $params = $array['params']; } $this->params = $params; } // Bind the array if (!$this->setProperties($array)) { $this->setError(JText::_('JLIB_USER_ERROR_BIND_ARRAY')); return false; } // Make sure its an integer $this->id = (int) $this->id; return true; } /** * Method to save the JUser object to the database * * @param boolean $updateOnly Save the object only if not a new user * * @return boolean True on success * @since 11.1 */ public function save($updateOnly = false) { // NOTE: $updateOnly is currently only used in the user reset password method. // Create the user table object $table = $this->getTable(); $this->params = (string) $this->_params; $table->bind($this->getProperties()); // Allow an exception to be thrown. try { // Check and store the object. if (!$table->check()) { $this->setError($table->getError()); return false; } // If user is made a Super Admin group and user is NOT a Super Admin // // @todo ACL - this needs to be acl checked // $my = JFactory::getUser(); //are we creating a new user $isNew = empty($this->id); // If we aren't allowed to create new users return if ($isNew && $updateOnly) { return true; } // Get the old user $oldUser = new JUser($this->id); // // Access Checks // // The only mandatory check is that only Super Admins can operate on other Super Admin accounts. // To add additional business rules, use a user plugin and throw an Exception with onUserBeforeSave. // Check if I am a Super Admin $iAmSuperAdmin = $my->authorise('core.admin'); // We are only worried about edits to this account if I am not a Super Admin. if ($iAmSuperAdmin != true) { if ($isNew) { // Check if the new user is being put into a Super Admin group. foreach ($this->groups as $key => $groupId) { if (JAccess::checkGroup($groupId, 'core.admin')) { throw new Exception(JText::_('JLIB_USER_ERROR_NOT_SUPERADMIN')); } } } else { // I am not a Super Admin, and this one is, so fail. if (JAccess::check($this->id, 'core.admin')) { throw new Exception(JText::_('JLIB_USER_ERROR_NOT_SUPERADMIN')); } if ($this->groups != null) { // I am not a Super Admin and I'm trying to make one. foreach ($this->groups as $groupId) { if (JAccess::checkGroup($groupId, 'core.admin')) { throw new Exception(JText::_('JLIB_USER_ERROR_NOT_SUPERADMIN')); } } } } } // Fire the onUserBeforeSave event. JPluginHelper::importPlugin('user'); $dispatcher = JDispatcher::getInstance(); $result = $dispatcher->trigger('onUserBeforeSave', array($oldUser->getProperties(), $isNew, $this->getProperties())); if (in_array(false, $result, true)) { // Plugin will have to raise it's own error or throw an exception. return false; } // Store the user data in the database if (!($result = $table->store())) { throw new Exception($table->getError()); } // Set the id for the JUser object in case we created a new user. if (empty($this->id)) { $this->id = $table->get('id'); } if ($my->id == $table->id) { $registry = new JRegistry; $registry->loadJSON($table->params); $my->setParameters($registry); } // Fire the onAftereStoreUser event $dispatcher->trigger('onUserAfterSave', array($this->getProperties(), $isNew, $result, $this->getError())); } catch (Exception $e) { $this->setError($e->getMessage()); return false; } return $result; } /** * Method to delete the JUser object from the database * * @return boolean True on success * @since 11.1 */ public function delete() { JPluginHelper::importPlugin('user'); // Trigger the onUserBeforeDelete event $dispatcher = JDispatcher::getInstance(); $dispatcher->trigger('onUserBeforeDelete', array($this->getProperties())); // Create the user table object $table = $this->getTable(); $result = false; if (!$result = $table->delete($this->id)) { $this->setError($table->getError()); } // Trigger the onUserAfterDelete event $dispatcher->trigger('onUserAfterDelete', array($this->getProperties(), $result, $this->getError())); return $result; } /** * Method to load a JUser object by user id number * * @param mixed $id The user id of the user to load * * @return boolean True on success * @since 11.1 */ public function load($id) { // Create the user table object $table = $this->getTable(); // Load the JUserModel object based on the user id or throw a warning. if (!$table->load($id)) { JError::raiseWarning('SOME_ERROR_CODE', JText::sprintf('JLIB_USER_ERROR_UNABLE_TO_LOAD_USER', $id)); return false; } // Set the user parameters using the default XML file. We might want to // extend this in the future to allow for the ability to have custom // user parameters, but for right now we'll leave it how it is. $this->_params->loadJSON($table->params); // Assuming all is well at this point lets bind the data $this->setProperties($table->getProperties()); return true; } }
Macsmice/Tamka
libraries/overrides/user/user.php
PHP
gpl-2.0
18,780
<?php /** * @package akeebainstaller * @copyright Copyright (C) 2009-2013 Nicholas K. Dionysopoulos. All rights reserved. * @author Nicholas K. Dionysopoulos - http://www.dionysopoulos.me * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL v3 or later * * Akeeba Backup Installer Output: Database restoration setup */ defined('_ABI') or die('Direct access is not allowed'); global $view; extract($view); if($existing == 'backup') { $sel1 = ''; $sel2 = 'checked="checked"'; } else { $sel2 = ''; $sel1 = 'checked="checked"'; } $automation = ABIAutomation::getInstance(); ?> <script type="text/javascript" language="javascript">//<![CDATA[ $(function() { // Add the database restoration behaviour hijackDBNext(); <?php if($automation->hasAutomation()): ?> hasAutomation = true; $('#nextButton').trigger('click'); <?php elseif($showdialog): ?> var cookieName = 'abi-<?php echo md5($friendlyName) ?>'; $('#warndialog-yes') .text('<?php echo ABIText::_('YES')?>') .click(function(e){ // Clear fields $('#dbhost').val(''); $('#dbuser').val(''); $('#dbpass').val(''); $('#dbname').val(''); $('#warndialog').dialog("close"); $.cookie(cookieName, 1); return false; }); $('#warndialog-no') .text('<?php echo ABIText::_('NO')?>') .click(function(e){ // Clear fields $('#warndialog').dialog("close"); $.cookie(cookieName, 2); return false; }); if(!$.cookie(cookieName)) { $('#warndialog').dialog('open'); } else if($.cookie(cookieName) == 1) { $('#dbhost').val(''); $('#dbuser').val(''); $('#dbpass').val(''); $('#dbname').val(''); } <?php endif; ?> }); //]]></script> <div id="dialog" title="<?php echo ABIText::_('RESTORATIONPROGRESS') ?>"> <div id="progressbar"></div> <p id="progresstext"></p> <div id="dberrorhelp"> <?php echo ABIText::_('GENERIC_HELPME_CANTGETIT') ?> <a href="https://www.akeebabackup.com/documentation/troubleshooter/abidatabase.html" target="_blank"><?php echo ABIText::_('GENERIC_HELPME_CLICKHERE_TROUBLESHOOTING') ?></a> </div> </div> <div id="warndialog" title="<?php echo ABIText::_('WARNDIALOG_HEADER') ?>" style="display:none"> <h2 id="warndialog-header"><?php echo ABIText::_('WARNDIALOG_WARNING')?></h2> <p><?php echo ABIText::_('WARNDIALOG_TEXT')?></p> <p id="warndialog-buttons"> <button id="warndialog-yes">YES</button> &nbsp;&nbsp; <button id="warndialog-no">NO</button> </p> </div> <h2><?php echo ABIText::_('TITLE_DBSETUP') ?> - <?php echo $friendlyName ?></h2> <div id="accordion"> <div id="helpme"> <?php echo ABIText::_('GENERIC_HELPME_WONDERING') ?> <a href="https://www.akeebabackup.com/documentation/quick-start-guide/abi-db-restoration.html" target="_blank"><?php echo ABIText::_('GENERIC_HELPME_CLICKHERE') ?></a> </div> <h3><?php echo ABIText::_('DBBASIC') ?></h3> <div class="categoryitems"> <table> <thead> <tr> <th><?php echo ABIText::_('ITEM'); ?></th> <th><?php echo ABIText::_('VALUE'); ?></th> </tr> </thead> <tbody> <tr> <td><?php echo ABIText::_('DBTYPE') ?></td> <td> <select name="dbtype" id="dbtype"> <option value="mysql" <?php if($dbtype=="mysql") echo 'selected="selected"' ?>>mysql</option> <option value="mysqli" <?php if($dbtype=="mysqli") echo 'selected="selected"' ?>>mysqli</option> </select> </td> </tr> <tr> <td><?php echo ABIText::_('DBHOST') ?></td> <td><input type="text" name="dbhost" id="dbhost" value="<?php echo $dbhost ?>" size="30" /></td> </tr> <tr> <td><?php echo ABIText::_('DBUSER') ?></td> <td><input type="text" name="dbuser" id="dbuser" value="<?php echo $dbuser ?>" size="30" /></td> </tr> <tr> <td><?php echo ABIText::_('DBPASS') ?></td> <td><input type="password" name="dbpass" id="dbpass" value="<?php echo $dbpass ?>" size="30" /></td> </tr> <tr> <td><?php echo ABIText::_('DBDATABASE') ?></td> <td><input type="text" name="dbname" id="dbname" value="<?php echo $dbname ?>" size="30" /></td> </tr> <tr> <td colspan="2"> <span class="cantgetittowork"> <?php echo ABIText::_('GENERIC_HELPME_CANTGETIT');?> <a href="https://www.akeebabackup.com/documentation/troubleshooter/abidatabase.html" target="_blank"><?php echo ABIText::_('GENERIC_HELPME_CLICKHERE_TROUBLESHOOTING');?></a> </span> </td> </tr> </tbody> </table> </div> <h3><?php echo ABIText::_('DBADVANCED') ?></h3> <div class="categoryitems"> <table> <thead> <tr> <th><?php echo ABIText::_('ITEM'); ?></th> <th><?php echo ABIText::_('VALUE'); ?></th> </tr> </thead> <tbody> <tr> <td><?php echo ABIText::_('EXISTINGTABLES') ?></td> <td><p> <input type="radio" name="existing" value="drop" <?php echo $sel1 ?> /><?php echo ABIText::_('DROPTABLES') ?><br/> <input type="radio" name="existing" value="backup" <?php echo $sel2 ?> /><?php echo ABIText::_('BACKUPTABLES') ?> </p></td> </tr> <tr> <td><?php echo ABIText::_('PREFIX') ?></td> <td><input type="text" name="prefix" id="prefix" value="<?php echo $prefix ?>" size="30" /></td> </tr> </tbody> </table> </div> <h3><?php echo ABIText::_('DBFINETUNE') ?></h3> <div class="categoryitems"> <table> <thead> <tr> <th><?php echo ABIText::_('ITEM'); ?></th> <th><?php echo ABIText::_('VALUE'); ?></th> </tr> </thead> <tbody> <tr> <td><?php echo ABIText::_('SUPPRESFK') ?></td> <td><input type="checkbox" name="suppressfk" id="suppressfk" <?php if($suppressfk) echo 'checked="checked"' ?> /></td> </tr> <tr> <td><?php echo ABIText::_('REPLACE') ?></td> <td><input type="checkbox" name="replacesql" id="replacesql" <?php if($replacesql) echo 'checked="checked"' ?> /></td> </tr> <tr> <td><?php echo ABIText::_('FORCEUTF8') ?></td> <td><input type="checkbox" name="forceutf8" id="forceutf8" <?php if($forceutf8) echo 'checked="checked"' ?> /></td> </tr> <tr> <td><?php echo ABIText::_('MAXTIME') ?></td> <td><input type="text" name="maxtime" id="maxtime" value="<?php echo $maxtime ?>" /></td> </tr> </tbody> </table> </div> </div>
FF120/pet
installation2/includes/output/dbsetup.php
PHP
gpl-2.0
6,063
package br.ufpe.cin.pbicc.test.intents.explicit; public final class Strings { public static final String ACTION = "ACTION_VIEW"; public static final String COMPONENT = "Other"; public static final String PACKAGE_NAME = "br.ufpe.cin.pbicc.test.intents.explicit"; public static final String CLASS_NAME = "br.ufpe.cin.pbicc.test.intents.explicit.TestActivity"; }
damorim/rwsets-icc
test-data/explicit_intent_test/app/src/main/java/br/ufpe/cin/pbicc/test/intents/explicit/Strings.java
Java
gpl-2.0
376
package org.zanata.events; import lombok.Value; import org.zanata.webtrans.server.TranslationWorkspace; import org.zanata.webtrans.shared.rpc.TransUnitUpdated; /** * This event is raised in Hibernate entity listener after change has been made. * * We then gather all relevant information required for TransUnitUpdated object * creation. * * @see org.zanata.webtrans.server.HibernateIntegrator * @see org.zanata.webtrans.shared.rpc.TransUnitUpdated * @see org.zanata.webtrans.server.rpc.TransUnitUpdateHelper * @author Patrick Huang <a * href="mailto:pahuang@redhat.com">pahuang@redhat.com</a> */ @Value public class TextFlowTargetUpdatedEvent { private final TranslationWorkspace workspace; private final Long textFlowTargetId; private final TransUnitUpdated transUnitUpdated; }
Halcom/zanata-server
zanata-war/src/main/java/org/zanata/events/TextFlowTargetUpdatedEvent.java
Java
gpl-2.0
812
<?xml version="1.0" ?><!DOCTYPE TS><TS language="be" version="2.1"> <context> <name>AbstractPolyObjectFactory</name> <message> <location filename="../src/model/PolyObject.cpp" line="47"/> <source>Bowling Pin</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="60"/> <source>Skyhook</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="61"/> <source>A skyhook just hangs in the air. And you can hang a lot of weight on it!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="70"/> <source>Weight</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="48"/> <source>Bowling pins are meant to be run over—most people prefer to do that using a bowling ball.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="71"/> <source>A serious mass. It is very heavy.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="78"/> <source>Left Ramp</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="79"/> <source>This is a ramp. The left is lower than the right, so things slide to the left.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="86"/> <source>Right Ramp</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="87"/> <source>This is a ramp. The left is higher than the right, so things slide to the right.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="94"/> <source>Left Birch Wedge</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="95"/> <source>This is a movable birch wedge. The left is lower than the right, so things slide to the left.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="102"/> <source>Right Birch Wedge</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="103"/> <source>This is a movable birch wedge. The left is higher than the right, so things slide to the right.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="110"/> <source>Left Fixed Wedge</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="111"/> <source>This is an immovable wedge. The left is lower than the right, so things slide to the left.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="118"/> <source>Right Fixed Wedge</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="119"/> <source>This is an immovable wedge. The left is higher than the right, so things slide to the right.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="129"/> <location filename="../src/model/PolyObject.cpp" line="143"/> <source>This quarter arc is attached to the scene. It can&apos;t be moved, penetrated or destroyed.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="159"/> <source>Toy Chest</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="160"/> <source>Most people use a chest to keep things.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="170"/> <source>Cardboard Box</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="171"/> <source>Cardboard boxes are used to carry small and light things around.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="180"/> <source>Small Seesaw</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="181"/> <source>One usually puts toddlers on a seesaw, but they&apos;re in short supply.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="190"/> <source>Rotating Bar</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="191"/> <source>This wooden bar rotates around its center.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="128"/> <source>Quarter Arc Small</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PolyObject.cpp" line="142"/> <source>Quarter Arc Large</source> <translation type="unfinished"/> </message> </context> <context> <name>AbstractRectObjectFactory</name> <message> <location filename="../src/model/RectObject.cpp" line="53"/> <source>Wooden Bar</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="54"/> <source>Birch is a type of wood. Birch wood beams move and float.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="58"/> <source>Domino (Red)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="59"/> <source>The famous red plastic domino stone.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="64"/> <source>The famous blue plastic domino stone.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="69"/> <source>The famous green plastic domino stone.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="74"/> <source>This is the floor. It is attached to the scene and can&apos;t be moved, penetrated or destroyed.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="81"/> <source>This is a steel I-beam. Steel I-beams are large and heavy and useful to build bridges and other constructions.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="92"/> <source>This is a hammer which has been attached to the scene at the end of its handle. The hammer can be used to apply a force to some of the heavier objects.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="97"/> <source>Cola Crate</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="98"/> <source>A crate of 12 filled cola bottles. It&apos;s very heavy and hard to push around.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="63"/> <source>Domino (Blue)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="68"/> <source>Domino (Green)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="73"/> <source>Floor</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="80"/> <source>Steel I-Beam</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="85"/> <source>Wall</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="86"/> <source>This is a brick wall. It is attached to the scene and can&apos;t be moved, penetrated or destroyed.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/RectObject.cpp" line="91"/> <source>Hammer</source> <translation type="unfinished"/> </message> </context> <context> <name>ChooseLevel</name> <message> <location filename="../src/view/ChooseLevel.ui" line="14"/> <source>Choose your game!</source> <translation>Абярыце сваю гульню!</translation> </message> <message> <location filename="../src/view/ChooseLevel.ui" line="103"/> <source>Choose your next level</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ChooseLevel.ui" line="128"/> <source>Please select the level you want to play. Double-click for the post-it notes for help. </source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ChooseLevel.ui" line="148"/> <source>#</source> <translation>#</translation> </message> <message> <location filename="../src/view/ChooseLevel.ui" line="153"/> <source>Level Title</source> <translation>Назва ўзроўню</translation> </message> <message> <location filename="../src/view/ChooseLevel.ui" line="166"/> <source>Cancel</source> <translation>Скасаваць</translation> </message> <message> <location filename="../src/view/ChooseLevel.ui" line="189"/> <source>Go!</source> <translation>Наперад!</translation> </message> <message> <location filename="../src/view/ChooseLevel.cpp" line="92"/> <source>done</source> <translation>гатова</translation> </message> <message> <location filename="../src/view/ChooseLevel.cpp" line="95"/> <source>skipped</source> <translation>прапушчана</translation> </message> </context> <context> <name>ChoosePhoneNumber</name> <message> <location filename="../src/view/ChoosePhoneNumber.ui" line="20"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location filename="../src/view/ChoosePhoneNumber.ui" line="117"/> <source>Select phone to dial</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ChoosePhoneNumber.ui" line="169"/> <source>Phone Number:</source> <translation>№ тэлефону:</translation> </message> <message> <location filename="../src/view/ChoosePhoneNumber.ui" line="216"/> <source>OK</source> <translation>Добра</translation> </message> <message> <location filename="../src/view/ChoosePhoneNumber.ui" line="226"/> <source>Cancel</source> <translation>Скасаваць</translation> </message> </context> <context> <name>ChoosePhoneUndoCommand</name> <message> <location filename="../src/control/ChoosePhoneUndoCommand.cpp" line="24"/> <source>ChoosePhone</source> <translation type="unfinished"/> </message> </context> <context> <name>CircleObjectFactory</name> <message> <location filename="../src/model/CircleObjects.cpp" line="29"/> <source>Bowling Ball</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/CircleObjects.cpp" line="30"/> <source>Your average bowling ball: heavy, round and willing to roll.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/CircleObjects.cpp" line="35"/> <source>Volleyball</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/CircleObjects.cpp" line="36"/> <source>A volleyball—you know: light, soft and very bouncy.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/CircleObjects.cpp" line="45"/> <source>A tennis ball is small, fuzzy and bouncy.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/CircleObjects.cpp" line="53"/> <source>A soccer ball is large and bouncy.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/CircleObjects.cpp" line="61"/> <source>A pétanque ball is made of metal and is quite heavy.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/CircleObjects.cpp" line="44"/> <source>Tennis Ball</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/CircleObjects.cpp" line="52"/> <source>Soccer Ball</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/CircleObjects.cpp" line="60"/> <source>Pétanque Boule</source> <translation type="unfinished"/> </message> </context> <context> <name>EditLevelProperties</name> <message> <location filename="../src/view/EditLevelProperties.ui" line="14"/> <source>Dialog</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="20"/> <source>Note: changes in this dialog are not undoable!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="30"/> <source>Level Properties</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="36"/> <source>Level width:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="43"/> <source>width of the level in meters</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="68"/> <source>Level height:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="75"/> <source>Height of the level in meters</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="103"/> <source>Background Properties</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="111"/> <source>Image name:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="121"/> <source>Specify the image name here. Omit the extension. Any image within the level directory or the images directory will be found.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="132"/> <source>Image repeat width</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="142"/> <source>The distance in which the image will repeat itself. use zero for no repeat - the image will be stretched to fit the level.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="155"/> <source>height</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="165"/> <source>The distance in which the image will repeat itself vertically. use zero for no repeat - the image will be stretched to fit the level.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="180"/> <source>Gradient (in front of image):</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="189"/> <source>This table defines the gradient of the background. Each line is a stop. You need at least two stops.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="214"/> <source>The resulting gradient is shown here</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="225"/> <source>new line</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.ui" line="232"/> <source>delete line</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditLevelProperties.cpp" line="80"/> <source>VPos;Color;Transparency</source> <extracomment>translators: keep the semicolons - they separate the column descriptions</extracomment> <translation type="unfinished"/> </message> </context> <context> <name>EditObjectDialog</name> <message> <location filename="../src/view/EditObjectDialog.ui" line="20"/> <source>Edit Object</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditObjectDialog.ui" line="32"/> <source>Basics for: %1</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditObjectDialog.ui" line="40"/> <source>Object ID:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditObjectDialog.ui" line="86"/> <source>Center coord: (</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditObjectDialog.ui" line="103"/> <source>,</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditObjectDialog.ui" line="120"/> <source>)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditObjectDialog.ui" line="131"/> <source>Angle:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditObjectDialog.ui" line="154"/> <source>Radians</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditObjectDialog.ui" line="165"/> <source>Width:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditObjectDialog.ui" line="182"/> <source> Height:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditObjectDialog.cpp" line="216"/> <source>Basic Properties for &apos;%1&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/EditObjectDialog.cpp" line="234"/> <source>Value</source> <translation type="unfinished"/> </message> </context> <context> <name>GameControls</name> <message> <location filename="../src/view/GameControls.ui" line="32"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameControls.ui" line="92"/> <source>Reset</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameControls.ui" line="133"/> <source>Pause</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameControls.ui" line="152"/> <source>Play</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameControls.ui" line="171"/> <source>FF</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameControls.cpp" line="82"/> <source>&amp;Forward</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameControls.cpp" line="84"/> <source>f</source> <extracomment>translators: 'f' is for (fast) forward</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameControls.cpp" line="88"/> <source>P&amp;ause</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameControls.cpp" line="92"/> <source>&amp;Play</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameControls.cpp" line="96"/> <source>&amp;Reset</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameControls.cpp" line="98"/> <source>r</source> <extracomment>translators: 'r' is for reset</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameControls.cpp" line="102"/> <source>Shift+f</source> <extracomment>translators: really-fast-forward is only available as a key shortcut it should be shift-&lt;normal fast-forward&gt;...</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameControls.cpp" line="109"/> <source>Shift+s</source> <extracomment>translators: slow is only available as a key shortcut it should be shift-S...</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameControls.cpp" line="150"/> <source>Space</source> <comment>key for start/pause the simulation</comment> <translation type="unfinished"/> </message> </context> <context> <name>GameResources</name> <message> <location filename="../src/view/GameResources.ui" line="14"/> <source>Toolbox</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameResources.ui" line="66"/> <source>This is the level title</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameResources.ui" line="108"/> <source>This box describes your task.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameResources.ui" line="117"/> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;br /&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameResources.ui" line="159"/> <source>By: The Author</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameResources.ui" line="194"/> <source>Reset</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameResources.ui" line="213"/> <source>Clicking on this button will make the dialog go up.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameResources.ui" line="219"/> <source>OK</source> <translation>Добра</translation> </message> <message> <location filename="../src/view/GameResources.cpp" line="78"/> <source>Undo all your work and go back to a clean start of this level?</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GameResources.cpp" line="94"/> <source>Level by: &lt;b&gt;%1&lt;/b&gt;</source> <extracomment>translators: please do not try to translate the &lt;b&gt;%1&lt;/b&gt; part!</extracomment> <translation type="unfinished"/> </message> </context> <context> <name>GoalEditor</name> <message> <location filename="../src/view/GoalEditor.ui" line="14"/> <source>Goal and Fail Editor </source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GoalEditor.ui" line="20"/> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;GOALS&lt;/span&gt;&lt;br /&gt;A level can only be won if &lt;span style=&quot; font-style:italic;&quot;&gt;all&lt;/span&gt; goals are satisfied.&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;If an ObjectID is red, that ID currently does not exist.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GoalEditor.ui" line="43"/> <location filename="../src/view/GoalEditor.ui" line="94"/> <source>+</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GoalEditor.ui" line="50"/> <location filename="../src/view/GoalEditor.ui" line="101"/> <source>-</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GoalEditor.ui" line="72"/> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;FAILS&lt;/span&gt;&lt;br /&gt;A level can only be won if &lt;span style=&quot; font-style:italic;&quot;&gt;never&lt;/span&gt; any of the fail conditions is met.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GoalEditor.cpp" line="89"/> <source>Not all goals/fails were OK Nothing was changed yet, please fix.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GoalEditor.cpp" line="156"/> <source>Are you sure you want to remove goal %1:&lt;br&gt;%2</source> <extracomment>translator, be careful not to translate the %'s and the &lt;br&gt;'s...</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GoalEditor.cpp" line="177"/> <source>Are you sure you want to remove fail %1:&lt;br&gt;%2</source> <extracomment>translator, be careful not to translate the %'s and the &lt;br&gt;'s...</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GoalEditor.cpp" line="191"/> <location filename="../src/view/GoalEditor.cpp" line="194"/> <location filename="../src/view/GoalEditor.cpp" line="204"/> <location filename="../src/view/GoalEditor.cpp" line="207"/> <source>no object</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GoalEditor.cpp" line="277"/> <source>Variable;Object;Cond.;Value;Object2</source> <extracomment>translators: Cond. is short for Condition - otherwise it doesn't fit</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/GoalEditor.h" line="48"/> <source>change</source> <translation type="unfinished"/> </message> </context> <context> <name>Level</name> <message> <location filename="../src/loadsave/Level.cpp" line="158"/> <location filename="../src/loadsave/Level.cpp" line="179"/> <source>Cannot read file &apos;%1&apos;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/Level.cpp" line="185"/> <source>Cannot parse file - not valid XML?</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/Level.cpp" line="195"/> <location filename="../src/loadsave/Level.cpp" line="213"/> <location filename="../src/loadsave/Level.cpp" line="233"/> <location filename="../src/loadsave/Level.cpp" line="247"/> <location filename="../src/loadsave/Level.cpp" line="264"/> <location filename="../src/loadsave/Level.cpp" line="299"/> <location filename="../src/loadsave/Level.cpp" line="357"/> <source>Parsing &apos;%1&apos; section failed: </source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/Level.cpp" line="240"/> <source>scene width or height unspecified</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/Level.cpp" line="255"/> <source>Parsing &apos;%1&apos; section failed: %2</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/Level.cpp" line="279"/> <source>expected a &lt;%1&gt; section, got &lt;%2&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/Level.cpp" line="286"/> <location filename="../src/loadsave/Level.cpp" line="331"/> <location filename="../src/loadsave/Level.cpp" line="391"/> <source>createObjectFromDom failed</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/Level.cpp" line="303"/> <source>no &lt;%1&gt; section found!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/Level.cpp" line="323"/> <location filename="../src/loadsave/Level.cpp" line="383"/> <source>expected a &lt;%1&gt; section, got &lt;%2&gt;. </source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/Level.cpp" line="337"/> <source>&lt;%1&gt; properties could not be parsed. </source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/Level.cpp" line="507"/> <source>Cannot write file &apos;%1&apos;: %2.</source> <translation type="unfinished"/> </message> </context> <context> <name>LevelCreator</name> <message> <location filename="../src/view/LevelCreator.cpp" line="36"/> <source>LevelCreator</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/LevelCreator.cpp" line="61"/> <source>&amp;Clone object</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/LevelCreator.cpp" line="67"/> <source>&amp;Collision OK</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/LevelCreator.cpp" line="75"/> <source>&amp;Prevent Collision</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/LevelCreator.cpp" line="86"/> <source>&amp;Insert</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/LevelCreator.cpp" line="102"/> <source>E&amp;ditors</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/LevelCreator.cpp" line="105"/> <source>&amp;Goal Editor...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/LevelCreator.cpp" line="109"/> <source>&amp;Size &amp;&amp; Background Editor...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/LevelCreator.cpp" line="113"/> <source>&amp;Name &amp;&amp; Description Editor...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/LevelCreator.cpp" line="122"/> <source>&amp;View</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/LevelCreator.cpp" line="124"/> <source>&amp;Draw Debug</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/LevelCreator.cpp" line="131"/> <source>&amp;Draw Normal</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/LevelCreator.cpp" line="154"/> <source>Object Properties</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/LevelCreator.cpp" line="155"/> <source>Toolbox</source> <translation type="unfinished"/> </message> </context> <context> <name>ListViewItemTooltip</name> <message> <location filename="../src/view/ListViewItemTooltip.ui" line="20"/> <source>ToolboxTooltip</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ListViewItemTooltip.ui" line="137"/> <source>Esc</source> <comment>Probably 'Esc' for any language</comment> <extracomment>escape should close the listviewtooltip</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ListViewItemTooltip.ui" line="277"/> <source>This is a dummy string to test the widget size</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ListViewItemTooltip.ui" line="124"/> <location filename="../src/view/ListViewItemTooltip.ui" line="302"/> <source>...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ListViewItemTooltip.ui" line="241"/> <source>1x</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ListViewItemTooltip.cpp" line="42"/> <source>%1x</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ListViewItemTooltip.cpp" line="66"/> <source>You can resize the object in all directions.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ListViewItemTooltip.cpp" line="70"/> <source>You can resize the object horizontally.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ListViewItemTooltip.cpp" line="72"/> <source>You can resize the object vertically.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ListViewItemTooltip.cpp" line="75"/> <source>You can rotate the object.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ListViewItemTooltip.cpp" line="77"/> <source>You can set the phone number.</source> <translation type="unfinished"/> </message> </context> <context> <name>MainWindow</name> <message> <location filename="../src/view/MainWindow.ui" line="14"/> <source>The Butterfly Effect</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="175"/> <source>&amp;File</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="192"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="197"/> <source>&amp;Controls</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="202"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="206"/> <source>&amp;Contribute</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="236"/> <source>&amp;Open Level...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="252"/> <source>O&amp;pen File...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="239"/> <source>Ctrl+O</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="123"/> <source>Shows the level information again</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="126"/> <source>Info</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="145"/> <source>Choose a different level to play</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="148"/> <source>Eject</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="220"/> <source>&amp;Languages</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="260"/> <source>S&amp;kip Level</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="270"/> <source>&amp;Quit</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="275"/> <source>Libraries...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="280"/> <source>&amp;Keyboard Shortcuts...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="290"/> <source>&amp;About...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="295"/> <source>&amp;Suggestions...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="305"/> <source>&amp;Bug Reports...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="310"/> <source>New Level Ideas...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="320"/> <source>&amp;Switch to Level Editor</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="323"/> <source>Switch</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="336"/> <source>&amp;Save</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="339"/> <source>Save current level under its current name</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="342"/> <source>Ctrl+S</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="358"/> <source>Save &amp;As...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="361"/> <source>Save level under a new name</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="374"/> <source>New Level...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="377"/> <source>Ctrl+N</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="393"/> <source>&amp;Reload Level</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="396"/> <source>Reload the current level from disk</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="399"/> <source>Ctrl+R</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="425"/> <source>&amp;Size &amp;&amp; Backgrounds...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="440"/> <source>&amp;Name &amp;&amp; Description...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="443"/> <source>Name &amp; Description Editor</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="113"/> <source>ERROR during reading file '%1': '%2' </source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="119"/> <source>Non-fatal problem reading file '%1': '%2'. This may affect playability, though!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="154"/> <source>&lt;b&gt;The Butterfly Effect - Bug Reports&lt;/b&gt;&lt;br&gt;&lt;br&gt;Of course, this game is not bug free yet.&lt;br&gt;If you come across anything that you think should not happen, please let us know. Go to our ticket website:&lt;br&gt;&lt;a href=&quot;https://github.com/the-butterfly-effect/tbe/issues&quot;&gt;https://github.com/the-butterfly-effect/tbe/issues&lt;/a&gt;&lt;br&gt;Please tell us at least the &lt;i&gt;name&lt;/i&gt; of the level, what you expected to happen and what did happen. If you want to learn how we fix your issue, please provide a valid e-mail address.</source> <extracomment>translators: &lt;b&gt; and &lt;br&gt; are statements for bold and newline, respectively</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="175"/> <source>&lt;b&gt;The Butterfly Effect - Keyboard shortcuts&lt;/b&gt;&lt;br&gt;&lt;br&gt;The following keys can be used to accelerate actions you&apos;d have to do with the mouse otherwise&lt;table cellpadding=&quot;4&quot;&gt;&lt;tr&gt;&lt;th align=&quot;left&quot;&gt;Key&lt;/th&gt;&lt;th align=&quot;left&quot;&gt;Function &lt;/th&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Space&lt;/td&gt;&lt;td&gt;start / stop simulation &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;f&lt;/td&gt;&lt;td&gt;(during simulation) fast forward / slow down &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;shift+f&lt;/td&gt;&lt;td&gt;(during simulation) really fast forward &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;r&lt;/td&gt;&lt;td&gt;reset the simulation &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Ctrl-Z&lt;/td&gt;&lt;td&gt; undo last action &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Ctrl-Y&lt;/td&gt;&lt;td&gt; redo last action &lt;/td&gt;&lt;/tr&gt; &lt;/table&gt;</source> <extracomment>translators: &lt;b&gt; and &lt;br&gt; are statements for bold and newline, respectively, please make sure to please make sure to match the statements in this dialog with your shortcuts</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="140"/> <source>&lt;b&gt;The Butterfly Effect&lt;/b&gt;&lt;br&gt;version: %2&lt;br&gt;An open source game that uses realistic physics simulations to combine lots of simple mechanical elements to achieve a simple goal in the most complex way possible.&lt;br&gt;&lt;br&gt;(C) 2009,2010,2011,2012,2013,2015,2016 Klaas van Gend and many others&lt;br&gt;&lt;br&gt;Code licensed under GPL version 2 - &lt;i&gt;only&lt;/i&gt;.&lt;br&gt;Levels and graphics may have different open/free licenses.&lt;br&gt;&lt;br&gt;See &lt;a href=&quot;http://%1/&quot;&gt;http://%1/&lt;/a&gt; for more info on this project.</source> <extracomment>translators: &lt;b&gt; and &lt;br&gt; are statements for bold and newline, respectively</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="93"/> <source>Welcome to The Butterfly Effect!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="192"/> <source>&lt;b&gt;The Butterfly Effect - Libraries&lt;/b&gt;&lt;br&gt;&lt;br&gt;The Butterfly Effect is a proud user of the Box2D Physics Library. Please refer to &lt;a href=&quot;http://www.box2d.org/&quot;&gt;http://www.box2d.org/&lt;/a&gt;.&lt;br&gt;The Butterfly Effect uses the Qt GUI toolkit. Please refer to &lt;a href=&quot;http://qt-project.org/&quot;&gt;http://qt-project.org/&lt;/a&gt;.</source> <extracomment>translators: &lt;b&gt; and &lt;br&gt; are statements for bold and newline, respectively</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="209"/> <source>Do you really want to discard the current level and start a new one?</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="231"/> <source>&lt;b&gt;The Butterfly Effect - Create New Levels&lt;/b&gt;&lt;br&gt;&lt;br&gt;We know you can design better levels than we do!&lt;br&gt;Use the Level Creator to build your levels and please submit them to us.&lt;br&gt;Even if your level is not finished yet, don&apos;t hesitate to share it with us! Of course, define how you think it should work so others can join in.&lt;br&gt;&lt;br&gt;Please file a ticket on github with your idea:&lt;br&gt;&lt;a href=&quot;https://github.com/the-butterfly-effect/tbe/issues&quot;&gt;https://github.com/the-butterfly-effect/tbe/issues&lt;/a&gt;&lt;br&gt;</source> <extracomment>translators: &lt;b&gt; and &lt;br&gt; are statements for bold and newline, respectively</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="253"/> <source>Open level</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="253"/> <source>TBE levels (*.xml)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="262"/> <source>really?</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="271"/> <source>You have unsaved changes, really reload Level from disk?</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="276"/> <source>Level has no name - could not be reloaded. Please use &quot;Save As...&quot;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="291"/> <source>Level has no name - could not be saved. Please use &quot;Save As...&quot;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="296"/> <source>File &apos;%1&apos; could not be saved.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="317"/> <source>You did not fill in all fields - but level saved anyway </source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="333"/> <source>Mark this level &apos;skipped&apos; and continue with the next level?</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="347"/> <source>&lt;b&gt;The Butterfly Effect - Suggestions&lt;/b&gt;&lt;br&gt;&lt;br&gt;If you have great ideas for new features in the game, please go to our shiny forums at: &lt;br&gt;&lt;a href=&quot;http://the-butterfly-effect.org/&quot;&gt;http://the-butterfly-effect.org/&lt;/a&gt;&lt;br&gt;to share your ideas with the world.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="374"/> <source>Coordinates: (%1,%2)</source> <extracomment>Shows the cursor coordinates as decimal numbers. %1 is x, %1 is y. The comma seperates both numbers, the translation may need a different seperator</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="381"/> <source> You have unsaved undo actions. You lose your actions when switching languages. </source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="384"/> <source>You requested a switch to language: %1 Be careful: not all languages are 100% complete. %2Are you sure?</source> <extracomment>translators: the %1 contains the language string, the %2 may contain a message about unsaved actions.</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="415"/> <source>&amp;Goal Editor...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.ui" line="430"/> <source>&amp;Object Editor...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="459"/> <source>&amp;Undo</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="461"/> <source>Ctrl+Z</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="463"/> <source>&amp;Redo</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="466"/> <source>Ctrl+Y</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/MainWindow.cpp" line="466"/> <source>Shift+Ctrl+Z</source> <translation type="unfinished"/> </message> </context> <context> <name>QObject</name> <message> <location filename="../src/control/DeleteUndoCommand.cpp" line="32"/> <source>Remove</source> <translation type="unfinished"/> </message> <message> <location filename="../src/control/InsertUndoCommand.h" line="35"/> <source>Insert</source> <translation type="unfinished"/> </message> <message> <location filename="../src/control/MoveUndoCommand.cpp" line="29"/> <source>Move</source> <translation type="unfinished"/> </message> <message> <location filename="../src/control/ResizeUndoCommand.cpp" line="29"/> <source>Resize</source> <translation type="unfinished"/> </message> <message> <location filename="../src/control/RotateUndoCommand.cpp" line="27"/> <source>Rotate</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/GoalSerializer.cpp" line="180"/> <source>Position X</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/GoalSerializer.cpp" line="181"/> <source>Position Y</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/GoalSerializer.cpp" line="182"/> <source>Angle</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/GoalSerializer.cpp" line="183"/> <source>X/Y/Angle</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/GoalSerializer.cpp" line="184"/> <source>Distance</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/GoalSerializer.cpp" line="185"/> <source>Object State</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/GoalSerializer.cpp" line="186"/> <source>Escaped Pingus</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/BalloonCactus.cpp" line="58"/> <source>Balloon</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/BalloonCactus.cpp" line="59"/> <source>A helium balloon. Lighter than air, it moves up. It will pop when it hits sharp objects or gets squashed.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/BalloonCactus.cpp" line="267"/> <source>Cactus (Cactacea Bulbuous Stingus): A cactus has sharp spines.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/BalloonCactus.cpp" line="345"/> <source>A wooden board attached to the scene. It has many sharp nails on one side.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/BalloonCactus.cpp" line="415"/> <source>A rotating disc with sharp teeth.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/BalloonCactus.cpp" line="266"/> <source>Cactus</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/BalloonCactus.cpp" line="344"/> <source>BedOfNails</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/BalloonCactus.cpp" line="414"/> <source>CircularSaw</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/Butterfly.h" line="41"/> <source>Butterfly</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/ColaMintBottle.cpp" line="49"/> <source>Cola+Mint Bottle</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/ColaMintBottle.cpp" line="50"/> <source>This is a prepared cola bottle with a mint in it. If you shake it just a little bit, a reaction starts, which makes the bottle spit a long stream of cola.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/Glue.h" line="57"/> <source>Glue</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/Glue.cpp" line="47"/> <source>Glue links two objects immovably together.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/Link.h" line="57"/> <source>Link</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/Link.cpp" line="45"/> <source>A Link is a massless, bodyless connection between two objects.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PivotPoint.h" line="72"/> <source>PivotPoint</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PivotPoint.cpp" line="127"/> <source>Objects rotate around this point</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PostIt.h" line="48"/> <source>PostIt</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/Scenery.h" line="45"/> <source>Scenery</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/Spring.cpp" line="76"/> <source>Spring</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/Spring.cpp" line="77"/> <source>A loose spring. When a force is applied to it, it retracts and expands.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/Spring.cpp" line="212"/> <source>Spring End</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/TranslationGuide.h" line="64"/> <source>TranslationGuide</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/TranslationGuide.cpp" line="109"/> <source>Objects are limited to only move along one axis</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/TriggerExplosion.cpp" line="43"/> <source>Detonator Box</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/TriggerExplosion.cpp" line="149"/> <source>(empty)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/TriggerExplosion.cpp" line="155"/> <source>This is a detonator box attached to a cell phone. It triggers dynamite remotely if the handle is pushed. </source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/TriggerExplosion.cpp" line="159"/> <source>This one doesn't make any calls yet, select a phone number!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/TriggerExplosion.cpp" line="162"/> <source>This one calls %1.</source> <extracomment>Translators: The %1 will be replaced by a phone number.</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/model/TriggerExplosion.cpp" line="234"/> <source>This is the handle of a detonator box. Throw a heavy object on it to push it.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/TriggerExplosion.cpp" line="431"/> <source>It's dynamite attached to a cell phone. This cell phone doesn&apos;t take any calls, however.</source> <extracomment>Translators: “ ” means “newline”, keep it.</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/model/TriggerExplosion.cpp" line="434"/> <source>It's dynamite attached to a cell phone, ready to be remotely triggered by a detonator box. Dial %1 to make the dynamite go boom.</source> <extracomment>Translators: “ ” means “newline”, keep it. “%1” will be replaced by the phone number</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/model/TriggerExplosion.cpp" line="233"/> <source>Detonator Box Handle</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/TriggerExplosion.cpp" line="322"/> <source>Dynamite</source> <translation type="unfinished"/> </message> <message> <location filename="../src/tbe_global.h.in" line="22"/> <source>The Butterfly Effect</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/Popup.h" line="48"/> <source>critical error</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/Popup.h" line="71"/> <source>informational message</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/Popup.h" line="87"/> <source>warning</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/Popup.h" line="104"/> <source>question</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/LevelList.cpp" line="47"/> <source>Level parser: Cannot read the level descriptions in '%1': %2.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/loadsave/LevelList.cpp" line="164"/> <source>LevelList: Parse error at line %1, column %2: %3</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/Pingus.cpp" line="53"/> <source>Pingus</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/Pingus.cpp" line="54"/> <source>A penguin walks left or right and turns around when it collides with something heavy. It can push light objects around. It also likes to slide down slopes but can&apos;t take much abuse.</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/Butterfly.cpp" line="45"/> <source>Butterfly (Flappus Chaoticus Fragilius): It slowly flies to the right and is attracted to flowers. It is very fragile. You have to keep it safe at all costs!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/model/PostIt.cpp" line="52"/> <source>Someone left notes all over the place. You know, those yellow 3×3 inch pieces of paper. You might want to read them—it may help!</source> <translation type="unfinished"/> </message> <message> <location filename="../src/control/EditPropertyUndoCommand.cpp" line="27"/> <source>EditProperty</source> <translation type="unfinished"/> </message> </context> <context> <name>SaveLevelInfo</name> <message> <location filename="../src/view/SaveLevelInfo.ui" line="14"/> <source>Save Level - Information</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/SaveLevelInfo.ui" line="22"/> <source>File name to save to:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/SaveLevelInfo.ui" line="39"/> <source>...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/SaveLevelInfo.ui" line="48"/> <source>Level information - Use English Only</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/SaveLevelInfo.ui" line="54"/> <source>Title:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/SaveLevelInfo.ui" line="71"/> <source>Author Name:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/SaveLevelInfo.ui" line="88"/> <source>License:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/SaveLevelInfo.ui" line="95"/> <source>GPLv2</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/SaveLevelInfo.ui" line="102"/> <source>Date:</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/SaveLevelInfo.ui" line="115"/> <source>Level Description (summary, make sure to use Post-it notes for real hints):</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/SaveLevelInfo.cpp" line="96"/> <source>Save Level</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/SaveLevelInfo.cpp" line="96"/> <source>TBE levels (*.tbe *.xml)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/SaveLevelInfo.cpp" line="113"/> <source>A File with name '%1' file already exists. Overwrite? </source> <translation type="unfinished"/> </message> </context> <context> <name>ToolboxListWidgetItem</name> <message> <location filename="../src/view/ToolboxListWidgetItem.cpp" line="103"/> <source>(empty)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ToolboxListWidgetItem.cpp" line="110"/> <source>%1x %2</source> <extracomment>%1 is the number of items, %2 is the name of the item</extracomment> <translation type="unfinished"/> </message> </context> <context> <name>ViewPostIt</name> <message> <location filename="../src/view/ViewPostIt.ui" line="26"/> <source>Post-It viewer</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ViewPostIt.ui" line="112"/> <source>Next&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ViewPostIt.ui" line="122"/> <source>Cancel</source> <translation>Скасаваць</translation> </message> <message> <location filename="../src/view/ViewPostIt.cpp" line="154"/> <source>Finish</source> <translation type="unfinished"/> </message> </context> <context> <name>ViewWorld</name> <message> <location filename="../src/view/ViewWorld.cpp" line="87"/> <source>You cannot make changes now, the simulation is ongoing. Reset the simulation?</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/ViewWorld.cpp" line="117"/> <source> %1 fps; %2 s</source> <translation type="unfinished"/> </message> </context> <context> <name>WinFailDialog</name> <message> <location filename="../src/view/WinFailDialog.ui" line="14"/> <source>Form</source> <translation>Форма</translation> </message> <message> <location filename="../src/view/WinFailDialog.ui" line="75"/> <source>TextLabel</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/WinFailDialog.ui" line="118"/> <source>&amp;Replay</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/WinFailDialog.ui" line="128"/> <source>&amp;Skip</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/WinFailDialog.ui" line="151"/> <source>&amp;Choose...</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/WinFailDialog.ui" line="158"/> <source>Go to next level</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/WinFailDialog.ui" line="164"/> <source>&amp;Next&gt;</source> <translation type="unfinished"/> </message> <message> <location filename="../src/view/WinFailDialog.cpp" line="37"/> <source>Congratulations!</source> <extracomment>make sure the translated text fits - the rest won't be shown</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/WinFailDialog.cpp" line="43"/> <source>Fail - retry?</source> <extracomment>make sure the translated text fits - the rest won't be shown</extracomment> <translation type="unfinished"/> </message> <message> <location filename="../src/view/WinFailDialog.cpp" line="45"/> <source>&amp;Retry</source> <translation type="unfinished"/> </message> </context> </TS>
amarsman/tbe
i18n/tbe_be.ts
TypeScript
gpl-2.0
75,216
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1"> <context> <name>Konsole::Session</name> <message> <location filename="../Session.cpp" line="454"/> <source>Bell in session &apos;%1&apos;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../Session.cpp" line="606"/> <source>Session &apos;%1&apos; exited with status %2.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../Session.cpp" line="608"/> <source>Session &apos;%1&apos; crashed.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../Session.cpp" line="613"/> <source>Session &apos;%1&apos; exited unexpectedly.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Konsole::TerminalDisplay</name> <message> <location filename="../TerminalDisplay.cpp" line="1279"/> <source>Size: XXX x XXX</source> <translation type="unfinished"></translation> </message> <message> <location filename="../TerminalDisplay.cpp" line="1291"/> <source>Size: %1 x %2</source> <translation type="unfinished"></translation> </message> <message> <location filename="../TerminalDisplay.cpp" line="2741"/> <source>Paste multiline text</source> <translation type="unfinished"></translation> </message> <message> <location filename="../TerminalDisplay.cpp" line="2742"/> <source>Are you sure you want to paste this text?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../TerminalDisplay.cpp" line="3241"/> <source>&lt;qt&gt;Output has been &lt;a href=&quot;http://en.wikipedia.org/wiki/Flow_control&quot;&gt;suspended&lt;/a&gt; by pressing Ctrl+S. Press &lt;b&gt;Ctrl+Q&lt;/b&gt; to resume.&lt;/qt&gt;</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Konsole::Vt102Emulation</name> <message> <location filename="../Vt102Emulation.cpp" line="1121"/> <source>No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QMessageBox</name> <message> <location filename="../TerminalDisplay.cpp" line="2748"/> <source>Show Details...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QObject</name> <message> <location filename="../ColorScheme.cpp" line="278"/> <location filename="../ColorScheme.cpp" line="293"/> <source>Un-named Color Scheme</source> <translation type="unfinished"></translation> </message> <message> <location filename="../ColorScheme.cpp" line="464"/> <source>Accessible Color Scheme</source> <translation type="unfinished"></translation> </message> <message> <location filename="../Filter.cpp" line="515"/> <source>Open Link</source> <translation type="unfinished"></translation> </message> <message> <location filename="../Filter.cpp" line="516"/> <source>Copy Link Address</source> <translation type="unfinished"></translation> </message> <message> <location filename="../Filter.cpp" line="520"/> <source>Send Email To...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../Filter.cpp" line="521"/> <source>Copy Email Address</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QTermWidget</name> <message> <location filename="../qtermwidget.cpp" line="468"/> <source>Color Scheme Error</source> <translation type="unfinished"></translation> </message> <message> <location filename="../qtermwidget.cpp" line="469"/> <source>Cannot load color scheme: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SearchBar</name> <message> <location filename="../SearchBar.cpp" line="40"/> <source>Match case</source> <translation type="unfinished"></translation> </message> <message> <location filename="../SearchBar.cpp" line="46"/> <source>Regular expression</source> <translation type="unfinished"></translation> </message> <message> <location filename="../SearchBar.cpp" line="50"/> <source>Highlight all matches</source> <translation type="unfinished"></translation> </message> <message> <location filename="../SearchBar.ui" line="14"/> <source>SearchBar</source> <translation type="unfinished"></translation> </message> <message> <location filename="../SearchBar.ui" line="20"/> <source>X</source> <translation type="unfinished"></translation> </message> <message> <location filename="../SearchBar.ui" line="32"/> <source>Find:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../SearchBar.ui" line="42"/> <source>&lt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../SearchBar.ui" line="54"/> <source>&gt;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../SearchBar.ui" line="66"/> <source>...</source> <translation type="unfinished"></translation> </message> </context> </TS>
lxde/qtermwidget
lib/translations/qtermwidget.ts
TypeScript
gpl-2.0
6,036
<?php /** * WorldCat backend. * * PHP version 5 * * Copyright (C) Villanova University 2010. * * 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. * * 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 * * @category VuFind * @package Search * @author David Maus <maus@hab.de> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org */ namespace VuFindSearch\Backend\WorldCat; use VuFindSearch\Backend\AbstractBackend; use VuFindSearch\ParamBag; use VuFindSearch\Query\AbstractQuery; use VuFindSearch\Response\RecordCollectionFactoryInterface; use VuFindSearch\Response\RecordCollectionInterface; /** * WorldCat backend. * * @category VuFind * @package Search * @author David Maus <maus@hab.de> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org */ class Backend extends AbstractBackend { /** * Connector. * * @var Connector */ protected $connector; /** * Query builder. * * @var QueryBuilder */ protected $queryBuilder = null; /** * Constructor. * * @param Connector $connector WorldCat connector * @param RecordCollectionFactoryInterface $factory Record collection factory * (null for default) * * @return void */ public function __construct(Connector $connector, RecordCollectionFactoryInterface $factory = null ) { if (null !== $factory) { $this->setRecordCollectionFactory($factory); } $this->connector = $connector; $this->identifier = null; } /** * Perform a search and return record collection. * * @param AbstractQuery $query Search query * @param int $offset Search offset * @param int $limit Search limit * @param ParamBag $params Search backend parameters * * @return RecordCollectionInterface */ public function search(AbstractQuery $query, $offset, $limit, ParamBag $params = null ) { if (null === $params) { $params = new ParamBag(); } $params->mergeWith($this->getQueryBuilder()->build($query)); $response = $this->connector->search($params, $offset, $limit); $collection = $this->createRecordCollection($response); $this->injectSourceIdentifier($collection); return $collection; } /** * Retrieve a single document. * * @param string $id Document identifier * @param ParamBag $params Search backend parameters * * @return RecordCollectionInterface */ public function retrieve($id, ParamBag $params = null) { $response = $this->connector->getRecord($id, $params); $collection = $this->createRecordCollection($response); $this->injectSourceIdentifier($collection); return $collection; } /** * Set the query builder. * * @param QueryBuilder $queryBuilder Query builder * * @return void */ public function setQueryBuilder(QueryBuilder $queryBuilder) { $this->queryBuilder = $queryBuilder; } /** * Return query builder. * * Lazy loads an empty QueryBuilder if none was set. * * @return QueryBuilder */ public function getQueryBuilder() { if (!$this->queryBuilder) { $this->queryBuilder = new QueryBuilder(); } return $this->queryBuilder; } /** * Return the record collection factory. * * Lazy loads a generic collection factory. * * @return RecordCollectionFactoryInterface */ public function getRecordCollectionFactory() { if ($this->collectionFactory === null) { $this->collectionFactory = new Response\XML\RecordCollectionFactory(); } return $this->collectionFactory; } /** * Return the WorldCat connector. * * @return Connector */ public function getConnector() { return $this->connector; } /// Internal API /** * Create record collection. * * @param array $records Records to process * * @return RecordCollectionInterface */ protected function createRecordCollection($records) { return $this->getRecordCollectionFactory()->factory($records); } }
bbeckman/NDL-VuFind2
module/VuFindSearch/src/VuFindSearch/Backend/WorldCat/Backend.php
PHP
gpl-2.0
5,041
/* * #%L * Fork of Apache Jakarta POI. * %% * Copyright (C) 2008 - 2016 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * 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. * #L% */ /* ==================================================================== 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 loci.poi.util; import java.io.File; import java.io.IOException; import java.util.Random; /** * Interface for creating temporary files. Collects them all into one directory. * * @author Glen Stampoultzis */ public class TempFile { static File dir; static Random rnd = new Random(); /** * Creates a temporary file. Files are collected into one directory and by default are * deleted on exit from the VM. Files can be kept by defining the system property * <code>poi.keep.tmp.files</code>. * <p> * Dont forget to close all files or it might not be possible to delete them. */ public static File createTempFile(String prefix, String suffix) throws IOException { if (dir == null) { dir = new File(System.getProperty("java.io.tmpdir"), "poifiles"); dir.mkdir(); if (System.getProperty("poi.keep.tmp.files") == null) dir.deleteOnExit(); } File newFile = new File(dir, prefix + rnd.nextInt() + suffix); if (System.getProperty("poi.keep.tmp.files") == null) newFile.deleteOnExit(); return newFile; } }
imunro/bioformats
components/forks/poi/src/loci/poi/util/TempFile.java
Java
gpl-2.0
2,917
package org.openyu.archetype.app; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.text.Collator; import java.text.MessageFormat; import java.util.Arrays; import java.util.concurrent.TimeUnit; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) { System.out .println("------------------------------------------------------------------------"); System.out.println("Pre Testing"); System.out .println("------------------------------------------------------------------------"); long begTime = System.nanoTime(); // // print applicationContext-init.xml InputStream in = App.class .getResourceAsStream("/applicationContext-init.xml"); InputStreamReader inputStreamReader = new InputStreamReader(in); // // System.out.println("--- Loading applicationContext-init.xml ---"); BufferedReader bufferedReader = null; StringBuilder buff = new StringBuilder(); String line; try { bufferedReader = new BufferedReader(inputStreamReader); while ((line = bufferedReader.readLine()) != null) { buff.append(line); buff.append("\r\n"); } } catch (Exception ex) { ex.printStackTrace(); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (Exception ex) { } } } // System.out.println(buff); // System.out.println("--- Loading applicationContext.xml ---"); // applicationContext ApplicationContext applicationContext = new ClassPathXmlApplicationContext( new String[] { "applicationContext.xml" }); // System.out.println(applicationContext); String[] beanNames = applicationContext.getBeanDefinitionNames(); Arrays.sort(beanNames, Collator.getInstance(java.util.Locale.ENGLISH)); // System.out.println(); System.out.println("--- Printing spring beans ---"); for (int i = 0; i < beanNames.length; i++) { System.out.println("[" + i + "] " + beanNames[i]); } System.out .println("------------------------------------------------------------------------"); System.out.println("PRE TESTING SUCCESS"); System.out .println("------------------------------------------------------------------------"); // long endTime = System.nanoTime(); long durTime = endTime - begTime; durTime = TimeUnit.NANOSECONDS.toMillis(durTime); // String msgPattern = "Total time: {0} ms"; StringBuilder msg = new StringBuilder(MessageFormat.format(msgPattern, durTime)); System.out.println(msg); // msgPattern = "Total beans: {0}"; msg = new StringBuilder(MessageFormat.format(msgPattern, beanNames.length)); System.out.println(msg); // System.out .println("------------------------------------------------------------------------"); System.exit(0); } }
mixaceh/openyu-archetype.j
openyu-archetype-app/src/main/java/org/openyu/archetype/app/App.java
Java
gpl-2.0
2,913
<?php /** * Shop System Plugins - Terms of Use * * The plugins offered are provided free of charge by Wirecard Central Eastern Europe GmbH * (abbreviated to Wirecard CEE) and are explicitly not part of the Wirecard CEE range of * products and services. * * They have been tested and approved for full functionality in the standard configuration * (status on delivery) of the corresponding shop system. They are under General Public * License Version 2 (GPLv2) and can be used, developed and passed on to third parties under * the same terms. * * However, Wirecard CEE does not provide any guarantee or accept any liability for any errors * occurring when used in an enhanced, customized shop system configuration. * * Operation in an enhanced, customized configuration is at your own risk and requires a * comprehensive test phase by the user of the plugin. * * Customers use the plugins at their own risk. Wirecard CEE does not guarantee their full * functionality neither does Wirecard CEE assume liability for any disadvantages related to * the use of the plugins. Additionally, Wirecard CEE does not guarantee the full functionality * for customized shop systems or installed plugins of other vendors of plugins within the same * shop system. * * Customers are responsible for testing the plugin's functionality before starting productive * operation. * * By installing the plugin into the shop system the customer agrees to these terms of use. * Please do not use the plugin if you do not agree to these terms of use! */ /** * @name WirecardCEE_Stdlib_Client_Exception_ExceptionInterface * @category WirecardCEE * @package WirecardCEE_Stdlib * @subpackage Client_Exception */ interface WirecardCEE_Stdlib_Client_Exception_ExceptionInterface extends WirecardCEE_Stdlib_Exception_ExceptionInterface { }
wirecard/woocommerce-wcs
woocommerce-wirecard-checkout-seamless/vendor/wirecard/checkout-client-library/library/WirecardCEE/Stdlib/Client/Exception/ExceptionInterface.php
PHP
gpl-2.0
1,841
<?php /** * @author Dr Kaushal Keraminiyage * @copyright Dr Kaushal Keraminiyage * @license GNU General Public License version 2 or later */ defined("_JEXEC") or die("Restricted access"); require_once JPATH_COMPONENT.'/helpers/confmgr.php'; /** * Camera_ready_papers list view class. * * @package Confmgr * @subpackage Views */ class ConfmgrViewCamera_ready_papers extends JViewLegacy { protected $items; protected $pagination; protected $state; public function display($tpl = null) { $this->items = $this->get('Items'); $this->state = $this->get('State'); $this->pagination = $this->get('Pagination'); $this->authors = $this->get('Authors'); $this->filterForm = $this->get('FilterForm'); $this->activeFilters = $this->get('ActiveFilters'); // Check for errors. if (count($errors = $this->get('Errors'))) { throw new Exception(implode("\n", $errors)); return false; } ConfmgrHelper::addSubmenu('camera_ready_papers'); // We don't need toolbar in the modal window. if ($this->getLayout() !== 'modal') { $this->addToolbar(); $this->sidebar = JHtmlSidebar::render(); } parent::display($tpl); } /** * Method to add a toolbar */ protected function addToolbar() { $state = $this->get('State'); $canDo = ConfmgrHelper::getActions(); $user = JFactory::getUser(); // Get the toolbar object instance $bar = JToolBar::getInstance('toolbar'); JToolBarHelper::title(JText::_('COM_CONFMGR_CAMERA_READY_PAPER_VIEW_CAMERA_READY_PAPERS_TITLE')); if ($canDo->get('core.create')) { JToolBarHelper::addNew('camera_ready_paper.add','JTOOLBAR_NEW'); } if (($canDo->get('core.edit') || $canDo->get('core.edit.own')) && isset($this->items[0])) { JToolBarHelper::editList('camera_ready_paper.edit','JTOOLBAR_EDIT'); } if ($canDo->get('core.edit.state')) { if (isset($this->items[0]->published)) { JToolBarHelper::divider(); JToolbarHelper::publish('camera_ready_papers.publish', 'JTOOLBAR_PUBLISH', true); JToolbarHelper::unpublish('camera_ready_papers.unpublish', 'JTOOLBAR_UNPUBLISH', true); } else if (isset($this->items[0])) { // Show a direct delete button JToolBarHelper::deleteList('', 'camera_ready_papers.delete','JTOOLBAR_DELETE'); } if (isset($this->items[0]->published)) { JToolBarHelper::divider(); JToolBarHelper::archiveList('camera_ready_papers.archive','JTOOLBAR_ARCHIVE'); } if (isset($this->items[0]->checked_out)) { JToolbarHelper::checkin('camera_ready_papers.checkin'); } } // Show trash and delete for components that uses the state field if (isset($this->items[0]->published)) { if ($state->get('filter.published') == -2 && $canDo->get('core.delete')) { JToolBarHelper::deleteList('', 'camera_ready_papers.delete','JTOOLBAR_EMPTY_TRASH'); JToolBarHelper::divider(); } else if ($state->get('filter.published') != -2 && $canDo->get('core.edit.state')) { JToolBarHelper::trash('camera_ready_papers.trash','JTOOLBAR_TRASH'); JToolBarHelper::divider(); } } // Add a batch button if (isset($this->items[0]) && $user->authorise('core.create', 'com_contacts') && $user->authorise('core.edit', 'com_contacts') && $user->authorise('core.edit.state', 'com_contacts')) { JHtml::_('bootstrap.modal', 'collapseModal'); $title = JText::_('JTOOLBAR_BATCH'); // Instantiate a new JLayoutFile instance and render the batch button $layout = new JLayoutFile('joomla.toolbar.batch'); $dhtml = $layout->render(array('title' => $title)); $bar->appendButton('Custom', $dhtml, 'batch'); } if ($canDo->get('core.admin')) { JToolBarHelper::preferences('com_confmgr'); } } } ?>
kaushal76/j34
administrator/components/com_jdeveloper/tmp/com_confmgr_v0.0.5/admin/views/camera_ready_papers/view.html.php
PHP
gpl-2.0
3,880
namespace LJH.Inventory.UI.Forms { partial class FrmReportBase { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmReportBase)); this.btnSearch = new System.Windows.Forms.Button(); this.btnSaveAs = new System.Windows.Forms.Button(); this.btnColumn = new System.Windows.Forms.Button(); this.SuspendLayout(); // // btnSearch // this.btnSearch.Location = new System.Drawing.Point(660, 12); this.btnSearch.Name = "btnSearch"; this.btnSearch.Size = new System.Drawing.Size(111, 23); this.btnSearch.TabIndex = 0; this.btnSearch.Text = "查询(&Q)"; this.btnSearch.UseVisualStyleBackColor = true; this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click); // // btnSaveAs // this.btnSaveAs.Location = new System.Drawing.Point(660, 41); this.btnSaveAs.Name = "btnSaveAs"; this.btnSaveAs.Size = new System.Drawing.Size(111, 23); this.btnSaveAs.TabIndex = 1; this.btnSaveAs.Text = "另存为(&S)"; this.btnSaveAs.UseVisualStyleBackColor = true; this.btnSaveAs.Click += new System.EventHandler(this.btnSaveAs_Click); // // btnColumn // this.btnColumn.Location = new System.Drawing.Point(660, 70); this.btnColumn.Name = "btnColumn"; this.btnColumn.Size = new System.Drawing.Size(111, 23); this.btnColumn.TabIndex = 17; this.btnColumn.Text = "选择列(&C)"; this.btnColumn.UseVisualStyleBackColor = true; this.btnColumn.Click += new System.EventHandler(this.btnColumn_Click); // // FrmReportBase // this.AcceptButton = this.btnSearch; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(792, 343); this.Controls.Add(this.btnColumn); this.Controls.Add(this.btnSaveAs); this.Controls.Add(this.btnSearch); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "FrmReportBase"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "FrmReportBase"; this.Controls.SetChildIndex(this.btnSearch, 0); this.Controls.SetChildIndex(this.btnSaveAs, 0); this.Controls.SetChildIndex(this.btnColumn, 0); this.ResumeLayout(false); this.PerformLayout(); } #endregion protected System.Windows.Forms.Button btnSearch; protected System.Windows.Forms.Button btnSaveAs; protected System.Windows.Forms.Button btnColumn; } }
ljh198275823/502-EasyInventory
Source/LJH.Inventory.UI/Forms/FrmReportBase.Designer.cs
C#
gpl-2.0
3,924
/* * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the Classpath exception as provided * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package traces.onmethod; import static org.openjdk.btrace.core.BTraceUtils.*; import org.openjdk.btrace.core.annotations.BTrace; import org.openjdk.btrace.core.annotations.Kind; import org.openjdk.btrace.core.annotations.Location; import org.openjdk.btrace.core.annotations.OnMethod; import org.openjdk.btrace.core.annotations.ProbeMethodName; import org.openjdk.btrace.core.annotations.Self; import org.openjdk.btrace.core.annotations.TargetInstance; /** @author Jaroslav Bachorik */ @BTrace public class SyncEntry { @OnMethod( clazz = "/.*\\.OnMethodTest/", method = "sync", location = @Location(value = Kind.SYNC_ENTRY)) public static void args( @Self Object self, @ProbeMethodName String pmn, @TargetInstance Object lock) { println("args"); } }
jbachorik/btrace
btrace-instr/src/test/btrace/onmethod/SyncEntry.java
Java
gpl-2.0
1,998
<?php /** * @Copyright Copyright (C) 2009-2011 ... Ahmad Bilal * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html * Company: Buruj Solutions + Contact: www.burujsolutions.com , ahmad@burujsolutions.com * Created on: Jan 11, 2009 ^ + Project: JS Jobs * File Name: admin/views/application/view.html.php ^ * Description: View class for single record in the admin ^ * History: NONE * */ defined('_JEXEC') or die('Restricted access'); jimport('joomla.application.component.view'); jimport('joomla.html.pagination'); class JSJobsViewJobtype extends JSView{ function display($tpl = null) { require_once JPATH_COMPONENT_ADMINISTRATOR . '/views/common.php'; // layout start if ($layoutName == 'formjobtype') { // jobtypes if (isset($_GET['cid'][0])) $c_id = $_GET['cid'][0]; else $c_id = ''; if ($c_id == '') { $cids = JRequest :: getVar('cid', array(0), 'post', 'array'); $c_id = $cids[0]; } if (is_numeric($c_id) == true AND $c_id != 0) $application = $this->getJSModel('jobtype')->getJobTypebyId($c_id); if (isset($application->id)) $isNew = false; $text = $isNew ? JText :: _('ADD') : JText :: _('EDIT'); JToolBarHelper :: title(JText :: _('JS_JOB_TYPE') . ': <small><small>[ ' . $text . ' ]</small></small>'); JToolBarHelper::apply('jobtype.savejobtypesave', 'SAVE'); JToolBarHelper :: save2new('jobtype.savejobtypeandnew'); JToolBarHelper :: save('jobtype.savejobtype'); if ($isNew) JToolBarHelper :: cancel('jobtype.cancel'); else JToolBarHelper :: cancel('jobtype.cancel', 'Close'); }elseif ($layoutName == 'jobtypes') { //job types JToolBarHelper :: title(JText::_('JS_JOB_TYPES')); JToolBarHelper :: addNew('jobtype.editjobtype'); JToolBarHelper :: editList('jobtype.editjobtype'); JToolBarHelper :: deleteList(JText::_('JS_ARE_YOU_SURE'),'jobtype.remove'); $result = $this->getJSModel('jobtype')->getAllJobTypes($limitstart, $limit); $items = $result[0]; $total = $result[1]; if ($total <= $limitstart) $limitstart = 0; $pagination = new JPagination($total, $limitstart, $limit); $this->assignRef('pagination', $pagination); } // layout end $this->assignRef('config', $config); $this->assignRef('application', $application); $this->assignRef('items', $items); $this->assignRef('theme', $theme); $this->assignRef('option', $option); $this->assignRef('uid', $uid); $this->assignRef('msg', $msg); $this->assignRef('isjobsharing', $_client_auth_key); parent :: display($tpl); } } ?>
jamielaff/als_resourcing
tmp/install_55cb054400b98/jsjobs/admin/views/jobtype/view.html.php
PHP
gpl-2.0
2,982
/* * Copyright (C) 2008-2010 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * 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 "Common.h" #include "DatabaseEnv.h" #include "WorldPacket.h" #include "Opcodes.h" #include "Log.h" #include "UpdateMask.h" #include "World.h" #include "ObjectMgr.h" #include "SpellMgr.h" #include "Player.h" #include "SkillExtraItems.h" #include "Unit.h" #include "Spell.h" #include "DynamicObject.h" #include "SpellAuras.h" #include "SpellAuraEffects.h" #include "Group.h" #include "UpdateData.h" #include "MapManager.h" #include "ObjectAccessor.h" #include "SharedDefines.h" #include "Pet.h" #include "GameObject.h" #include "GossipDef.h" #include "Creature.h" #include "Totem.h" #include "CreatureAI.h" #include "BattlegroundMgr.h" #include "Battleground.h" #include "BattlegroundEY.h" #include "BattlegroundWS.h" #include "OutdoorPvPMgr.h" #include "Language.h" #include "SocialMgr.h" #include "Util.h" #include "VMapFactory.h" #include "TemporarySummon.h" #include "CellImpl.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "SkillDiscovery.h" #include "Formulas.h" #include "Vehicle.h" #include "ScriptMgr.h" #include "GameObjectAI.h" pEffect SpellEffects[TOTAL_SPELL_EFFECTS]= { &Spell::EffectNULL, // 0 &Spell::EffectInstaKill, // 1 SPELL_EFFECT_INSTAKILL &Spell::EffectSchoolDMG, // 2 SPELL_EFFECT_SCHOOL_DAMAGE &Spell::EffectDummy, // 3 SPELL_EFFECT_DUMMY &Spell::EffectUnused, // 4 SPELL_EFFECT_PORTAL_TELEPORT unused &Spell::EffectTeleportUnits, // 5 SPELL_EFFECT_TELEPORT_UNITS &Spell::EffectApplyAura, // 6 SPELL_EFFECT_APPLY_AURA &Spell::EffectEnvirinmentalDMG, // 7 SPELL_EFFECT_ENVIRONMENTAL_DAMAGE &Spell::EffectPowerDrain, // 8 SPELL_EFFECT_POWER_DRAIN &Spell::EffectHealthLeech, // 9 SPELL_EFFECT_HEALTH_LEECH &Spell::EffectHeal, // 10 SPELL_EFFECT_HEAL &Spell::EffectBind, // 11 SPELL_EFFECT_BIND &Spell::EffectNULL, // 12 SPELL_EFFECT_PORTAL &Spell::EffectUnused, // 13 SPELL_EFFECT_RITUAL_BASE unused &Spell::EffectUnused, // 14 SPELL_EFFECT_RITUAL_SPECIALIZE unused &Spell::EffectUnused, // 15 SPELL_EFFECT_RITUAL_ACTIVATE_PORTAL unused &Spell::EffectQuestComplete, // 16 SPELL_EFFECT_QUEST_COMPLETE &Spell::EffectWeaponDmg, // 17 SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL &Spell::EffectResurrect, // 18 SPELL_EFFECT_RESURRECT &Spell::EffectAddExtraAttacks, // 19 SPELL_EFFECT_ADD_EXTRA_ATTACKS &Spell::EffectUnused, // 20 SPELL_EFFECT_DODGE one spell: Dodge &Spell::EffectUnused, // 21 SPELL_EFFECT_EVADE one spell: Evade (DND) &Spell::EffectParry, // 22 SPELL_EFFECT_PARRY &Spell::EffectBlock, // 23 SPELL_EFFECT_BLOCK one spell: Block &Spell::EffectCreateItem, // 24 SPELL_EFFECT_CREATE_ITEM &Spell::EffectUnused, // 25 SPELL_EFFECT_WEAPON &Spell::EffectUnused, // 26 SPELL_EFFECT_DEFENSE one spell: Defense &Spell::EffectPersistentAA, // 27 SPELL_EFFECT_PERSISTENT_AREA_AURA &Spell::EffectSummonType, // 28 SPELL_EFFECT_SUMMON &Spell::EffectLeap, // 29 SPELL_EFFECT_LEAP &Spell::EffectEnergize, // 30 SPELL_EFFECT_ENERGIZE &Spell::EffectWeaponDmg, // 31 SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &Spell::EffectTriggerMissileSpell, // 32 SPELL_EFFECT_TRIGGER_MISSILE &Spell::EffectOpenLock, // 33 SPELL_EFFECT_OPEN_LOCK &Spell::EffectSummonChangeItem, // 34 SPELL_EFFECT_SUMMON_CHANGE_ITEM &Spell::EffectApplyAreaAura, // 35 SPELL_EFFECT_APPLY_AREA_AURA_PARTY &Spell::EffectLearnSpell, // 36 SPELL_EFFECT_LEARN_SPELL &Spell::EffectUnused, // 37 SPELL_EFFECT_SPELL_DEFENSE one spell: SPELLDEFENSE (DND) &Spell::EffectDispel, // 38 SPELL_EFFECT_DISPEL &Spell::EffectUnused, // 39 SPELL_EFFECT_LANGUAGE &Spell::EffectDualWield, // 40 SPELL_EFFECT_DUAL_WIELD &Spell::EffectJump, // 41 SPELL_EFFECT_JUMP &Spell::EffectJumpDest, // 42 SPELL_EFFECT_JUMP_DEST &Spell::EffectTeleUnitsFaceCaster, // 43 SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER &Spell::EffectLearnSkill, // 44 SPELL_EFFECT_SKILL_STEP &Spell::EffectAddHonor, // 45 SPELL_EFFECT_ADD_HONOR honor/pvp related &Spell::EffectUnused, // 46 SPELL_EFFECT_SPAWN clientside, unit appears as if it was just spawned &Spell::EffectTradeSkill, // 47 SPELL_EFFECT_TRADE_SKILL &Spell::EffectUnused, // 48 SPELL_EFFECT_STEALTH one spell: Base Stealth &Spell::EffectUnused, // 49 SPELL_EFFECT_DETECT one spell: Detect &Spell::EffectTransmitted, // 50 SPELL_EFFECT_TRANS_DOOR &Spell::EffectUnused, // 51 SPELL_EFFECT_FORCE_CRITICAL_HIT unused &Spell::EffectUnused, // 52 SPELL_EFFECT_GUARANTEE_HIT one spell: zzOLDCritical Shot &Spell::EffectEnchantItemPerm, // 53 SPELL_EFFECT_ENCHANT_ITEM &Spell::EffectEnchantItemTmp, // 54 SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY &Spell::EffectTameCreature, // 55 SPELL_EFFECT_TAMECREATURE &Spell::EffectSummonPet, // 56 SPELL_EFFECT_SUMMON_PET &Spell::EffectLearnPetSpell, // 57 SPELL_EFFECT_LEARN_PET_SPELL &Spell::EffectWeaponDmg, // 58 SPELL_EFFECT_WEAPON_DAMAGE &Spell::EffectCreateRandomItem, // 59 SPELL_EFFECT_CREATE_RANDOM_ITEM create item base at spell specific loot &Spell::EffectProficiency, // 60 SPELL_EFFECT_PROFICIENCY &Spell::EffectSendEvent, // 61 SPELL_EFFECT_SEND_EVENT &Spell::EffectPowerBurn, // 62 SPELL_EFFECT_POWER_BURN &Spell::EffectThreat, // 63 SPELL_EFFECT_THREAT &Spell::EffectTriggerSpell, // 64 SPELL_EFFECT_TRIGGER_SPELL &Spell::EffectApplyAreaAura, // 65 SPELL_EFFECT_APPLY_AREA_AURA_RAID &Spell::EffectRechargeManaGem, // 66 SPELL_EFFECT_CREATE_MANA_GEM (possibly recharge it, misc - is item ID) &Spell::EffectHealMaxHealth, // 67 SPELL_EFFECT_HEAL_MAX_HEALTH &Spell::EffectInterruptCast, // 68 SPELL_EFFECT_INTERRUPT_CAST &Spell::EffectDistract, // 69 SPELL_EFFECT_DISTRACT &Spell::EffectPull, // 70 SPELL_EFFECT_PULL one spell: Distract Move &Spell::EffectPickPocket, // 71 SPELL_EFFECT_PICKPOCKET &Spell::EffectAddFarsight, // 72 SPELL_EFFECT_ADD_FARSIGHT &Spell::EffectUntrainTalents, // 73 SPELL_EFFECT_UNTRAIN_TALENTS &Spell::EffectApplyGlyph, // 74 SPELL_EFFECT_APPLY_GLYPH &Spell::EffectHealMechanical, // 75 SPELL_EFFECT_HEAL_MECHANICAL one spell: Mechanical Patch Kit &Spell::EffectSummonObjectWild, // 76 SPELL_EFFECT_SUMMON_OBJECT_WILD &Spell::EffectScriptEffect, // 77 SPELL_EFFECT_SCRIPT_EFFECT &Spell::EffectUnused, // 78 SPELL_EFFECT_ATTACK &Spell::EffectSanctuary, // 79 SPELL_EFFECT_SANCTUARY &Spell::EffectAddComboPoints, // 80 SPELL_EFFECT_ADD_COMBO_POINTS &Spell::EffectUnused, // 81 SPELL_EFFECT_CREATE_HOUSE one spell: Create House (TEST) &Spell::EffectNULL, // 82 SPELL_EFFECT_BIND_SIGHT &Spell::EffectDuel, // 83 SPELL_EFFECT_DUEL &Spell::EffectStuck, // 84 SPELL_EFFECT_STUCK &Spell::EffectSummonPlayer, // 85 SPELL_EFFECT_SUMMON_PLAYER &Spell::EffectActivateObject, // 86 SPELL_EFFECT_ACTIVATE_OBJECT &Spell::EffectWMODamage, // 87 SPELL_EFFECT_WMO_DAMAGE &Spell::EffectWMORepair, // 88 SPELL_EFFECT_WMO_REPAIR &Spell::EffectWMOChange, // 89 SPELL_EFFECT_WMO_CHANGE // 0 intact // 1 damaged // 2 destroyed // 3 rebuilding &Spell::EffectKillCreditPersonal, // 90 SPELL_EFFECT_KILL_CREDIT Kill credit but only for single person &Spell::EffectUnused, // 91 SPELL_EFFECT_THREAT_ALL one spell: zzOLDBrainwash &Spell::EffectEnchantHeldItem, // 92 SPELL_EFFECT_ENCHANT_HELD_ITEM &Spell::EffectForceDeselect, // 93 SPELL_EFFECT_FORCE_DESELECT &Spell::EffectSelfResurrect, // 94 SPELL_EFFECT_SELF_RESURRECT &Spell::EffectSkinning, // 95 SPELL_EFFECT_SKINNING &Spell::EffectCharge, // 96 SPELL_EFFECT_CHARGE &Spell::EffectCastButtons, // 97 SPELL_EFFECT_CAST_BUTTON (totem bar since 3.2.2a) &Spell::EffectKnockBack, // 98 SPELL_EFFECT_KNOCK_BACK &Spell::EffectDisEnchant, // 99 SPELL_EFFECT_DISENCHANT &Spell::EffectInebriate, //100 SPELL_EFFECT_INEBRIATE &Spell::EffectFeedPet, //101 SPELL_EFFECT_FEED_PET &Spell::EffectDismissPet, //102 SPELL_EFFECT_DISMISS_PET &Spell::EffectReputation, //103 SPELL_EFFECT_REPUTATION &Spell::EffectSummonObject, //104 SPELL_EFFECT_SUMMON_OBJECT_SLOT1 &Spell::EffectSummonObject, //105 SPELL_EFFECT_SUMMON_OBJECT_SLOT2 &Spell::EffectSummonObject, //106 SPELL_EFFECT_SUMMON_OBJECT_SLOT3 &Spell::EffectSummonObject, //107 SPELL_EFFECT_SUMMON_OBJECT_SLOT4 &Spell::EffectDispelMechanic, //108 SPELL_EFFECT_DISPEL_MECHANIC &Spell::EffectSummonDeadPet, //109 SPELL_EFFECT_SUMMON_DEAD_PET &Spell::EffectDestroyAllTotems, //110 SPELL_EFFECT_DESTROY_ALL_TOTEMS &Spell::EffectDurabilityDamage, //111 SPELL_EFFECT_DURABILITY_DAMAGE &Spell::EffectUnused, //112 SPELL_EFFECT_112 &Spell::EffectResurrectNew, //113 SPELL_EFFECT_RESURRECT_NEW &Spell::EffectTaunt, //114 SPELL_EFFECT_ATTACK_ME &Spell::EffectDurabilityDamagePCT, //115 SPELL_EFFECT_DURABILITY_DAMAGE_PCT &Spell::EffectSkinPlayerCorpse, //116 SPELL_EFFECT_SKIN_PLAYER_CORPSE one spell: Remove Insignia, bg usage, required special corpse flags... &Spell::EffectSpiritHeal, //117 SPELL_EFFECT_SPIRIT_HEAL one spell: Spirit Heal &Spell::EffectSkill, //118 SPELL_EFFECT_SKILL professions and more &Spell::EffectApplyAreaAura, //119 SPELL_EFFECT_APPLY_AREA_AURA_PET &Spell::EffectUnused, //120 SPELL_EFFECT_TELEPORT_GRAVEYARD one spell: Graveyard Teleport Test &Spell::EffectWeaponDmg, //121 SPELL_EFFECT_NORMALIZED_WEAPON_DMG &Spell::EffectUnused, //122 SPELL_EFFECT_122 unused &Spell::EffectSendTaxi, //123 SPELL_EFFECT_SEND_TAXI taxi/flight related (misc value is taxi path id) &Spell::EffectPullTowards, //124 SPELL_EFFECT_PULL_TOWARDS &Spell::EffectModifyThreatPercent, //125 SPELL_EFFECT_MODIFY_THREAT_PERCENT &Spell::EffectStealBeneficialBuff, //126 SPELL_EFFECT_STEAL_BENEFICIAL_BUFF spell steal effect? &Spell::EffectProspecting, //127 SPELL_EFFECT_PROSPECTING Prospecting spell &Spell::EffectApplyAreaAura, //128 SPELL_EFFECT_APPLY_AREA_AURA_FRIEND &Spell::EffectApplyAreaAura, //129 SPELL_EFFECT_APPLY_AREA_AURA_ENEMY &Spell::EffectRedirectThreat, //130 SPELL_EFFECT_REDIRECT_THREAT &Spell::EffectPlayerNotification, //131 SPELL_EFFECT_PLAYER_NOTIFICATION &Spell::EffectPlayMusic, //132 SPELL_EFFECT_PLAY_MUSIC sound id in misc value (SoundEntries.dbc) &Spell::EffectUnlearnSpecialization, //133 SPELL_EFFECT_UNLEARN_SPECIALIZATION unlearn profession specialization &Spell::EffectKillCredit, //134 SPELL_EFFECT_KILL_CREDIT misc value is creature entry &Spell::EffectNULL, //135 SPELL_EFFECT_CALL_PET &Spell::EffectHealPct, //136 SPELL_EFFECT_HEAL_PCT &Spell::EffectEnergizePct, //137 SPELL_EFFECT_ENERGIZE_PCT &Spell::EffectLeapBack, //138 SPELL_EFFECT_LEAP_BACK Leap back &Spell::EffectQuestClear, //139 SPELL_EFFECT_CLEAR_QUEST Reset quest status (miscValue - quest ID) &Spell::EffectForceCast, //140 SPELL_EFFECT_FORCE_CAST &Spell::EffectForceCastWithValue, //141 SPELL_EFFECT_FORCE_CAST_WITH_VALUE &Spell::EffectTriggerSpellWithValue, //142 SPELL_EFFECT_TRIGGER_SPELL_WITH_VALUE &Spell::EffectApplyAreaAura, //143 SPELL_EFFECT_APPLY_AREA_AURA_OWNER &Spell::EffectKnockBack, //144 SPELL_EFFECT_KNOCK_BACK_DEST &Spell::EffectPullTowards, //145 SPELL_EFFECT_PULL_TOWARDS_DEST Black Hole Effect &Spell::EffectActivateRune, //146 SPELL_EFFECT_ACTIVATE_RUNE &Spell::EffectQuestFail, //147 SPELL_EFFECT_QUEST_FAIL quest fail &Spell::EffectUnused, //148 SPELL_EFFECT_148 1 spell - 43509 &Spell::EffectChargeDest, //149 SPELL_EFFECT_CHARGE_DEST &Spell::EffectQuestStart, //150 SPELL_EFFECT_QUEST_START &Spell::EffectTriggerRitualOfSummoning, //151 SPELL_EFFECT_TRIGGER_SPELL_2 &Spell::EffectNULL, //152 SPELL_EFFECT_152 summon Refer-a-Friend &Spell::EffectCreateTamedPet, //153 SPELL_EFFECT_CREATE_TAMED_PET misc value is creature entry &Spell::EffectDiscoverTaxi, //154 SPELL_EFFECT_DISCOVER_TAXI &Spell::EffectTitanGrip, //155 SPELL_EFFECT_TITAN_GRIP Allows you to equip two-handed axes, maces and swords in one hand, but you attack $49152s1% slower than normal. &Spell::EffectEnchantItemPrismatic, //156 SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC &Spell::EffectCreateItem2, //157 SPELL_EFFECT_CREATE_ITEM_2 create item or create item template and replace by some randon spell loot item &Spell::EffectMilling, //158 SPELL_EFFECT_MILLING milling &Spell::EffectRenamePet, //159 SPELL_EFFECT_ALLOW_RENAME_PET allow rename pet once again &Spell::EffectNULL, //160 SPELL_EFFECT_160 1 spell - 45534 &Spell::EffectSpecCount, //161 SPELL_EFFECT_TALENT_SPEC_COUNT second talent spec (learn/revert) &Spell::EffectActivateSpec, //162 SPELL_EFFECT_TALENT_SPEC_SELECT activate primary/secondary spec &Spell::EffectNULL, //163 unused &Spell::EffectRemoveAura, //164 SPELL_EFFECT_REMOVE_AURA }; void Spell::EffectNULL(SpellEffIndex /*effIndex*/) { sLog->outDebug("WORLD: Spell Effect DUMMY"); } void Spell::EffectUnused(SpellEffIndex /*effIndex*/) { // NOT USED BY ANY SPELL OR USELESS OR IMPLEMENTED IN DIFFERENT WAY IN TRINITY } void Spell::EffectResurrectNew(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->isAlive()) return; if (unitTarget->GetTypeId() != TYPEID_PLAYER) return; if (!unitTarget->IsInWorld()) return; Player* pTarget = unitTarget->ToPlayer(); if (pTarget->isRessurectRequested()) // already have one active request return; uint32 health = damage; uint32 mana = m_spellInfo->EffectMiscValue[effIndex]; ExecuteLogEffectResurrect(effIndex, pTarget); pTarget->setResurrectRequestData(m_caster->GetGUID(), m_caster->GetMapId(), m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ(), health, mana); SendResurrectRequest(pTarget); } void Spell::EffectInstaKill(SpellEffIndex /*effIndex*/) { if (!unitTarget || !unitTarget->isAlive()) return; // Demonic Sacrifice if (m_spellInfo->Id == 18788 && unitTarget->GetTypeId() == TYPEID_UNIT) { uint32 entry = unitTarget->GetEntry(); uint32 spellID; switch (entry) { case 416: spellID = 18789; break; //imp case 417: spellID = 18792; break; //fellhunter case 1860: spellID = 18790; break; //void case 1863: spellID = 18791; break; //succubus case 17252: spellID = 35701; break; //fellguard default: sLog->outError("EffectInstaKill: Unhandled creature entry (%u) case.", entry); return; } m_caster->CastSpell(m_caster, spellID, true); } if (m_caster == unitTarget) // prevent interrupt message finish(); WorldPacket data(SMSG_SPELLINSTAKILLLOG, 8+8+4); data << uint64(m_caster->GetGUID()); data << uint64(unitTarget->GetGUID()); data << uint32(m_spellInfo->Id); m_caster->SendMessageToSet(&data, true); m_caster->DealDamage(unitTarget, unitTarget->GetHealth(), NULL, NODAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); } void Spell::EffectEnvirinmentalDMG(SpellEffIndex effIndex) { uint32 absorb = 0; uint32 resist = 0; // Note: this hack with damage replace required until GO casting not implemented // environment damage spells already have around enemies targeting but this not help in case not existed GO casting support // currently each enemy selected explicitly and self cast damage, we prevent apply self casted spell bonuses/etc damage = SpellMgr::CalculateSpellEffectAmount(m_spellInfo, effIndex, m_caster); m_caster->CalcAbsorbResist(m_caster, GetSpellSchoolMask(m_spellInfo), SPELL_DIRECT_DAMAGE, damage, &absorb, &resist, m_spellInfo); m_caster->SendSpellNonMeleeDamageLog(m_caster, m_spellInfo->Id, damage, GetSpellSchoolMask(m_spellInfo), absorb, resist, false, 0, false); if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->EnvironmentalDamage(DAMAGE_FIRE, damage); } void Spell::EffectSchoolDMG(SpellEffIndex /*effIndex*/) { } void Spell::SpellDamageSchoolDmg(SpellEffIndex effIndex) { bool apply_direct_bonus = true; if (unitTarget && unitTarget->isAlive()) { switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: { // Meteor like spells (divided damage to targets) if (m_customAttr & SPELL_ATTR0_CU_SHARE_DAMAGE) { uint32 count = 0; for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if (ihit->effectMask & (1<<effIndex)) ++count; damage /= count; // divide to all targets } switch(m_spellInfo->Id) // better way to check unknown { // Positive/Negative Charge case 28062: case 28085: case 39090: case 39093: if (!m_triggeredByAuraSpell) break; if (unitTarget == m_caster) { uint8 count = 0; for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if (ihit->targetGUID != m_caster->GetGUID()) if (Player *target = ObjectAccessor::GetPlayer(*m_caster, ihit->targetGUID)) if (target->HasAura(m_triggeredByAuraSpell->Id)) ++count; if (count) { uint32 spellId = 0; switch (m_spellInfo->Id) { case 28062: spellId = 29659; break; case 28085: spellId = 29660; break; case 39090: spellId = 39089; break; case 39093: spellId = 39092; break; } m_caster->SetAuraStack(spellId, m_caster, count); } } if (unitTarget->HasAura(m_triggeredByAuraSpell->Id)) damage = 0; break; // Consumption case 28865: damage = (((InstanceMap*)m_caster->GetMap())->GetDifficulty() == REGULAR_DIFFICULTY ? 2750 : 4250); break; // percent from health with min case 25599: // Thundercrash { damage = unitTarget->GetHealth() / 2; if (damage < 200) damage = 200; break; } // arcane charge. must only affect demons (also undead?) case 45072: { if (unitTarget->GetCreatureType() != CREATURE_TYPE_DEMON && unitTarget->GetCreatureType() != CREATURE_TYPE_UNDEAD) return; break; } case 33671: // gruul's shatter case 50811: // krystallus shatter ( Normal ) case 61547: // krystallus shatter ( Heroic ) { // don't damage self and only players if (unitTarget->GetGUID() == m_caster->GetGUID() || unitTarget->GetTypeId() != TYPEID_PLAYER) return; float radius = GetSpellRadiusForHostile(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[0])); if (!radius) return; float distance = m_caster->GetDistance2d(unitTarget); damage = (distance > radius) ? 0 : int32(SpellMgr::CalculateSpellEffectAmount(m_spellInfo, 0) * ((radius - distance)/radius)); break; } // TODO: add spell specific target requirement hook for spells // Shadowbolts only affects targets with Shadow Mark (Gothik) case 27831: case 55638: if (!unitTarget->HasAura(27825)) return; break; // Cataclysmic Bolt case 38441: { damage = unitTarget->CountPctFromMaxHealth(50); break; } // Tympanic Tantrum case 62775: { damage = unitTarget->CountPctFromMaxHealth(10); break; } // Gargoyle Strike case 51963: { // about +4 base spell dmg per level damage = (m_caster->getLevel() - 60) * 4 + 60; break; } // Loken Pulsing Shockwave case 59837: case 52942: { // don't damage self and only players if(unitTarget->GetGUID() == m_caster->GetGUID() || unitTarget->GetTypeId() != TYPEID_PLAYER) return; float radius = GetSpellRadiusForHostile(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[0])); if (!radius) return; float distance = m_caster->GetDistance2d(unitTarget); damage = (distance > radius) ? 0 : int32(SpellMgr::CalculateSpellEffectAmount(m_spellInfo, 0) * distance); break; } } break; } case SPELLFAMILY_WARRIOR: { // Bloodthirst if (m_spellInfo->SpellFamilyFlags[1] & 0x400) ApplyPctF(damage, m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); // Shield Slam else if (m_spellInfo->SpellFamilyFlags[1] & 0x200 && m_spellInfo->Category == 1209) damage += int32(m_caster->ApplyEffectModifiers(m_spellInfo, effIndex, float(m_caster->GetShieldBlockValue()))); // Victory Rush else if (m_spellInfo->SpellFamilyFlags[1] & 0x100) { ApplyPctF(damage, m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); m_caster->ModifyAuraState(AURA_STATE_WARRIOR_VICTORY_RUSH, false); } // Shockwave else if (m_spellInfo->Id == 46968) { int32 pct = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, 2); if (pct > 0) damage += int32(CalculatePctN(m_caster->GetTotalAttackPowerValue(BASE_ATTACK), pct)); break; } break; } case SPELLFAMILY_WARLOCK: { // Incinerate Rank 1 & 2 if ((m_spellInfo->SpellFamilyFlags[1] & 0x000040) && m_spellInfo->SpellIconID == 2128) { // Incinerate does more dmg (dmg*0.25) if the target have Immolate debuff. // Check aura state for speed but aura state set not only for Immolate spell if (unitTarget->HasAuraState(AURA_STATE_CONFLAGRATE)) { if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_WARLOCK, 0x4, 0, 0)) damage += damage/4; } } // Conflagrate - consumes Immolate or Shadowflame else if (m_spellInfo->TargetAuraState == AURA_STATE_CONFLAGRATE) { AuraEffect const* aura = NULL; // found req. aura for damage calculation Unit::AuraEffectList const &mPeriodic = unitTarget->GetAuraEffectsByType(SPELL_AURA_PERIODIC_DAMAGE); for (Unit::AuraEffectList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i) { // for caster applied auras only if ((*i)->GetSpellProto()->SpellFamilyName != SPELLFAMILY_WARLOCK || (*i)->GetCasterGUID() != m_caster->GetGUID()) continue; // Immolate if ((*i)->GetSpellProto()->SpellFamilyFlags[0] & 0x4) { aura = *i; // it selected always if exist break; } // Shadowflame if ((*i)->GetSpellProto()->SpellFamilyFlags[2] & 0x00000002) aura = *i; // remember but wait possible Immolate as primary priority } // found Immolate or Shadowflame if (aura) { uint32 pdamage = uint32(std::max(aura->GetAmount(), 0)); pdamage = m_caster->SpellDamageBonus(unitTarget, aura->GetSpellProto(), pdamage, DOT, aura->GetBase()->GetStackAmount()); uint32 pct_dir = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, (effIndex + 1)); uint8 baseTotalTicks = uint8(m_caster->CalcSpellDuration(aura->GetSpellProto()) / aura->GetSpellProto()->EffectAmplitude[0]); damage += int32(CalculatePctU(pdamage * baseTotalTicks, pct_dir)); uint32 pct_dot = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, (effIndex + 2)) / 3; m_spellValue->EffectBasePoints[1] = SpellMgr::CalculateSpellEffectBaseAmount(int32(CalculatePctU(pdamage * baseTotalTicks, pct_dot)), m_spellInfo, 1); apply_direct_bonus = false; // Glyph of Conflagrate if (!m_caster->HasAura(56235)) unitTarget->RemoveAurasDueToSpell(aura->GetId(), m_caster->GetGUID()); break; } } // Shadow Bite else if (m_spellInfo->SpellFamilyFlags[1] & 0x400000) { if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isPet()) { // Get DoTs on target by owner (5% increase by dot) damage += int32(CalculatePctN(unitTarget->GetDoTsByCaster(m_caster->GetOwnerGUID()), 5)); if (Player* owner = m_caster->GetOwner()->ToPlayer()) { if (AuraEffect* aurEff = owner->GetAuraEffect(SPELL_AURA_ADD_FLAT_MODIFIER, SPELLFAMILY_WARLOCK, 214, 0)) { int32 bp0 = aurEff->GetId() == 54037 ? 4 : 8; m_caster->CastCustomSpell(m_caster, 54425, &bp0, NULL, NULL, true); } } } } break; } case SPELLFAMILY_PRIEST: { // Shadow Word: Death - deals damage equal to damage done to caster if ((m_spellInfo->SpellFamilyFlags[1] & 0x2)) { int32 back_damage = m_caster->SpellDamageBonus(unitTarget, m_spellInfo, (uint32)damage, SPELL_DIRECT_DAMAGE); // Pain and Suffering reduces damage if (AuraEffect * aurEff = m_caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST, 2874, 0)) AddPctN(back_damage, -aurEff->GetAmount()); if (back_damage < int32(unitTarget->GetHealth())) m_caster->CastCustomSpell(m_caster, 32409, &back_damage, 0, 0, true); } // Mind Blast - applies Mind Trauma if: else if (m_spellInfo->SpellFamilyFlags[2] & 0x00002000) { // We are in Shadow Form if (m_caster->GetShapeshiftForm() == FORM_SHADOW) // We have Improved Mind Blast if (AuraEffect * aurEff = m_caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST,95,0)) // Chance has been successfully rolled if (roll_chance_i(aurEff->GetAmount())) m_caster->CastSpell(unitTarget, 48301, true); } // Smite else if (m_spellInfo->SpellFamilyFlags[0] & 0x80) { // Glyph of Smite if (AuraEffect * aurEff = m_caster->GetAuraEffect(55692, 0)) if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x100000, 0, 0, m_caster->GetGUID())) AddPctN(damage, aurEff->GetAmount()); } // Improved Mind Blast (Mind Blast in shadow form bonus) else if (m_caster->GetShapeshiftForm() == FORM_SHADOW && (m_spellInfo->SpellFamilyFlags[0] & 0x00002000)) { Unit::AuraEffectList const& ImprMindBlast = m_caster->GetAuraEffectsByType(SPELL_AURA_ADD_FLAT_MODIFIER); for (Unit::AuraEffectList::const_iterator i = ImprMindBlast.begin(); i != ImprMindBlast.end(); ++i) { if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_PRIEST && ((*i)->GetSpellProto()->SpellIconID == 95)) { int chance = SpellMgr::CalculateSpellEffectAmount((*i)->GetSpellProto(), 1, m_caster); if (roll_chance_i(chance)) // Mind Trauma m_caster->CastSpell(unitTarget, 48301, true, 0); break; } } } break; } case SPELLFAMILY_DRUID: { // Ferocious Bite if (m_caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->SpellFamilyFlags[0] & 0x000800000) && m_spellInfo->SpellVisual[0] == 6587) { // converts each extra point of energy into ($f1+$AP/410) additional damage float ap = m_caster->GetTotalAttackPowerValue(BASE_ATTACK); float multiple = ap / 410 + m_spellInfo->EffectDamageMultiplier[effIndex]; int32 energy = -(m_caster->ModifyPower(POWER_ENERGY, -30)); damage += int32(energy * multiple); damage += int32(CalculatePctN(m_caster->ToPlayer()->GetComboPoints() * ap, 7)); } // Wrath else if (m_spellInfo->SpellFamilyFlags[0] & 0x00000001) { // Improved Insect Swarm if (AuraEffect const * aurEff = m_caster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 1771, 0)) if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00200000, 0, 0)) AddPctN(damage, aurEff->GetAmount()); } break; } case SPELLFAMILY_ROGUE: { // Envenom if (m_caster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->SpellFamilyFlags[1] & 0x8)) { // consume from stack dozes not more that have combo-points if (uint32 combo = m_caster->ToPlayer()->GetComboPoints()) { // Lookup for Deadly poison (only attacker applied) if (AuraEffect const * aurEff = unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_ROGUE, 0x10000, 0, 0, m_caster->GetGUID())) { // count consumed deadly poison doses at target bool needConsume = true; uint32 spellId = aurEff->GetId(); uint32 doses = aurEff->GetBase()->GetStackAmount(); if (doses > combo) doses = combo; // Master Poisoner Unit::AuraEffectList const& auraList = m_caster->ToPlayer()->GetAuraEffectsByType(SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL_NOT_STACK); for (Unit::AuraEffectList::const_iterator iter = auraList.begin(); iter != auraList.end(); ++iter) { if ((*iter)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_ROGUE && (*iter)->GetSpellProto()->SpellIconID == 1960) { uint32 chance = SpellMgr::CalculateSpellEffectAmount((*iter)->GetSpellProto(), 2, m_caster); if (chance && roll_chance_i(chance)) needConsume = false; break; } } if (needConsume) for (uint32 i = 0; i < doses; ++i) unitTarget->RemoveAuraFromStack(spellId); damage *= doses; damage += int32(((Player*)m_caster)->GetTotalAttackPowerValue(BASE_ATTACK) * 0.09f * doses); } // Eviscerate and Envenom Bonus Damage (item set effect) if (m_caster->HasAura(37169)) damage += ((Player*)m_caster)->GetComboPoints()*40; } } // Eviscerate else if ((m_spellInfo->SpellFamilyFlags[0] & 0x00020000) && m_caster->GetTypeId() == TYPEID_PLAYER) { if (uint32 combo = ((Player*)m_caster)->GetComboPoints()) { float ap = m_caster->GetTotalAttackPowerValue(BASE_ATTACK); damage += irand(int32(ap * combo * 0.03f), int32(ap * combo * 0.07f)); // Eviscerate and Envenom Bonus Damage (item set effect) if (m_caster->HasAura(37169)) damage += combo*40; } } break; } case SPELLFAMILY_HUNTER: { //Gore if (m_spellInfo->SpellIconID == 1578) { if (m_caster->HasAura(57627)) // Charge 6 sec post-affect damage *= 2; } // Steady Shot else if (m_spellInfo->SpellFamilyFlags[1] & 0x1) { bool found = false; // check dazed affect Unit::AuraEffectList const& decSpeedList = unitTarget->GetAuraEffectsByType(SPELL_AURA_MOD_DECREASE_SPEED); for (Unit::AuraEffectList::const_iterator iter = decSpeedList.begin(); iter != decSpeedList.end(); ++iter) { if ((*iter)->GetSpellProto()->SpellIconID == 15 && (*iter)->GetSpellProto()->Dispel == 0) { found = true; break; } } // TODO: should this be put on taken but not done? if (found) damage += SpellMgr::CalculateSpellEffectAmount(m_spellInfo, 1); if (m_caster->GetTypeId() == TYPEID_PLAYER) { // Add Ammo and Weapon damage plus RAP * 0.1 Item *item = m_caster->ToPlayer()->GetWeaponForAttack(RANGED_ATTACK); if (item) { float dmg_min = item->GetProto()->Damage->DamageMin; float dmg_max = item->GetProto()->Damage->DamageMax; if (dmg_max == 0.0f && dmg_min > dmg_max) damage += int32(dmg_min); else damage += irand(int32(dmg_min), int32(dmg_max)); damage += int32(m_caster->ToPlayer()->GetAmmoDPS()*item->GetProto()->Delay*0.001f); } } } break; } case SPELLFAMILY_PALADIN: { // Hammer of the Righteous if (m_spellInfo->SpellFamilyFlags[1]&0x00040000) { // Add main hand dps * effect[2] amount float average = (m_caster->GetFloatValue(UNIT_FIELD_MINDAMAGE) + m_caster->GetFloatValue(UNIT_FIELD_MAXDAMAGE)) / 2; int32 count = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, EFFECT_2); damage += count * int32(average * IN_MILLISECONDS) / m_caster->GetAttackTime(BASE_ATTACK); break; } // Shield of Righteousness if (m_spellInfo->SpellFamilyFlags[EFFECT_1] & 0x100000) { damage += CalculatePctN(m_caster->GetShieldBlockValue(), SpellMgr::CalculateSpellEffectAmount(m_spellInfo, EFFECT_1)); break; } break; } case SPELLFAMILY_DEATHKNIGHT: { // Blood Boil - bonus for diseased targets if (m_spellInfo->SpellFamilyFlags[0] & 0x00040000 && unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0, 0, 0x00000002, m_caster->GetGUID())) { damage += m_damage / 2; damage += int32(m_caster->GetTotalAttackPowerValue(RANGED_ATTACK)* 0.035f); } break; } } if (m_originalCaster && damage > 0 && apply_direct_bonus) damage = m_originalCaster->SpellDamageBonus(unitTarget, m_spellInfo, (uint32)damage, SPELL_DIRECT_DAMAGE); m_damage += damage; } } void Spell::EffectDummy(SpellEffIndex effIndex) { if (!unitTarget && !gameObjTarget && !itemTarget) return; uint32 spell_id = 0; int32 bp = 0; bool triggered = true; SpellCastTargets targets; // selection by spell family switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: { switch (m_spellInfo->Id) { case 8593: // Symbol of life (restore creature to life) case 31225: // Shimmering Vessel (restore creature to life) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT) return; unitTarget->ToCreature()->setDeathState(JUST_ALIVED); return; } case 12162: // Deep wounds case 12850: // (now good common check for this spells) case 12868: { if (!unitTarget) return; float damage; // DW should benefit of attack power, damage percent mods etc. // TODO: check if using offhand damage is correct and if it should be divided by 2 if (m_caster->haveOffhandWeapon() && m_caster->getAttackTimer(BASE_ATTACK) > m_caster->getAttackTimer(OFF_ATTACK)) damage = (m_caster->GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE) + m_caster->GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE))/2; else damage = (m_caster->GetFloatValue(UNIT_FIELD_MINDAMAGE) + m_caster->GetFloatValue(UNIT_FIELD_MAXDAMAGE))/2; switch (m_spellInfo->Id) { case 12162: damage *= 0.16f; break; // Rank 1 case 12850: damage *= 0.32f; break; // Rank 2 case 12868: damage *= 0.48f; break; // Rank 3 default: sLog->outError("Spell::EffectDummy: Spell %u not handled in DW",m_spellInfo->Id); return; }; // get remaining damage of old Deep Wound aura AuraEffect* deepWound = unitTarget->GetAuraEffect(12721, 0); if (deepWound) { int32 remainingTicks = deepWound->GetBase()->GetDuration() / deepWound->GetAmplitude(); damage += remainingTicks * deepWound->GetAmount(); } // 1 tick/sec * 6 sec = 6 ticks int32 deepWoundsDotBasePoints0 = int32(damage / 6); m_caster->CastCustomSpell(unitTarget, 12721, &deepWoundsDotBasePoints0, NULL, NULL, true, NULL); return; } case 13567: // Dummy Trigger { // can be used for different aura triggering, so select by aura if (!m_triggeredByAuraSpell || !unitTarget) return; switch (m_triggeredByAuraSpell->Id) { case 26467: // Persistent Shield m_caster->CastCustomSpell(unitTarget, 26470, &damage, NULL, NULL, true); break; default: sLog->outError("EffectDummy: Non-handled case for spell 13567 for triggered aura %u",m_triggeredByAuraSpell->Id); break; } return; } case 17251: // Spirit Healer Res { if (!unitTarget || !m_originalCaster) return; if (m_originalCaster->GetTypeId() == TYPEID_PLAYER) { WorldPacket data(SMSG_SPIRIT_HEALER_CONFIRM, 8); data << uint64(unitTarget->GetGUID()); m_originalCaster->ToPlayer()->GetSession()->SendPacket(&data); } return; } case 20577: // Cannibalize if (unitTarget) m_caster->CastSpell(m_caster, 20578, false, NULL); return; case 23019: // Crystal Prison Dummy DND { if (!unitTarget || !unitTarget->isAlive() || unitTarget->GetTypeId() != TYPEID_UNIT || unitTarget->ToCreature()->isPet()) return; Creature* creatureTarget = unitTarget->ToCreature(); m_caster->SummonGameObject(179644, creatureTarget->GetPositionX(), creatureTarget->GetPositionY(), creatureTarget->GetPositionZ(), creatureTarget->GetOrientation(), 0, 0, 0, 0, uint32(creatureTarget->GetRespawnTime()-time(NULL))); sLog->outDebug("SummonGameObject at SpellEfects.cpp EffectDummy for Spell 23019"); creatureTarget->ForcedDespawn(); return; } case 23448: // Transporter Arrival - Ultrasafe Transporter: Gadgetzan - backfires { int32 r = irand(0, 119); if (r < 20) // Transporter Malfunction - 1/6 polymorph m_caster->CastSpell(m_caster, 23444, true); else if (r < 100) // Evil Twin - 4/6 evil twin m_caster->CastSpell(m_caster, 23445, true); else // Transporter Malfunction - 1/6 miss the target m_caster->CastSpell(m_caster, 36902, true); return; } case 23453: // Gnomish Transporter - Ultrasafe Transporter: Gadgetzan if (roll_chance_i(50)) // Gadgetzan Transporter - success m_caster->CastSpell(m_caster, 23441, true); else // Gadgetzan Transporter Failure - failure m_caster->CastSpell(m_caster, 23446, true); return; case 25860: // Reindeer Transformation { if (!m_caster->HasAuraType(SPELL_AURA_MOUNTED)) return; float flyspeed = m_caster->GetSpeedRate(MOVE_FLIGHT); float speed = m_caster->GetSpeedRate(MOVE_RUN); m_caster->RemoveAurasByType(SPELL_AURA_MOUNTED); //5 different spells used depending on mounted speed and if mount can fly or not if (flyspeed >= 4.1f) // Flying Reindeer m_caster->CastSpell(m_caster, 44827, true); //310% flying Reindeer else if (flyspeed >= 3.8f) // Flying Reindeer m_caster->CastSpell(m_caster, 44825, true); //280% flying Reindeer else if (flyspeed >= 1.6f) // Flying Reindeer m_caster->CastSpell(m_caster, 44824, true); //60% flying Reindeer else if (speed >= 2.0f) // Reindeer m_caster->CastSpell(m_caster, 25859, true); //100% ground Reindeer else // Reindeer m_caster->CastSpell(m_caster, 25858, true); //60% ground Reindeer return; } case 26074: // Holiday Cheer // implemented at client side return; // Polarity Shift case 28089: if (unitTarget) unitTarget->CastSpell(unitTarget, roll_chance_i(50) ? 28059 : 28084, true, NULL, NULL, m_caster->GetGUID()); break; // Polarity Shift case 39096: if (unitTarget) unitTarget->CastSpell(unitTarget, roll_chance_i(50) ? 39088 : 39091, true, NULL, NULL, m_caster->GetGUID()); break; case 29200: // Purify Helboar Meat { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; uint32 spell_id = roll_chance_i(50) ? 29277 // Summon Purified Helboar Meat : 29278; // Summon Toxic Helboar Meat m_caster->CastSpell(m_caster,spell_id,true,NULL); return; } case 29858: // Soulshatter if (unitTarget && unitTarget->CanHaveThreatList() && unitTarget->getThreatManager().getThreat(m_caster) > 0.0f) m_caster->CastSpell(unitTarget,32835,true); return; case 30458: // Nigh Invulnerability if (!m_CastItem) return; if (roll_chance_i(86)) // Nigh-Invulnerability - success m_caster->CastSpell(m_caster, 30456, true, m_CastItem); else // Complete Vulnerability - backfire in 14% casts m_caster->CastSpell(m_caster, 30457, true, m_CastItem); return; case 30507: // Poultryizer if (!m_CastItem) return; if (roll_chance_i(80)) // Poultryized! - success m_caster->CastSpell(unitTarget, 30501, true, m_CastItem); else // Poultryized! - backfire 20% m_caster->CastSpell(unitTarget, 30504, true, m_CastItem); return; case 35745: // Socrethar's Stone { uint32 spell_id; switch(m_caster->GetAreaId()) { case 3900: spell_id = 35743; break; // Socrethar Portal case 3742: spell_id = 35744; break; // Socrethar Portal default: return; } m_caster->CastSpell(m_caster, spell_id, true); return; } case 37674: // Chaos Blast { if (!unitTarget) return; int32 basepoints0 = 100; m_caster->CastCustomSpell(unitTarget, 37675, &basepoints0, NULL, NULL, true); return; } // Wrath of the Astromancer case 42784: { uint32 count = 0; for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if (ihit->effectMask & (1<<effIndex)) ++count; damage = 12000; // maybe wrong value damage /= count; SpellEntry const *spellInfo = sSpellStore.LookupEntry(42784); // now deal the damage for (std::list<TargetInfo>::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if (ihit->effectMask & (1<<effIndex)) { if (Unit* casttarget = Unit::GetUnit((*unitTarget), ihit->targetGUID)) m_caster->DealDamage(casttarget, damage, NULL, SPELL_DIRECT_DAMAGE, SPELL_SCHOOL_MASK_ARCANE, spellInfo, false); } return; } // Demon Broiled Surprise case 43723: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player *player = (Player*)m_caster; if (player && player->GetQuestStatus(11379) == QUEST_STATUS_INCOMPLETE) { Creature *creature = player->FindNearestCreature(19973, 10, false); if (!creature) { SendCastResult(SPELL_FAILED_NOT_HERE); return; } player->CastSpell(player, 43753, false); } return; } case 44875: // Complete Raptor Capture { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT) return; unitTarget->ToCreature()->ForcedDespawn(); //cast spell Raptor Capture Credit m_caster->CastSpell(m_caster, 42337, true, NULL); return; } case 47170: // Impale Leviroth { if (!unitTarget && unitTarget->GetEntry() != 26452 && unitTarget->HealthAbovePct(95)) return; m_caster->DealDamage(unitTarget, unitTarget->CountPctFromMaxHealth(93)); return; } case 49357: // Brewfest Mount Transformation if (m_caster->GetTypeId() != TYPEID_PLAYER) return; if (!m_caster->HasAuraType(SPELL_AURA_MOUNTED)) return; m_caster->RemoveAurasByType(SPELL_AURA_MOUNTED); // Ram for Alliance, Kodo for Horde if (m_caster->ToPlayer()->GetTeam() == ALLIANCE) { if (m_caster->GetSpeedRate(MOVE_RUN) >= 2.0f) // 100% Ram m_caster->CastSpell(m_caster, 43900, true); else // 60% Ram m_caster->CastSpell(m_caster, 43899, true); } else { if (m_caster->ToPlayer()->GetSpeedRate(MOVE_RUN) >= 2.0f) // 100% Kodo m_caster->CastSpell(m_caster, 49379, true); else // 60% Kodo m_caster->CastSpell(m_caster, 49378, true); } return; case 52845: // Brewfest Mount Transformation (Faction Swap) if (m_caster->GetTypeId() != TYPEID_PLAYER) return; if (!m_caster->HasAuraType(SPELL_AURA_MOUNTED)) return; m_caster->RemoveAurasByType(SPELL_AURA_MOUNTED); // Ram for Horde, Kodo for Alliance if (m_caster->ToPlayer()->GetTeam() == HORDE) { if (m_caster->GetSpeedRate(MOVE_RUN) >= 2.0f) // 100% Ram m_caster->CastSpell(m_caster, 43900, true); else // 60% Ram m_caster->CastSpell(m_caster, 43899, true); } else { if (m_caster->ToPlayer()->GetSpeedRate(MOVE_RUN) >= 2.0f) // 100% Kodo m_caster->CastSpell(m_caster, 49379, true); else // 60% Kodo m_caster->CastSpell(m_caster, 49378, true); } return; case 55004: // Nitro Boosts if (!m_CastItem) return; if (roll_chance_i(95)) // Nitro Boosts - success m_caster->CastSpell(m_caster, 54861, true, m_CastItem); else // Knocked Up - backfire 5% m_caster->CastSpell(m_caster, 46014, true, m_CastItem); return; case 50243: // Teach Language { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; // spell has a 1/3 chance to trigger one of the below if (roll_chance_i(66)) return; if (m_caster->ToPlayer()->GetTeam() == ALLIANCE) { // 1000001 - gnomish binary m_caster->CastSpell(m_caster, 50242, true); } else { // 01001000 - goblin binary m_caster->CastSpell(m_caster, 50246, true); } return; } case 51582: //Rocket Boots Engaged (Rocket Boots Xtreme and Rocket Boots Xtreme Lite) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; if (Battleground* bg = m_caster->ToPlayer()->GetBattleground()) bg->EventPlayerDroppedFlag(m_caster->ToPlayer()); m_caster->CastSpell(m_caster, 30452, true, NULL); return; } case 52759: // Ancestral Awakening if (!unitTarget) return; m_caster->CastCustomSpell(unitTarget, 52752, &damage, NULL, NULL, true); return; case 54171: //Divine Storm { m_caster->CastCustomSpell(unitTarget, 54172, &damage, 0, 0, true); return; } case 58418: // Portal to Orgrimmar case 58420: // Portal to Stormwind return; // implemented in EffectScript[0] case 62324: // Throw Passenger { if (m_targets.HasTraj()) { if (Vehicle *vehicle = m_caster->GetVehicleKit()) if (Unit *passenger = vehicle->GetPassenger(damage - 1)) { std::list<Unit*> unitList; // use 99 because it is 3d search SearchAreaTarget(unitList, 99, PUSH_DST_CENTER, SPELL_TARGETS_ENTRY, 33114); float minDist = 99 * 99; Vehicle *target = NULL; for (std::list<Unit*>::iterator itr = unitList.begin(); itr != unitList.end(); ++itr) { if (Vehicle *seat = (*itr)->GetVehicleKit()) if (!seat->GetPassenger(0)) if (Unit *device = seat->GetPassenger(2)) if (!device->GetCurrentSpell(CURRENT_CHANNELED_SPELL)) { float dist = (*itr)->GetExactDistSq(&m_targets.m_dstPos); if (dist < minDist) { minDist = dist; target = seat; } } } if (target && target->GetBase()->IsWithinDist2d(&m_targets.m_dstPos, GetSpellRadius(m_spellInfo, effIndex, false) * 2)) // now we use *2 because the location of the seat is not correct passenger->EnterVehicle(target, 0); else { passenger->ExitVehicle(); float x, y, z; m_targets.m_dstPos.GetPosition(x, y, z); passenger->GetMotionMaster()->MoveJump(x, y, z, m_targets.GetSpeedXY(), m_targets.GetSpeedZ()); } } } return; } case 64385: // Unusual Compass { m_caster->SetOrientation(float(urand(0,62832)) / 10000.0f); WorldPacket data; m_caster->BuildHeartBeatMsg(&data); m_caster->SendMessageToSet(&data,true); return; } } break; } case SPELLFAMILY_WARRIOR: // Charge if (m_spellInfo->SpellFamilyFlags & SPELLFAMILYFLAG_WARRIOR_CHARGE && m_spellInfo->SpellVisual[0] == 867) { int32 chargeBasePoints0 = damage; m_caster->CastCustomSpell(m_caster, 34846, &chargeBasePoints0, NULL, NULL, true); //Juggernaut crit bonus if (m_caster->HasAura(64976)) m_caster->CastSpell(m_caster, 65156, true); return; } //Slam if (m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_WARRIOR_SLAM && m_spellInfo->SpellIconID == 559) { int32 bp0 = damage; m_caster->CastCustomSpell(unitTarget, 50783, &bp0, NULL, NULL, true, 0); return; } // Execute if (m_spellInfo->SpellFamilyFlags[EFFECT_0] & SPELLFAMILYFLAG_WARRIOR_EXECUTE) { if (!unitTarget) return; spell_id = 20647; int32 rageUsed = std::min<int32>(300 - m_powerCost, m_caster->GetPower(POWER_RAGE)); int32 newRage = std::max<int32>(0, m_caster->GetPower(POWER_RAGE) - rageUsed); // Sudden Death rage save if (AuraEffect * aurEff = m_caster->GetAuraEffect(SPELL_AURA_PROC_TRIGGER_SPELL, SPELLFAMILY_GENERIC, 1989, EFFECT_0)) { int32 ragesave = SpellMgr::CalculateSpellEffectAmount(aurEff->GetSpellProto(), EFFECT_1) * 10; newRage = std::max(newRage, ragesave); } m_caster->SetPower(POWER_RAGE, uint32(newRage)); // Glyph of Execution bonus if (AuraEffect * aurEff = m_caster->GetAuraEffect(58367, EFFECT_0)) rageUsed += aurEff->GetAmount() * 10; bp = damage + int32(rageUsed * m_spellInfo->EffectDamageMultiplier[effIndex] + m_caster->GetTotalAttackPowerValue(BASE_ATTACK) * 0.2f); break; } // Concussion Blow if (m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_WARRIOR_CONCUSSION_BLOW) { m_damage += CalculatePctF(damage, m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); return; } switch(m_spellInfo->Id) { // Bloodthirst case 23881: { m_caster->CastCustomSpell(unitTarget, 23885, &damage, NULL, NULL, true, NULL); return; } } break; case SPELLFAMILY_WARLOCK: // Life Tap if (m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_WARLOCK_LIFETAP) { float spFactor = 0.0f; switch (m_spellInfo->Id) { case 11689: spFactor = 0.2f; break; case 27222: case 57946: spFactor = 0.5f; break; } int32 damage = int32(SpellMgr::CalculateSpellEffectAmount(m_spellInfo, 0) + (6.3875 * m_spellInfo->baseLevel)); int32 mana = int32(damage + (m_caster->ToPlayer()->GetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+SPELL_SCHOOL_SHADOW) * spFactor)); if (unitTarget && (int32(unitTarget->GetHealth()) > damage)) { // Shouldn't Appear in Combat Log unitTarget->ModifyHealth(-damage); // Improved Life Tap mod if (AuraEffect const * aurEff = m_caster->GetDummyAuraEffect(SPELLFAMILY_WARLOCK, 208, 0)) AddPctN(mana, aurEff->GetAmount()); m_caster->CastCustomSpell(unitTarget, 31818, &mana, NULL, NULL, true); // Mana Feed int32 manaFeedVal = 0; if (AuraEffect const * aurEff = m_caster->GetAuraEffect(SPELL_AURA_ADD_FLAT_MODIFIER, SPELLFAMILY_WARLOCK, 1982, 0)) manaFeedVal = aurEff->GetAmount(); if (manaFeedVal > 0) { ApplyPctN(manaFeedVal, mana); m_caster->CastCustomSpell(m_caster, 32553, &manaFeedVal, NULL, NULL, true, NULL); } } else SendCastResult(SPELL_FAILED_FIZZLE); return; } break; case SPELLFAMILY_DRUID: // Starfall if (m_spellInfo->SpellFamilyFlags[2] & SPELLFAMILYFLAG2_DRUID_STARFALL) { //Shapeshifting into an animal form or mounting cancels the effect. if (m_caster->GetCreatureType() == CREATURE_TYPE_BEAST || m_caster->IsMounted()) { if (m_triggeredByAuraSpell) m_caster->RemoveAurasDueToSpell(m_triggeredByAuraSpell->Id); return; } //Any effect which causes you to lose control of your character will supress the starfall effect. if (m_caster->HasUnitState(UNIT_STAT_STUNNED | UNIT_STAT_FLEEING | UNIT_STAT_ROOT | UNIT_STAT_CONFUSED)) return; m_caster->CastSpell(unitTarget, damage, true); return; } break; case SPELLFAMILY_PALADIN: // Divine Storm if (m_spellInfo->SpellFamilyFlags[1] & SPELLFAMILYFLAG1_PALADIN_DIVINESTORM && effIndex == 1) { int32 dmg = CalculatePctN(m_damage, damage); if (!unitTarget) unitTarget = m_caster; m_caster->CastCustomSpell(unitTarget, 54171, &dmg, 0, 0, true); return; } switch(m_spellInfo->Id) { case 31789: // Righteous Defense (step 1) { // Clear targets for eff 1 for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) ihit->effectMask &= ~(1<<1); // not empty (checked), copy Unit::AttackerSet attackers = unitTarget->getAttackers(); // selected from list 3 for (uint32 i = 0; i < std::min(size_t(3), attackers.size()); ++i) { Unit::AttackerSet::iterator aItr = attackers.begin(); std::advance(aItr, rand() % attackers.size()); AddUnitTarget((*aItr), 1); attackers.erase(aItr); } // now let next effect cast spell at each target. return; } } break; case SPELLFAMILY_SHAMAN: // Cleansing Totem Pulse if (m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_SHAMAN_TOTEM_EFFECTS && m_spellInfo->SpellIconID == 1673) { int32 bp1 = 1; // Cleansing Totem Effect if (unitTarget) m_caster->CastCustomSpell(unitTarget, 52025, NULL, &bp1, NULL, true, NULL, NULL, m_originalCasterGUID); return; } // Healing Stream Totem if (m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_SHAMAN_HEALING_STREAM) { if (!unitTarget) return; // Restorative Totems if (Unit *owner = m_caster->GetOwner()) if (AuraEffect *dummy = owner->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 338, 1)) AddPctN(damage, dummy->GetAmount()); m_caster->CastCustomSpell(unitTarget, 52042, &damage, 0, 0, true, 0, 0, m_originalCasterGUID); return; } // Mana Spring Totem if (m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_SHAMAN_MANA_SPRING) { if (!unitTarget || unitTarget->getPowerType() != POWER_MANA) return; m_caster->CastCustomSpell(unitTarget, 52032, &damage, 0, 0, true, 0, 0, m_originalCasterGUID); return; } // Lava Lash if (m_spellInfo->SpellFamilyFlags[2] & SPELLFAMILYFLAG2_SHAMAN_LAVA_LASH) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; if (m_caster->ToPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND)) { // Damage is increased by 25% if your off-hand weapon is enchanted with Flametongue. if (m_caster->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0x200000, 0, 0)) AddPctN(m_damage, damage); } return; } break; case SPELLFAMILY_DEATHKNIGHT: // Death strike if (m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_DK_DEATH_STRIKE) { uint32 count = unitTarget->GetDiseasesByCaster(m_caster->GetGUID()); int32 bp = int32(count * m_caster->CountPctFromMaxHealth(int32(m_spellInfo->EffectDamageMultiplier[0]))); // Improved Death Strike if (AuraEffect const * aurEff = m_caster->GetAuraEffect(SPELL_AURA_ADD_PCT_MODIFIER, SPELLFAMILY_DEATHKNIGHT, 2751, 0)) AddPctN(bp, m_caster->CalculateSpellDamage(m_caster, aurEff->GetSpellProto(), 2)); m_caster->CastCustomSpell(m_caster, 45470, &bp, NULL, NULL, false); return; } // Death Coil if (m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_DK_DEATH_COIL) { if (m_caster->IsFriendlyTo(unitTarget)) { int32 bp = int32(damage * 1.5f); m_caster->CastCustomSpell(unitTarget, 47633, &bp, NULL, NULL, true); } else { int32 bp = damage; m_caster->CastCustomSpell(unitTarget, 47632, &bp, NULL, NULL, true); } return; } switch (m_spellInfo->Id) { case 49560: // Death Grip Position pos; GetSummonPosition(effIndex, pos); if (Unit *unit = unitTarget->GetVehicleBase()) // what is this for? unit->CastSpell(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), damage, true); else if (!unitTarget->HasAuraType(SPELL_AURA_DEFLECT_SPELLS)) // Deterrence unitTarget->CastSpell(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), damage, true); return; case 46584: // Raise Dead if (m_caster->GetTypeId() != TYPEID_PLAYER) return; // Do we have talent Master of Ghouls? if (m_caster->HasAura(52143)) // summon as pet bp = 52150; else // or guardian bp = 46585; if (m_targets.HasDst()) targets.setDst(m_targets.m_dstPos); else { targets.setDst(*m_caster); // Corpse not found - take reagents (only not triggered cast can take them) triggered = false; } // Remove cooldown - summon spellls have category m_caster->ToPlayer()->RemoveSpellCooldown(m_spellInfo->Id, true); spell_id = 48289; break; // Raise dead - take reagents and trigger summon spells case 48289: if (m_targets.HasDst()) targets.setDst(m_targets.m_dstPos); spell_id = CalculateDamage(0, NULL); break; } break; } //spells triggered by dummy effect should not miss if (spell_id) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id); if (!spellInfo) { sLog->outError("EffectDummy of spell %u: triggering unknown spell id %i\n", m_spellInfo->Id, spell_id); return; } targets.setUnitTarget(unitTarget); Spell* spell = new Spell(m_caster, spellInfo, triggered, m_originalCasterGUID, true); if (bp) spell->SetSpellValue(SPELLVALUE_BASE_POINT0, bp); spell->prepare(&targets); } // pet auras if (PetAura const* petSpell = sSpellMgr->GetPetAura(m_spellInfo->Id,effIndex)) { m_caster->AddPetAura(petSpell); return; } // normal DB scripted effect sLog->outDebug("Spell ScriptStart spellid %u in EffectDummy(%u)", m_spellInfo->Id, effIndex); m_caster->GetMap()->ScriptsStart(sSpellScripts, uint32(m_spellInfo->Id | (effIndex << 24)), m_caster, unitTarget); // Script based implementation. Must be used only for not good for implementation in core spell effects // So called only for not proccessed cases if (gameObjTarget) sScriptMgr->OnDummyEffect(m_caster, m_spellInfo->Id, effIndex, gameObjTarget); else if (unitTarget && unitTarget->GetTypeId() == TYPEID_UNIT) sScriptMgr->OnDummyEffect(m_caster, m_spellInfo->Id, effIndex, unitTarget->ToCreature()); else if (itemTarget) sScriptMgr->OnDummyEffect(m_caster, m_spellInfo->Id, effIndex, itemTarget); } void Spell::EffectTriggerSpellWithValue(SpellEffIndex effIndex) { uint32 triggered_spell_id = m_spellInfo->EffectTriggerSpell[effIndex]; // normal case SpellEntry const *spellInfo = sSpellStore.LookupEntry(triggered_spell_id); if (!spellInfo) { sLog->outError("EffectTriggerSpellWithValue of spell %u: triggering unknown spell id %i", m_spellInfo->Id,triggered_spell_id); return; } int32 bp = damage; Unit * caster = GetTriggeredSpellCaster(spellInfo, m_caster, unitTarget); caster->CastCustomSpell(unitTarget,triggered_spell_id,&bp,&bp,&bp,true); } void Spell::EffectTriggerRitualOfSummoning(SpellEffIndex effIndex) { uint32 triggered_spell_id = m_spellInfo->EffectTriggerSpell[effIndex]; SpellEntry const *spellInfo = sSpellStore.LookupEntry(triggered_spell_id); if (!spellInfo) { sLog->outError("EffectTriggerRitualOfSummoning of spell %u: triggering unknown spell id %i", m_spellInfo->Id,triggered_spell_id); return; } finish(); m_caster->CastSpell(unitTarget,spellInfo,false); } void Spell::EffectForceCast(SpellEffIndex effIndex) { if (!unitTarget) return; uint32 triggered_spell_id = m_spellInfo->EffectTriggerSpell[effIndex]; // normal case SpellEntry const *spellInfo = sSpellStore.LookupEntry(triggered_spell_id); if (!spellInfo) { sLog->outError("EffectForceCast of spell %u: triggering unknown spell id %i", m_spellInfo->Id,triggered_spell_id); return; } if (damage) { switch(m_spellInfo->Id) { case 52588: // Skeletal Gryphon Escape case 48598: // Ride Flamebringer Cue unitTarget->RemoveAura(damage); break; case 52463: // Hide In Mine Car case 52349: // Overtake unitTarget->CastCustomSpell(unitTarget, spellInfo->Id, &damage, NULL, NULL, true, NULL, NULL, m_originalCasterGUID); return; case 72378: // Blood Nova case 73058: // Blood Nova spellInfo = sSpellMgr->GetSpellForDifficultyFromSpell(spellInfo, m_caster); break; } } switch (triggered_spell_id) { case 62056: case 63985: // Stone Grip Forcecast (10m, 25m) unitTarget->CastSpell(unitTarget, spellInfo, true); // Don't send m_originalCasterGUID param here or underlying return; // AureEffect::HandleAuraControlVehicle will fail on caster == target } Unit * caster = GetTriggeredSpellCaster(spellInfo, m_caster, unitTarget); caster->CastSpell(unitTarget, spellInfo, true, NULL, NULL, m_originalCasterGUID); } void Spell::EffectForceCastWithValue(SpellEffIndex effIndex) { if (!unitTarget) return; uint32 triggered_spell_id = m_spellInfo->EffectTriggerSpell[effIndex]; // normal case SpellEntry const *spellInfo = sSpellStore.LookupEntry(triggered_spell_id); if (!spellInfo) { sLog->outError("EffectForceCastWithValue of spell %u: triggering unknown spell id %i", m_spellInfo->Id,triggered_spell_id); return; } int32 bp = damage; Unit * caster = GetTriggeredSpellCaster(spellInfo, m_caster, unitTarget); caster->CastCustomSpell(unitTarget, spellInfo->Id, &bp, &bp, &bp, true, NULL, NULL, m_originalCasterGUID); } void Spell::EffectTriggerSpell(SpellEffIndex effIndex) { // only unit case known if (!unitTarget) { if (gameObjTarget || itemTarget) sLog->outError("Spell::EffectTriggerSpell (Spell: %u): Unsupported non-unit case!",m_spellInfo->Id); return; } uint32 triggered_spell_id = m_spellInfo->EffectTriggerSpell[effIndex]; Unit* originalCaster = NULL; // special cases switch(triggered_spell_id) { // Mirror Image case 58832: { // Glyph of Mirror Image if (m_caster->HasAura(63093)) m_caster->CastSpell(m_caster, 65047, true); // Mirror Image break; } // Vanish (not exist) case 18461: { unitTarget->RemoveMovementImpairingAuras(); unitTarget->RemoveAurasByType(SPELL_AURA_MOD_STALKED); // If this spell is given to an NPC, it must handle the rest using its own AI if (unitTarget->GetTypeId() != TYPEID_PLAYER) return; // See if we already are stealthed. If so, we're done. if (unitTarget->HasAura(1784)) return; // Reset cooldown on stealth if needed if (unitTarget->ToPlayer()->HasSpellCooldown(1784)) unitTarget->ToPlayer()->RemoveSpellCooldown(1784); triggered_spell_id = 1784; break; } // Demonic Empowerment -- succubus case 54437: { unitTarget->RemoveMovementImpairingAuras(); unitTarget->RemoveAurasByType(SPELL_AURA_MOD_STALKED); unitTarget->RemoveAurasByType(SPELL_AURA_MOD_STUN); // Cast Lesser Invisibility triggered_spell_id = 7870; break; } // just skip case 23770: // Sayge's Dark Fortune of * // not exist, common cooldown can be implemented in scripts if need. return; // Brittle Armor - (need add max stack of 24575 Brittle Armor) case 29284: { // Brittle Armor SpellEntry const* spell = sSpellStore.LookupEntry(24575); if (!spell) return; for (uint32 j = 0; j < spell->StackAmount; ++j) m_caster->CastSpell(unitTarget, spell->Id, true); return; } // Mercurial Shield - (need add max stack of 26464 Mercurial Shield) case 29286: { // Mercurial Shield SpellEntry const* spell = sSpellStore.LookupEntry(26464); if (!spell) return; for (uint32 j = 0; j < spell->StackAmount; ++j) m_caster->CastSpell(unitTarget, spell->Id, true); return; } // Righteous Defense case 31980: { m_caster->CastSpell(unitTarget, 31790, true); return; } // Cloak of Shadows case 35729: { uint32 dispelMask = GetDispellMask(DISPEL_ALL); Unit::AuraApplicationMap& Auras = unitTarget->GetAppliedAuras(); for (Unit::AuraApplicationMap::iterator iter = Auras.begin(); iter != Auras.end();) { // remove all harmful spells on you... SpellEntry const* spell = iter->second->GetBase()->GetSpellProto(); if ((spell->DmgClass == SPELL_DAMAGE_CLASS_MAGIC // only affect magic spells || ((1<<spell->Dispel) & dispelMask)) // ignore positive and passive auras && !iter->second->IsPositive() && !iter->second->GetBase()->IsPassive()) { m_caster->RemoveAura(iter); } else iter++; } return; } // Priest Shadowfiend (34433) need apply mana gain trigger aura on pet case 41967: { if (Unit *pet = unitTarget->GetGuardianPet()) pet->CastSpell(pet, 28305, true); return; } // Empower Rune Weapon case 53258: return; // skip, hack-added in spell effect // Snake Trap case 57879: originalCaster = m_originalCaster; break; // Coldflame case 33801: return; // just make the core stfu } // normal case SpellEntry const *spellInfo = sSpellStore.LookupEntry(triggered_spell_id); if (!spellInfo) { sLog->outError("EffectTriggerSpell of spell %u: triggering unknown spell id %i", m_spellInfo->Id,triggered_spell_id); return; } // Remove spell cooldown (not category) if spell triggering spell with cooldown and same category // Needed by freezing arrow and few other spells if (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->CategoryRecoveryTime && spellInfo->CategoryRecoveryTime && m_spellInfo->Category == spellInfo->Category) m_caster->ToPlayer()->RemoveSpellCooldown(spellInfo->Id); // Note: not exist spells with weapon req. and IsSpellHaveCasterSourceTargets == true // so this just for speedup places in else Unit * caster = GetTriggeredSpellCaster(spellInfo, m_caster, unitTarget); caster->CastSpell(unitTarget,spellInfo,true, 0, 0, (originalCaster ? originalCaster->GetGUID() : 0)); } void Spell::EffectTriggerMissileSpell(SpellEffIndex effIndex) { uint32 triggered_spell_id = m_spellInfo->EffectTriggerSpell[effIndex]; // normal case SpellEntry const *spellInfo = sSpellStore.LookupEntry(triggered_spell_id); if (!spellInfo) { sLog->outError("EffectTriggerMissileSpell of spell %u (eff: %u): triggering unknown spell id %u", m_spellInfo->Id,effIndex,triggered_spell_id); return; } if (m_CastItem) sLog->outStaticDebug("WORLD: cast Item spellId - %i", spellInfo->Id); // Remove spell cooldown (not category) if spell triggering spell with cooldown and same category // Needed by freezing arrow and few other spells if (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->CategoryRecoveryTime && spellInfo->CategoryRecoveryTime && m_spellInfo->Category == spellInfo->Category) m_caster->ToPlayer()->RemoveSpellCooldown(spellInfo->Id); float x, y, z; m_targets.m_dstPos.GetPosition(x, y, z); m_caster->CastSpell(x, y, z, spellInfo->Id, true, m_CastItem, 0, m_originalCasterGUID); } void Spell::EffectJump(SpellEffIndex effIndex) { if (m_caster->isInFlight()) return; float x,y,z,o; if (m_targets.getUnitTarget()) { m_targets.getUnitTarget()->GetContactPoint(m_caster,x,y,z,CONTACT_DISTANCE); o = m_caster->GetOrientation(); } else if (m_targets.getGOTarget()) { m_targets.getGOTarget()->GetContactPoint(m_caster,x,y,z,CONTACT_DISTANCE); o = m_caster->GetOrientation(); } else { sLog->outError("Spell::EffectJump - unsupported target mode for spell ID %u", m_spellInfo->Id); return; } float speedXY, speedZ; CalculateJumpSpeeds(effIndex, m_caster->GetExactDist2d(x, y), speedXY, speedZ); m_caster->GetMotionMaster()->MoveJump(x, y, z, speedXY, speedZ); } void Spell::EffectJumpDest(SpellEffIndex effIndex) { if (m_caster->isInFlight()) return; // Init dest coordinates float x,y,z,o; if (m_targets.HasDst()) { m_targets.m_dstPos.GetPosition(x, y, z); if (m_spellInfo->EffectImplicitTargetA[effIndex] == TARGET_DEST_TARGET_BACK) { // explicit cast data from client or server-side cast // some spell at client send caster Unit* pTarget = NULL; if (m_targets.getUnitTarget() && m_targets.getUnitTarget() != m_caster) pTarget = m_targets.getUnitTarget(); else if (m_caster->getVictim()) pTarget = m_caster->getVictim(); else if (m_caster->GetTypeId() == TYPEID_PLAYER) pTarget = ObjectAccessor::GetUnit(*m_caster, m_caster->ToPlayer()->GetSelection()); o = pTarget ? pTarget->GetOrientation() : m_caster->GetOrientation(); } else o = m_caster->GetOrientation(); } else { sLog->outError("Spell::EffectJumpDest - unsupported target mode for spell ID %u", m_spellInfo->Id); return; } float speedXY, speedZ; CalculateJumpSpeeds(effIndex, m_caster->GetExactDist2d(x, y), speedXY, speedZ); m_caster->GetMotionMaster()->MoveJump(x, y, z, speedXY, speedZ); } void Spell::CalculateJumpSpeeds(uint8 i, float dist, float & speedXY, float & speedZ) { if (m_spellInfo->EffectMiscValue[i]) speedZ = float(m_spellInfo->EffectMiscValue[i])/10; else if (m_spellInfo->EffectMiscValueB[i]) speedZ = float(m_spellInfo->EffectMiscValueB[i])/10; else speedZ = 10.0f; speedXY = dist * 10.0f / speedZ; } void Spell::EffectTeleportUnits(SpellEffIndex /*effIndex*/) { if (!unitTarget || unitTarget->isInFlight()) return; // Pre effects uint8 uiMaxSafeLevel = 0; switch (m_spellInfo->Id) { case 48129: // Scroll of Recall uiMaxSafeLevel = 40; case 60320: // Scroll of Recall II if (!uiMaxSafeLevel) uiMaxSafeLevel = 70; case 60321: // Scroll of Recal III if (!uiMaxSafeLevel) uiMaxSafeLevel = 80; if (unitTarget->getLevel() > uiMaxSafeLevel) { unitTarget->AddAura(60444,unitTarget); //Apply Lost! Aura return; } break; } // If not exist data for dest location - return if (!m_targets.HasDst()) { sLog->outError("Spell::EffectTeleportUnits - does not have destination for spell ID %u\n", m_spellInfo->Id); return; } // Init dest coordinates uint32 mapid = m_targets.m_dstPos.GetMapId(); if (mapid == MAPID_INVALID) mapid = unitTarget->GetMapId(); float x, y, z, orientation; m_targets.m_dstPos.GetPosition(x, y, z, orientation); if (!orientation && m_targets.getUnitTarget()) orientation = m_targets.getUnitTarget()->GetOrientation(); sLog->outDebug("Spell::EffectTeleportUnits - teleport unit to %u %f %f %f %f\n", mapid, x, y, z, orientation); if (mapid == unitTarget->GetMapId()) unitTarget->NearTeleportTo(x, y, z, orientation, unitTarget == m_caster); else if (unitTarget->GetTypeId() == TYPEID_PLAYER) unitTarget->ToPlayer()->TeleportTo(mapid, x, y, z, orientation, unitTarget == m_caster ? TELE_TO_SPELL : 0); // post effects for TARGET_DST_DB switch (m_spellInfo->Id) { // Dimensional Ripper - Everlook case 23442: { int32 r = irand(0, 119); if (r >= 70) // 7/12 success { if (r < 100) // 4/12 evil twin m_caster->CastSpell(m_caster, 23445, true); else // 1/12 fire m_caster->CastSpell(m_caster, 23449, true); } return; } // Ultrasafe Transporter: Toshley's Station case 36941: { if (roll_chance_i(50)) // 50% success { int32 rand_eff = urand(1, 7); switch (rand_eff) { case 1: // soul split - evil m_caster->CastSpell(m_caster, 36900, true); break; case 2: // soul split - good m_caster->CastSpell(m_caster, 36901, true); break; case 3: // Increase the size m_caster->CastSpell(m_caster, 36895, true); break; case 4: // Decrease the size m_caster->CastSpell(m_caster, 36893, true); break; case 5: // Transform { if (m_caster->ToPlayer()->GetTeam() == ALLIANCE) m_caster->CastSpell(m_caster, 36897, true); else m_caster->CastSpell(m_caster, 36899, true); break; } case 6: // chicken m_caster->CastSpell(m_caster, 36940, true); break; case 7: // evil twin m_caster->CastSpell(m_caster, 23445, true); break; } } return; } // Dimensional Ripper - Area 52 case 36890: { if (roll_chance_i(50)) // 50% success { int32 rand_eff = urand(1, 4); switch (rand_eff) { case 1: // soul split - evil m_caster->CastSpell(m_caster, 36900, true); break; case 2: // soul split - good m_caster->CastSpell(m_caster, 36901, true); break; case 3: // Increase the size m_caster->CastSpell(m_caster, 36895, true); break; case 4: // Transform { if (m_caster->ToPlayer()->GetTeam() == ALLIANCE) m_caster->CastSpell(m_caster, 36897, true); else m_caster->CastSpell(m_caster, 36899, true); break; } } } return; } } } void Spell::EffectApplyAura(SpellEffIndex effIndex) { if (!m_spellAura || !unitTarget) return; ASSERT(unitTarget == m_spellAura->GetOwner()); m_spellAura->_ApplyEffectForTargets(effIndex); } void Spell::EffectApplyAreaAura(SpellEffIndex effIndex) { if (!m_spellAura || !unitTarget) return; ASSERT (unitTarget == m_spellAura->GetOwner()); m_spellAura->_ApplyEffectForTargets(effIndex); } void Spell::EffectUnlearnSpecialization(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player *_player = (Player*)unitTarget; uint32 spellToUnlearn = m_spellInfo->EffectTriggerSpell[effIndex]; _player->removeSpell(spellToUnlearn); sLog->outDebug("Spell: Player %u has unlearned spell %u from NpcGUID: %u", _player->GetGUIDLow(), spellToUnlearn, m_caster->GetGUIDLow()); } void Spell::EffectPowerDrain(SpellEffIndex effIndex) { if (m_spellInfo->EffectMiscValue[effIndex] < 0 || m_spellInfo->EffectMiscValue[effIndex] >= int8(MAX_POWERS)) return; Powers powerType = Powers(m_spellInfo->EffectMiscValue[effIndex]); if (!unitTarget || !unitTarget->isAlive() || unitTarget->getPowerType() != powerType || damage < 0) return; // add spell damage bonus damage = m_caster->SpellDamageBonus(unitTarget, m_spellInfo, uint32(damage), SPELL_DIRECT_DAMAGE); // resilience reduce mana draining effect at spell crit damage reduction (added in 2.4) int32 power = damage; if (powerType == POWER_MANA) power -= unitTarget->GetSpellCritDamageReduction(power); int32 newDamage = -(unitTarget->ModifyPower(powerType, -int32(power))); float gainMultiplier = 0.0f; // Don`t restore from self drain if (m_caster != unitTarget) { gainMultiplier = SpellMgr::CalculateSpellEffectValueMultiplier(m_spellInfo, effIndex, m_originalCaster, this); int32 gain = int32(newDamage * gainMultiplier); m_caster->EnergizeBySpell(m_caster, m_spellInfo->Id, gain, powerType); } ExecuteLogEffectTakeTargetPower(effIndex, unitTarget, powerType, newDamage, gainMultiplier); } void Spell::EffectSendEvent(SpellEffIndex effIndex) { /* we do not handle a flag dropping or clicking on flag in battleground by sendevent system */ sLog->outDebug("Spell ScriptStart %u for spellid %u in EffectSendEvent ", m_spellInfo->EffectMiscValue[effIndex], m_spellInfo->Id); Object *pTarget; if (focusObject) pTarget = focusObject; else if (unitTarget) pTarget = unitTarget; else if (gameObjTarget) pTarget = gameObjTarget; else pTarget = NULL; m_caster->GetMap()->ScriptsStart(sEventScripts, m_spellInfo->EffectMiscValue[effIndex], m_caster, pTarget); } void Spell::EffectPowerBurn(SpellEffIndex effIndex) { if (m_spellInfo->EffectMiscValue[effIndex] < 0 || m_spellInfo->EffectMiscValue[effIndex] >= int8(MAX_POWERS)) return; Powers powerType = Powers(m_spellInfo->EffectMiscValue[effIndex]); if (!unitTarget || !unitTarget->isAlive() || unitTarget->getPowerType() != powerType || damage < 0) return; // burn x% of target's mana, up to maximum of 2x% of caster's mana (Mana Burn) if (m_spellInfo->ManaCostPercentage) { int32 maxDamage = int32(CalculatePctN(m_caster->GetMaxPower(powerType), damage * 2)); damage = int32(CalculatePctN(unitTarget->GetMaxPower(powerType), damage)); damage = std::min(damage, maxDamage); } int32 power = damage; // resilience reduce mana draining effect at spell crit damage reduction (added in 2.4) if (powerType == POWER_MANA) power -= unitTarget->GetSpellCritDamageReduction(power); int32 newDamage = -(unitTarget->ModifyPower(powerType, -power)); // NO - Not a typo - EffectPowerBurn uses effect value multiplier - not effect damage multiplier float dmgMultiplier = SpellMgr::CalculateSpellEffectValueMultiplier(m_spellInfo, effIndex, m_originalCaster, this); // add log data before multiplication (need power amount, not damage) ExecuteLogEffectTakeTargetPower(effIndex, unitTarget, powerType, newDamage, 0.0f); newDamage = int32(newDamage * dmgMultiplier); m_damage += newDamage; } void Spell::EffectHeal(SpellEffIndex /*effIndex*/) { } void Spell::SpellDamageHeal(SpellEffIndex /*effIndex*/) { if (unitTarget && unitTarget->isAlive() && damage >= 0) { // Try to get original caster Unit *caster = m_originalCasterGUID ? m_originalCaster : m_caster; // Skip if m_originalCaster not available if (!caster) return; int32 addhealth = damage; // Vessel of the Naaru (Vial of the Sunwell trinket) if (m_spellInfo->Id == 45064) { // Amount of heal - depends from stacked Holy Energy int damageAmount = 0; if (AuraEffect const * aurEff = m_caster->GetAuraEffect(45062, 0)) { damageAmount+= aurEff->GetAmount(); m_caster->RemoveAurasDueToSpell(45062); } addhealth += damageAmount; } // Swiftmend - consumes Regrowth or Rejuvenation else if (m_spellInfo->TargetAuraState == AURA_STATE_SWIFTMEND && unitTarget->HasAuraState(AURA_STATE_SWIFTMEND, m_spellInfo, m_caster)) { Unit::AuraEffectList const& RejorRegr = unitTarget->GetAuraEffectsByType(SPELL_AURA_PERIODIC_HEAL); // find most short by duration AuraEffect *targetAura = NULL; for (Unit::AuraEffectList::const_iterator i = RejorRegr.begin(); i != RejorRegr.end(); ++i) { if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_DRUID && (*i)->GetSpellProto()->SpellFamilyFlags[0] & 0x50) { if (!targetAura || (*i)->GetBase()->GetDuration() < targetAura->GetBase()->GetDuration()) targetAura = *i; } } if (!targetAura) { sLog->outError("Target(GUID:" UI64FMTD ") has aurastate AURA_STATE_SWIFTMEND but no matching aura.", unitTarget->GetGUID()); return; } int32 tickheal = targetAura->GetAmount(); if (Unit* auraCaster = targetAura->GetCaster()) tickheal = auraCaster->SpellHealingBonus(unitTarget, targetAura->GetSpellProto(), tickheal, DOT); //int32 tickheal = targetAura->GetSpellProto()->EffectBasePoints[idx] + 1; //It is said that talent bonus should not be included int32 tickcount = 0; // Rejuvenation if (targetAura->GetSpellProto()->SpellFamilyFlags[0] & 0x10) tickcount = 4; // Regrowth else // if (targetAura->GetSpellProto()->SpellFamilyFlags[0] & 0x40) tickcount = 6; addhealth += tickheal * tickcount; // Glyph of Swiftmend if (!caster->HasAura(54824)) unitTarget->RemoveAura(targetAura->GetId(), targetAura->GetCasterGUID()); //addhealth += tickheal * tickcount; //addhealth = caster->SpellHealingBonus(m_spellInfo, addhealth,HEAL, unitTarget); } // Glyph of Nourish else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DRUID && m_spellInfo->SpellFamilyFlags[1] & 0x2000000) { addhealth = caster->SpellHealingBonus(unitTarget, m_spellInfo, addhealth, HEAL); if (AuraEffect const* aurEff = m_caster->GetAuraEffect(62971, 0)) { Unit::AuraEffectList const& Periodic = unitTarget->GetAuraEffectsByType(SPELL_AURA_PERIODIC_HEAL); for (Unit::AuraEffectList::const_iterator i = Periodic.begin(); i != Periodic.end(); ++i) { if (m_caster->GetGUID() == (*i)->GetCasterGUID()) AddPctN(addhealth, aurEff->GetAmount()); } } } // Lifebloom - final heal coef multiplied by original DoT stack else if (m_spellInfo->Id == 33778) addhealth = caster->SpellHealingBonus(unitTarget, m_spellInfo, addhealth, HEAL, m_spellValue->EffectBasePoints[1]); // Riptide - increase healing done by Chain Heal else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_SHAMAN && m_spellInfo->SpellFamilyFlags[0] & 0x100) { addhealth = caster->SpellHealingBonus(unitTarget, m_spellInfo, addhealth, HEAL); if (AuraEffect * aurEff = unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_SHAMAN, 0, 0, 0x10, m_originalCasterGUID)) { addhealth = int32(addhealth * 1.25f); // consume aura unitTarget->RemoveAura(aurEff->GetBase()); } } // Death Pact - return pct of max health to caster else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && m_spellInfo->SpellFamilyFlags[0] & 0x00080000) addhealth = caster->SpellHealingBonus(unitTarget, m_spellInfo, int32(caster->CountPctFromMaxHealth(damage)), HEAL); else addhealth = caster->SpellHealingBonus(unitTarget, m_spellInfo, addhealth, HEAL); // Remove Grievious bite if fully healed if (unitTarget->HasAura(48920) && (unitTarget->GetHealth() + addhealth >= unitTarget->GetMaxHealth())) unitTarget->RemoveAura(48920); m_damage -= addhealth; } } void Spell::EffectHealPct(SpellEffIndex /*effIndex*/) { if (!unitTarget || !unitTarget->isAlive() || damage < 0) return; // Skip if m_originalCaster not available if (!m_originalCaster) return; // Rune Tap - Party if (m_spellInfo->Id == 59754 && unitTarget == m_caster) return; m_healing += m_originalCaster->SpellHealingBonus(unitTarget, m_spellInfo, unitTarget->CountPctFromMaxHealth(damage), HEAL); } void Spell::EffectHealMechanical(SpellEffIndex /*effIndex*/) { if (!unitTarget || !unitTarget->isAlive() || damage < 0) return; // Skip if m_originalCaster not available if (!m_originalCaster) return; m_healing += m_originalCaster->SpellHealingBonus(unitTarget, m_spellInfo, uint32(damage), HEAL); } void Spell::EffectHealthLeech(SpellEffIndex effIndex) { if (!unitTarget || !unitTarget->isAlive() || damage < 0) return; sLog->outDebug("HealthLeech :%i", damage); float healMultiplier = SpellMgr::CalculateSpellEffectValueMultiplier(m_spellInfo, effIndex, m_originalCaster, this); m_damage += damage; // get max possible damage, don't count overkill for heal uint32 healthGain = uint32(-unitTarget->GetHealthGain(-damage) * healMultiplier); if (m_caster->isAlive()) { healthGain = m_caster->SpellHealingBonus(m_caster, m_spellInfo, healthGain, HEAL); m_caster->HealBySpell(m_caster, m_spellInfo, uint32(healthGain)); } } void Spell::DoCreateItem(uint32 /*i*/, uint32 itemtype) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)unitTarget; uint32 newitemid = itemtype; ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(newitemid); if (!pProto) { player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); return; } // bg reward have some special in code work uint32 bgType = 0; switch(m_spellInfo->Id) { case SPELL_AV_MARK_WINNER: case SPELL_AV_MARK_LOSER: bgType = BATTLEGROUND_AV; break; case SPELL_WS_MARK_WINNER: case SPELL_WS_MARK_LOSER: bgType = BATTLEGROUND_WS; break; case SPELL_AB_MARK_WINNER: case SPELL_AB_MARK_LOSER: bgType = BATTLEGROUND_AB; break; default: break; } uint32 num_to_add = damage; if (num_to_add < 1) num_to_add = 1; if (num_to_add > pProto->GetMaxStackSize()) num_to_add = pProto->GetMaxStackSize(); // init items_count to 1, since 1 item will be created regardless of specialization int items_count=1; // the chance to create additional items float additionalCreateChance=0.0f; // the maximum number of created additional items uint8 additionalMaxNum=0; // get the chance and maximum number for creating extra items if (canCreateExtraItems(player, m_spellInfo->Id, additionalCreateChance, additionalMaxNum)) { // roll with this chance till we roll not to create or we create the max num while (roll_chance_f(additionalCreateChance) && items_count <= additionalMaxNum) ++items_count; } // really will be created more items num_to_add *= items_count; // can the player store the new item? ItemPosCountVec dest; uint32 no_space = 0; uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, newitemid, num_to_add, &no_space); if (msg != EQUIP_ERR_OK) { // convert to possible store amount if (msg == EQUIP_ERR_INVENTORY_FULL || msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS) num_to_add -= no_space; else { // if not created by another reason from full inventory or unique items amount limitation player->SendEquipError(msg, NULL, NULL, newitemid); return; } } if (num_to_add) { // create the new item and store it Item* pItem = player->StoreNewItem(dest, newitemid, true, Item::GenerateItemRandomPropertyId(newitemid)); // was it successful? return error if not if (!pItem) { player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); return; } // set the "Crafted by ..." property of the item if (pItem->GetProto()->Class != ITEM_CLASS_CONSUMABLE && pItem->GetProto()->Class != ITEM_CLASS_QUEST && newitemid != 6265 && newitemid != 6948) pItem->SetUInt32Value(ITEM_FIELD_CREATOR, player->GetGUIDLow()); // send info to the client if (pItem) player->SendNewItem(pItem, num_to_add, true, bgType == 0); // we succeeded in creating at least one item, so a levelup is possible if (bgType == 0) player->UpdateCraftSkill(m_spellInfo->Id); } /* // for battleground marks send by mail if not add all expected if (no_space > 0 && bgType) { if (Battleground* bg = sBattlegroundMgr->GetBattlegroundTemplate(BattlegroundTypeId(bgType))) bg->SendRewardMarkByMail(player, newitemid, no_space); } */ } void Spell::EffectCreateItem(SpellEffIndex effIndex) { DoCreateItem(effIndex,m_spellInfo->EffectItemType[effIndex]); ExecuteLogEffectCreateItem(effIndex, m_spellInfo->EffectItemType[effIndex]); } void Spell::EffectCreateItem2(SpellEffIndex effIndex) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)m_caster; uint32 item_id = m_spellInfo->EffectItemType[effIndex]; if (item_id) DoCreateItem(effIndex, item_id); // special case: fake item replaced by generate using spell_loot_template if (IsLootCraftingSpell(m_spellInfo)) { if (item_id) { if (!player->HasItemCount(item_id, 1)) return; // remove reagent uint32 count = 1; player->DestroyItemCount(item_id, count, true); // create some random items player->AutoStoreLoot(m_spellInfo->Id, LootTemplates_Spell); } else player->AutoStoreLoot(m_spellInfo->Id, LootTemplates_Spell); // create some random items } // TODO: ExecuteLogEffectCreateItem(i, m_spellInfo->EffectItemType[i]); } void Spell::EffectCreateRandomItem(SpellEffIndex /*effIndex*/) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player* player = (Player*)m_caster; // create some random items player->AutoStoreLoot(m_spellInfo->Id, LootTemplates_Spell); // TODO: ExecuteLogEffectCreateItem(i, m_spellInfo->EffectItemType[i]); } void Spell::EffectPersistentAA(SpellEffIndex effIndex) { if (!m_spellAura) { float radius = GetSpellRadiusForFriend(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[effIndex])); if (Player* modOwner = m_originalCaster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RADIUS, radius); Unit *caster = m_caster->GetEntry() == WORLD_TRIGGER ? m_originalCaster : m_caster; // Caster not in world, might be spell triggered from aura removal if (!caster->IsInWorld()) return; DynamicObject* dynObj = new DynamicObject; if (!dynObj->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_DYNAMICOBJECT), caster, m_spellInfo->Id, m_targets.m_dstPos, radius, false)) { delete dynObj; return; } caster->AddDynObject(dynObj); dynObj->GetMap()->Add(dynObj); if (Aura * aura = Aura::TryCreate(m_spellInfo, dynObj, caster, &m_spellValue->EffectBasePoints[0])) m_spellAura = aura; else { ASSERT(false); return; } m_spellAura->_RegisterForTargets(); } ASSERT(m_spellAura->GetDynobjOwner()); m_spellAura->_ApplyEffectForTargets(effIndex); } void Spell::EffectEnergize(SpellEffIndex effIndex) { if (!unitTarget) return; if (!unitTarget->isAlive()) return; if (m_spellInfo->EffectMiscValue[effIndex] < 0 || m_spellInfo->EffectMiscValue[effIndex] >= int8(MAX_POWERS)) return; Powers power = Powers(m_spellInfo->EffectMiscValue[effIndex]); // Some level depends spells int level_multiplier = 0; int level_diff = 0; switch (m_spellInfo->Id) { case 9512: // Restore Energy level_diff = m_caster->getLevel() - 40; level_multiplier = 2; break; case 24571: // Blood Fury level_diff = m_caster->getLevel() - 60; level_multiplier = 10; break; case 24532: // Burst of Energy level_diff = m_caster->getLevel() - 60; level_multiplier = 4; break; case 31930: // Judgements of the Wise case 63375: // Improved Stormstrike case 68082: // Glyph of Seal of Command damage = int32(CalculatePctN(unitTarget->GetCreateMana(), damage)); break; case 48542: // Revitalize damage = int32(CalculatePctN(unitTarget->GetMaxPower(power), damage)); break; default: break; } if (level_diff > 0) damage -= level_multiplier * level_diff; if (damage < 0) return; if (unitTarget->GetMaxPower(power) == 0) return; m_caster->EnergizeBySpell(unitTarget, m_spellInfo->Id, damage, power); // Mad Alchemist's Potion if (m_spellInfo->Id == 45051) { // find elixirs on target bool guardianFound = false; bool battleFound = false; Unit::AuraApplicationMap& Auras = unitTarget->GetAppliedAuras(); for (Unit::AuraApplicationMap::iterator itr = Auras.begin(); itr != Auras.end(); ++itr) { uint32 spell_id = itr->second->GetBase()->GetId(); if (!guardianFound) if (sSpellMgr->IsSpellMemberOfSpellGroup(spell_id, SPELL_GROUP_ELIXIR_GUARDIAN)) guardianFound = true; if (!battleFound) if (sSpellMgr->IsSpellMemberOfSpellGroup(spell_id, SPELL_GROUP_ELIXIR_BATTLE)) battleFound = true; if (battleFound && guardianFound) break; } // get all available elixirs by mask and spell level std::set<uint32> avalibleElixirs; if (!guardianFound) sSpellMgr->GetSetOfSpellsInSpellGroup(SPELL_GROUP_ELIXIR_GUARDIAN, avalibleElixirs); if (!battleFound) sSpellMgr->GetSetOfSpellsInSpellGroup(SPELL_GROUP_ELIXIR_BATTLE, avalibleElixirs); for (std::set<uint32>::iterator itr = avalibleElixirs.begin(); itr != avalibleElixirs.end() ;) { SpellEntry const *spellInfo = sSpellStore.LookupEntry(*itr); if (spellInfo->spellLevel < m_spellInfo->spellLevel || spellInfo->spellLevel > unitTarget->getLevel()) avalibleElixirs.erase(itr++); else if (sSpellMgr->IsSpellMemberOfSpellGroup(*itr, SPELL_GROUP_ELIXIR_SHATTRATH)) avalibleElixirs.erase(itr++); else if (sSpellMgr->IsSpellMemberOfSpellGroup(*itr, SPELL_GROUP_ELIXIR_UNSTABLE)) avalibleElixirs.erase(itr++); else ++itr; } if (!avalibleElixirs.empty()) { // cast random elixir on target uint32 rand_spell = urand(0,avalibleElixirs.size()-1); std::set<uint32>::iterator itr = avalibleElixirs.begin(); std::advance(itr, rand_spell); m_caster->CastSpell(unitTarget,*itr,true,m_CastItem); } } } void Spell::EffectEnergizePct(SpellEffIndex effIndex) { if (!unitTarget) return; if (!unitTarget->isAlive()) return; if (m_spellInfo->EffectMiscValue[effIndex] < 0 || m_spellInfo->EffectMiscValue[effIndex] >= int8(MAX_POWERS)) return; Powers power = Powers(m_spellInfo->EffectMiscValue[effIndex]); uint32 maxPower = unitTarget->GetMaxPower(power); if (maxPower == 0) return; uint32 gain = CalculatePctN(maxPower, damage); m_caster->EnergizeBySpell(unitTarget, m_spellInfo->Id, gain, power); } void Spell::SendLoot(uint64 guid, LootType loottype) { Player* player = m_caster->ToPlayer(); if (!player) return; if (gameObjTarget) { // special case, already has GossipHello inside so return and avoid calling twice if (gameObjTarget->GetGoType() == GAMEOBJECT_TYPE_GOOBER) { gameObjTarget->Use(m_caster); return; } if (sScriptMgr->OnGossipHello(player, gameObjTarget)) return; gameObjTarget->AI()->GossipHello(player); switch (gameObjTarget->GetGoType()) { case GAMEOBJECT_TYPE_DOOR: case GAMEOBJECT_TYPE_BUTTON: gameObjTarget->UseDoorOrButton(); player->GetMap()->ScriptsStart(sGameObjectScripts, gameObjTarget->GetDBTableGUIDLow(), player, gameObjTarget); return; case GAMEOBJECT_TYPE_QUESTGIVER: // start or end quest player->PrepareQuestMenu(guid); player->SendPreparedQuest(guid); return; case GAMEOBJECT_TYPE_SPELL_FOCUS: // triggering linked GO if (uint32 trapEntry = gameObjTarget->GetGOInfo()->spellFocus.linkedTrapId) gameObjTarget->TriggeringLinkedGameObject(trapEntry,m_caster); return; case GAMEOBJECT_TYPE_CHEST: // TODO: possible must be moved to loot release (in different from linked triggering) if (gameObjTarget->GetGOInfo()->chest.eventId) { sLog->outDebug("Chest ScriptStart id %u for GO %u", gameObjTarget->GetGOInfo()->chest.eventId,gameObjTarget->GetDBTableGUIDLow()); player->GetMap()->ScriptsStart(sEventScripts, gameObjTarget->GetGOInfo()->chest.eventId, player, gameObjTarget); } // triggering linked GO if (uint32 trapEntry = gameObjTarget->GetGOInfo()->chest.linkedTrapId) gameObjTarget->TriggeringLinkedGameObject(trapEntry,m_caster); // Don't return, let loots been taken default: break; } } // Send loot player->SendLoot(guid, loottype); } void Spell::EffectOpenLock(SpellEffIndex effIndex) { if (m_caster->GetTypeId() != TYPEID_PLAYER) { sLog->outDebug("WORLD: Open Lock - No Player Caster!"); return; } Player* player = (Player*)m_caster; uint32 lockId = 0; uint64 guid = 0; // Get lockId if (gameObjTarget) { GameObjectInfo const* goInfo = gameObjTarget->GetGOInfo(); // Arathi Basin banner opening ! if ((goInfo->type == GAMEOBJECT_TYPE_BUTTON && goInfo->button.noDamageImmune) || (goInfo->type == GAMEOBJECT_TYPE_GOOBER && goInfo->goober.losOK)) { //CanUseBattlegroundObject() already called in CheckCast() // in battleground check if (Battleground *bg = player->GetBattleground()) { bg->EventPlayerClickedOnFlag(player, gameObjTarget); return; } } else if (goInfo->type == GAMEOBJECT_TYPE_FLAGSTAND) { //CanUseBattlegroundObject() already called in CheckCast() // in battleground check if (Battleground *bg = player->GetBattleground()) { if (bg->GetTypeID(true) == BATTLEGROUND_EY) bg->EventPlayerClickedOnFlag(player, gameObjTarget); return; } }else if (m_spellInfo->Id == 1842 && gameObjTarget->GetGOInfo()->type == GAMEOBJECT_TYPE_TRAP && gameObjTarget->GetOwner()) { gameObjTarget->SetLootState(GO_JUST_DEACTIVATED); return; } // TODO: Add script for spell 41920 - Filling, becouse server it freze when use this spell // handle outdoor pvp object opening, return true if go was registered for handling // these objects must have been spawned by outdoorpvp! else if (gameObjTarget->GetGOInfo()->type == GAMEOBJECT_TYPE_GOOBER && sOutdoorPvPMgr->HandleOpenGo(player, gameObjTarget->GetGUID())) return; lockId = goInfo->GetLockId(); guid = gameObjTarget->GetGUID(); } else if (itemTarget) { lockId = itemTarget->GetProto()->LockID; guid = itemTarget->GetGUID(); } else { sLog->outDebug("WORLD: Open Lock - No GameObject/Item Target!"); return; } SkillType skillId = SKILL_NONE; int32 reqSkillValue = 0; int32 skillValue; SpellCastResult res = CanOpenLock(effIndex, lockId, skillId, reqSkillValue, skillValue); if (res != SPELL_CAST_OK) { SendCastResult(res); return; } if (gameObjTarget) SendLoot(guid, LOOT_SKINNING); else itemTarget->SetFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_UNLOCKED); // not allow use skill grow at item base open if (!m_CastItem && skillId != SKILL_NONE) { // update skill if really known if (uint32 pureSkillValue = player->GetPureSkillValue(skillId)) { if (gameObjTarget) { // Allow one skill-up until respawned if (!gameObjTarget->IsInSkillupList(player->GetGUIDLow()) && player->UpdateGatherSkill(skillId, pureSkillValue, reqSkillValue)) gameObjTarget->AddToSkillupList(player->GetGUIDLow()); } else if (itemTarget) { // Do one skill-up player->UpdateGatherSkill(skillId, pureSkillValue, reqSkillValue); } } } ExecuteLogEffectOpenLock(effIndex, gameObjTarget ? (Object*)gameObjTarget : (Object*)itemTarget); } void Spell::EffectSummonChangeItem(SpellEffIndex effIndex) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player *player = (Player*)m_caster; // applied only to using item if (!m_CastItem) return; // ... only to item in own inventory/bank/equip_slot if (m_CastItem->GetOwnerGUID() != player->GetGUID()) return; uint32 newitemid = m_spellInfo->EffectItemType[effIndex]; if (!newitemid) return; uint16 pos = m_CastItem->GetPos(); Item *pNewItem = Item::CreateItem(newitemid, 1, player); if (!pNewItem) return; for (uint8 j = PERM_ENCHANTMENT_SLOT; j <= TEMP_ENCHANTMENT_SLOT; ++j) if (m_CastItem->GetEnchantmentId(EnchantmentSlot(j))) pNewItem->SetEnchantment(EnchantmentSlot(j), m_CastItem->GetEnchantmentId(EnchantmentSlot(j)), m_CastItem->GetEnchantmentDuration(EnchantmentSlot(j)), m_CastItem->GetEnchantmentCharges(EnchantmentSlot(j))); if (m_CastItem->GetUInt32Value(ITEM_FIELD_DURABILITY) < m_CastItem->GetUInt32Value(ITEM_FIELD_MAXDURABILITY)) { double lossPercent = 1 - m_CastItem->GetUInt32Value(ITEM_FIELD_DURABILITY) / double(m_CastItem->GetUInt32Value(ITEM_FIELD_MAXDURABILITY)); player->DurabilityLoss(pNewItem, lossPercent); } if (player->IsInventoryPos(pos)) { ItemPosCountVec dest; uint8 msg = player->CanStoreItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), dest, pNewItem, true); if (msg == EQUIP_ERR_OK) { player->DestroyItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), true); // prevent crash at access and unexpected charges counting with item update queue corrupt if (m_CastItem == m_targets.getItemTarget()) m_targets.setItemTarget(NULL); m_CastItem = NULL; player->StoreItem(dest, pNewItem, true); return; } } else if (player->IsBankPos(pos)) { ItemPosCountVec dest; uint8 msg = player->CanBankItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), dest, pNewItem, true); if (msg == EQUIP_ERR_OK) { player->DestroyItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), true); // prevent crash at access and unexpected charges counting with item update queue corrupt if (m_CastItem == m_targets.getItemTarget()) m_targets.setItemTarget(NULL); m_CastItem = NULL; player->BankItem(dest, pNewItem, true); return; } } else if (player->IsEquipmentPos(pos)) { uint16 dest; player->DestroyItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), true); uint8 msg = player->CanEquipItem(m_CastItem->GetSlot(), dest, pNewItem, true); if (msg == EQUIP_ERR_OK || msg == EQUIP_ERR_CANT_DO_RIGHT_NOW) { if (msg == EQUIP_ERR_CANT_DO_RIGHT_NOW) dest = EQUIPMENT_SLOT_MAINHAND; // prevent crash at access and unexpected charges counting with item update queue corrupt if (m_CastItem == m_targets.getItemTarget()) m_targets.setItemTarget(NULL); m_CastItem = NULL; player->EquipItem(dest, pNewItem, true); player->AutoUnequipOffhandIfNeed(); return; } } // fail delete pNewItem; } void Spell::EffectProficiency(SpellEffIndex /*effIndex*/) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player *p_target = (Player*)unitTarget; uint32 subClassMask = m_spellInfo->EquippedItemSubClassMask; if (m_spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON && !(p_target->GetWeaponProficiency() & subClassMask)) { p_target->AddWeaponProficiency(subClassMask); p_target->SendProficiency(ITEM_CLASS_WEAPON, p_target->GetWeaponProficiency()); } if (m_spellInfo->EquippedItemClass == ITEM_CLASS_ARMOR && !(p_target->GetArmorProficiency() & subClassMask)) { p_target->AddArmorProficiency(subClassMask); p_target->SendProficiency(ITEM_CLASS_ARMOR, p_target->GetArmorProficiency()); } } void Spell::EffectSummonType(SpellEffIndex effIndex) { uint32 entry = m_spellInfo->EffectMiscValue[effIndex]; if (!entry) return; SummonPropertiesEntry const *properties = sSummonPropertiesStore.LookupEntry(m_spellInfo->EffectMiscValueB[effIndex]); if (!properties) { sLog->outError("EffectSummonType: Unhandled summon type %u", m_spellInfo->EffectMiscValueB[effIndex]); return; } if (!m_originalCaster) return; int32 duration = GetSpellDuration(m_spellInfo); if (Player* modOwner = m_originalCaster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration); Position pos; GetSummonPosition(effIndex, pos); /*//totem must be at same Z in case swimming caster and etc. if (fabs(z - m_caster->GetPositionZ()) > 5) z = m_caster->GetPositionZ(); uint8 level = m_caster->getLevel(); // level of creature summoned using engineering item based at engineering skill level if (m_caster->GetTypeId() == TYPEID_PLAYER && m_CastItem) { ItemPrototype const *proto = m_CastItem->GetProto(); if (proto && proto->RequiredSkill == SKILL_ENGINERING) { uint16 skill202 = m_caster->ToPlayer()->GetSkillValue(SKILL_ENGINERING); if (skill202) level = skill202/5; } }*/ TempSummon *summon = NULL; switch (properties->Category) { default: if (properties->Flags & 512) { SummonGuardian(effIndex, entry, properties); break; } switch (properties->Type) { case SUMMON_TYPE_PET: case SUMMON_TYPE_GUARDIAN: case SUMMON_TYPE_GUARDIAN2: case SUMMON_TYPE_MINION: SummonGuardian(effIndex, entry, properties); break; case SUMMON_TYPE_VEHICLE: case SUMMON_TYPE_VEHICLE2: if (m_originalCaster) summon = m_caster->GetMap()->SummonCreature(entry, pos, properties, duration, m_originalCaster); break; case SUMMON_TYPE_TOTEM: { summon = m_caster->GetMap()->SummonCreature(entry, pos, properties, duration, m_originalCaster); if (!summon || !summon->isTotem()) return; if (damage) // if not spell info, DB values used { summon->SetMaxHealth(damage); summon->SetHealth(damage); } //summon->SetUInt32Value(UNIT_CREATED_BY_SPELL,m_spellInfo->Id); if (m_originalCaster->GetTypeId() == TYPEID_PLAYER && properties->Slot >= SUMMON_SLOT_TOTEM && properties->Slot < MAX_TOTEM_SLOT) { // set display id depending on race uint32 displayId = m_originalCaster->GetModelForTotem(PlayerTotemType(properties->Id)); summon->SetNativeDisplayId(displayId); summon->SetDisplayId(displayId); //summon->SendUpdateToPlayerm_originalCaster->ToPlayer(); WorldPacket data(SMSG_TOTEM_CREATED, 1+8+4+4); data << uint8(properties->Slot-1); data << uint64(m_originalCaster->GetGUID()); data << uint32(duration); data << uint32(m_spellInfo->Id); m_originalCaster->ToPlayer()->SendDirectMessage(&data); } break; } case SUMMON_TYPE_MINIPET: { summon = m_caster->GetMap()->SummonCreature(entry, pos, properties, duration, m_originalCaster); if (!summon || !summon->HasUnitTypeMask(UNIT_MASK_MINION)) return; //summon->InitPetCreateSpells(); // e.g. disgusting oozeling has a create spell as summon... summon->SelectLevel(summon->GetCreatureInfo()); // some summoned creaters have different from 1 DB data for level/hp summon->SetUInt32Value(UNIT_NPC_FLAGS, summon->GetCreatureInfo()->npcflag); summon->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); summon->AI()->EnterEvadeMode(); std::string name = m_originalCaster->GetName(); name.append(petTypeSuffix[3]); summon->SetName(name); break; } default: { float radius = GetSpellRadiusForHostile(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[effIndex])); uint32 amount = damage > 0 ? damage : 1; if (m_spellInfo->Id == 18662) // Curse of Doom amount = 1; for (uint32 count = 0; count < amount; ++count) { GetSummonPosition(effIndex, pos, radius, count); TempSummonType summonType = (duration == 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN; summon = m_originalCaster->SummonCreature(entry, pos, summonType, duration); if (!summon) continue; if (properties->Category == SUMMON_CATEGORY_ALLY) { summon->SetUInt64Value(UNIT_FIELD_SUMMONEDBY, m_originalCaster->GetGUID()); summon->setFaction(m_originalCaster->getFaction()); summon->SetUInt32Value(UNIT_CREATED_BY_SPELL, m_spellInfo->Id); } ExecuteLogEffectSummonObject(effIndex, summon); } return; } }//switch break; case SUMMON_CATEGORY_PET: SummonGuardian(effIndex, entry, properties); break; case SUMMON_CATEGORY_PUPPET: summon = m_caster->GetMap()->SummonCreature(entry, pos, properties, duration, m_originalCaster); break; case SUMMON_CATEGORY_VEHICLE: { float x, y, z; m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE); summon = m_caster->GetMap()->SummonCreature(entry, pos, properties, duration, m_caster); if (!summon || !summon->IsVehicle()) return; if (m_spellInfo->EffectBasePoints[effIndex]) { SpellEntry const *spellProto = sSpellStore.LookupEntry(SpellMgr::CalculateSpellEffectAmount(m_spellInfo, effIndex)); if (spellProto) m_caster->CastSpell(summon, spellProto, true); } m_caster->EnterVehicle(summon->GetVehicleKit()); break; } } if (summon) { summon->SetUInt32Value(UNIT_CREATED_BY_SPELL, m_spellInfo->Id); summon->SetCreatorGUID(m_originalCaster->GetGUID()); ExecuteLogEffectSummonObject(effIndex, summon); } } void Spell::EffectLearnSpell(SpellEffIndex effIndex) { if (!unitTarget) return; if (unitTarget->GetTypeId() != TYPEID_PLAYER) { if (m_caster->GetTypeId() == TYPEID_PLAYER) EffectLearnPetSpell(effIndex); return; } Player *player = (Player*)unitTarget; uint32 spellToLearn = (m_spellInfo->Id == 483 || m_spellInfo->Id == 55884) ? damage : m_spellInfo->EffectTriggerSpell[effIndex]; player->learnSpell(spellToLearn, false); sLog->outDebug("Spell: Player %u has learned spell %u from NpcGUID=%u", player->GetGUIDLow(), spellToLearn, m_caster->GetGUIDLow()); } typedef std::list< std::pair<uint32, uint64> > DispelList; typedef std::list< std::pair<Aura *, uint8> > DispelChargesList; void Spell::EffectDispel(SpellEffIndex effIndex) { if (!unitTarget) return; DispelChargesList dispel_list; // Create dispel mask by dispel type uint32 dispel_type = m_spellInfo->EffectMiscValue[effIndex]; uint32 dispelMask = GetDispellMask(DispelType(dispel_type)); // we should not be able to dispel diseases if the target is affected by unholy blight if (dispelMask & (1 << DISPEL_DISEASE) && unitTarget->HasAura(50536)) dispelMask &= ~(1 << DISPEL_DISEASE); Unit::AuraMap const& auras = unitTarget->GetOwnedAuras(); for (Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { Aura * aura = itr->second; AuraApplication * aurApp = aura->GetApplicationOfTarget(unitTarget->GetGUID()); if (!aurApp) continue; if ((1<<aura->GetSpellProto()->Dispel) & dispelMask) { if (aura->GetSpellProto()->Dispel == DISPEL_MAGIC) { bool positive = aurApp->IsPositive() ? (!(aura->GetSpellProto()->AttributesEx & SPELL_ATTR1_NEGATIVE)) : false; // do not remove positive auras if friendly target // negative auras if non-friendly target if (positive == unitTarget->IsFriendlyTo(m_caster)) continue; } // The charges / stack amounts don't count towards the total number of auras that can be dispelled. // Ie: A dispel on a target with 5 stacks of Winters Chill and a Polymorph has 1 / (1 + 1) -> 50% chance to dispell // Polymorph instead of 1 / (5 + 1) -> 16%. bool dispel_charges = aura->GetSpellProto()->AttributesEx7 & SPELL_ATTR7_DISPEL_CHARGES; uint8 charges = dispel_charges ? aura->GetCharges() : aura->GetStackAmount(); if (charges > 0) dispel_list.push_back(std::make_pair(aura, charges)); } } if (dispel_list.empty()) return; // Ok if exist some buffs for dispel try dispel it uint32 failCount = 0; DispelList success_list; WorldPacket dataFail(SMSG_DISPEL_FAILED, 8+8+4+4+damage*4); // dispel N = damage buffs (or while exist buffs for dispel) for (int32 count = 0; count < damage && !dispel_list.empty();) { // Random select buff for dispel DispelChargesList::iterator itr = dispel_list.begin(); std::advance(itr, urand(0, dispel_list.size() - 1)); bool success = false; // 2.4.3 Patch Notes: "Dispel effects will no longer attempt to remove effects that have 100% dispel resistance." if (!GetDispelChance(itr->first->GetCaster(), unitTarget, itr->first->GetId(), !unitTarget->IsFriendlyTo(m_caster), &success)) { dispel_list.erase(itr); continue; } else { if (success) { success_list.push_back(std::make_pair(itr->first->GetId(), itr->first->GetCasterGUID())); --itr->second; if (itr->second <= 0) dispel_list.erase(itr); } else { if (!failCount) { // Failed to dispell dataFail << uint64(m_caster->GetGUID()); // Caster GUID dataFail << uint64(unitTarget->GetGUID()); // Victim GUID dataFail << uint32(m_spellInfo->Id); // dispel spell id } ++failCount; dataFail << uint32(itr->first->GetId()); // Spell Id } ++count; } } if (failCount) m_caster->SendMessageToSet(&dataFail, true); if (success_list.empty()) return; WorldPacket dataSuccess(SMSG_SPELLDISPELLOG, 8+8+4+1+4+damage*5); // Send packet header dataSuccess.append(unitTarget->GetPackGUID()); // Victim GUID dataSuccess.append(m_caster->GetPackGUID()); // Caster GUID dataSuccess << uint32(m_spellInfo->Id); // dispel spell id dataSuccess << uint8(0); // not used dataSuccess << uint32(success_list.size()); // count for (DispelList::iterator itr = success_list.begin(); itr != success_list.end(); ++itr) { // Send dispelled spell info dataSuccess << uint32(itr->first); // Spell Id dataSuccess << uint8(0); // 0 - dispelled !=0 cleansed unitTarget->RemoveAurasDueToSpellByDispel(itr->first, itr->second, m_caster); } m_caster->SendMessageToSet(&dataSuccess, true); // On success dispel // Devour Magic if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->Category == SPELLCATEGORY_DEVOUR_MAGIC) { int32 heal_amount = SpellMgr::CalculateSpellEffectAmount(m_spellInfo, 1); m_caster->CastCustomSpell(m_caster, 19658, &heal_amount, NULL, NULL, true); // Glyph of Felhunter if (Unit * pOwner = m_caster->GetOwner()) if (pOwner->GetAura(56249)) pOwner->CastCustomSpell(pOwner, 19658, &heal_amount, NULL, NULL, true); } } void Spell::EffectDualWield(SpellEffIndex /*effIndex*/) { unitTarget->SetCanDualWield(true); if (unitTarget->GetTypeId() == TYPEID_UNIT) unitTarget->ToCreature()->UpdateDamagePhysical(OFF_ATTACK); } void Spell::EffectPull(SpellEffIndex effIndex) { // TODO: create a proper pull towards distract spell center for distract EffectNULL(effIndex); } void Spell::EffectDistract(SpellEffIndex /*effIndex*/) { // Check for possible target if (!unitTarget || unitTarget->isInCombat()) return; // target must be OK to do this if (unitTarget->HasUnitState(UNIT_STAT_CONFUSED | UNIT_STAT_STUNNED | UNIT_STAT_FLEEING)) return; float angle = unitTarget->GetAngle(&m_targets.m_dstPos); if (unitTarget->GetTypeId() == TYPEID_PLAYER) { // For players just turn them unitTarget->ToPlayer()->SetPosition(unitTarget->GetPositionX(), unitTarget->GetPositionY(), unitTarget->GetPositionZ(), angle, false); unitTarget->ToPlayer()->SendTeleportAckPacket(); } else { // Set creature Distracted, Stop it, And turn it unitTarget->SetOrientation(angle); unitTarget->StopMoving(); unitTarget->GetMotionMaster()->MoveDistract(damage * IN_MILLISECONDS); } } void Spell::EffectPickPocket(SpellEffIndex /*effIndex*/) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; // victim must be creature and attackable if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT || m_caster->IsFriendlyTo(unitTarget)) return; // victim have to be alive and humanoid or undead if (unitTarget->isAlive() && (unitTarget->GetCreatureTypeMask() &CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD) != 0) m_caster->ToPlayer()->SendLoot(unitTarget->GetGUID(),LOOT_PICKPOCKETING); } void Spell::EffectAddFarsight(SpellEffIndex effIndex) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; float radius = GetSpellRadiusForFriend(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[effIndex])); int32 duration = GetSpellDuration(m_spellInfo); // Caster not in world, might be spell triggered from aura removal if (!m_caster->IsInWorld()) return; DynamicObject* dynObj = new DynamicObject; if (!dynObj->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_DYNAMICOBJECT), m_caster, m_spellInfo->Id, m_targets.m_dstPos, radius, true)) { delete dynObj; return; } dynObj->SetDuration(duration); dynObj->SetUInt32Value(DYNAMICOBJECT_BYTES, 0x80000002); m_caster->AddDynObject(dynObj); dynObj->setActive(true); //must before add to map to be put in world container dynObj->GetMap()->Add(dynObj); //grid will also be loaded // Need to update visibility of object for client to accept farsight guid m_caster->ToPlayer()->SetViewpoint(dynObj, true); //m_caster->ToPlayer()->UpdateVisibilityOf(dynObj); } void Spell::EffectUntrainTalents(SpellEffIndex /*effIndex*/) { if (!unitTarget || m_caster->GetTypeId() == TYPEID_PLAYER) return; if (uint64 guid = m_caster->GetGUID()) // the trainer is the caster unitTarget->ToPlayer()->SendTalentWipeConfirm(guid); } void Spell::EffectTeleUnitsFaceCaster(SpellEffIndex effIndex) { if (!unitTarget) return; if (unitTarget->isInFlight()) return; float dis = (float)m_caster->GetSpellRadiusForTarget(unitTarget, sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[effIndex])); float fx,fy,fz; m_caster->GetClosePoint(fx,fy,fz,unitTarget->GetObjectSize(),dis); unitTarget->NearTeleportTo(fx,fy,fz,-m_caster->GetOrientation(),unitTarget == m_caster); } void Spell::EffectLearnSkill(SpellEffIndex effIndex) { if (unitTarget->GetTypeId() != TYPEID_PLAYER) return; if (damage < 0) return; uint32 skillid = m_spellInfo->EffectMiscValue[effIndex]; uint16 skillval = unitTarget->ToPlayer()->GetPureSkillValue(skillid); unitTarget->ToPlayer()->SetSkill(skillid, SpellMgr::CalculateSpellEffectAmount(m_spellInfo, effIndex), skillval?skillval:1, damage*75); } void Spell::EffectAddHonor(SpellEffIndex /*effIndex*/) { if (unitTarget->GetTypeId() != TYPEID_PLAYER) return; // not scale value for item based reward (/10 value expected) if (m_CastItem) { unitTarget->ToPlayer()->RewardHonor(NULL, 1, damage/10); sLog->outDebug("SpellEffect::AddHonor (spell_id %u) rewards %d honor points (item %u) for player: %u", m_spellInfo->Id, damage/10, m_CastItem->GetEntry(),unitTarget->ToPlayer()->GetGUIDLow()); return; } // do not allow to add too many honor for player (50 * 21) = 1040 at level 70, or (50 * 31) = 1550 at level 80 if (damage <= 50) { uint32 honor_reward = Trinity::Honor::hk_honor_at_level(unitTarget->getLevel(), float(damage)); unitTarget->ToPlayer()->RewardHonor(NULL, 1, honor_reward); sLog->outDebug("SpellEffect::AddHonor (spell_id %u) rewards %u honor points (scale) to player: %u", m_spellInfo->Id, honor_reward, unitTarget->ToPlayer()->GetGUIDLow()); } else { //maybe we have correct honor_gain in damage already unitTarget->ToPlayer()->RewardHonor(NULL, 1, damage); sLog->outDebug("SpellEffect::AddHonor (spell_id %u) rewards %u honor points (non scale) for player: %u", m_spellInfo->Id, damage, unitTarget->ToPlayer()->GetGUIDLow()); } } void Spell::EffectTradeSkill(SpellEffIndex /*effIndex*/) { if (unitTarget->GetTypeId() != TYPEID_PLAYER) return; // uint32 skillid = m_spellInfo->EffectMiscValue[i]; // uint16 skillmax = unitTarget->ToPlayer()->(skillid); // unitTarget->ToPlayer()->SetSkill(skillid,skillval?skillval:1,skillmax+75); } void Spell::EffectEnchantItemPerm(SpellEffIndex effIndex) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; if (!itemTarget) return; Player* p_caster = (Player*)m_caster; // Handle vellums if (itemTarget->IsWeaponVellum() || itemTarget->IsArmorVellum()) { // destroy one vellum from stack uint32 count = 1; p_caster->DestroyItemCount(itemTarget,count,true); unitTarget=p_caster; // and add a scroll DoCreateItem(effIndex,m_spellInfo->EffectItemType[effIndex]); itemTarget=NULL; m_targets.setItemTarget(NULL); } else { // do not increase skill if vellum used if (!(m_CastItem && m_CastItem->GetProto()->Flags & ITEM_PROTO_FLAG_TRIGGERED_CAST)) p_caster->UpdateCraftSkill(m_spellInfo->Id); uint32 enchant_id = m_spellInfo->EffectMiscValue[effIndex]; if (!enchant_id) return; SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) return; // item can be in trade slot and have owner diff. from caster Player* item_owner = itemTarget->GetOwner(); if (!item_owner) return; if (item_owner != p_caster && p_caster->GetSession()->GetSecurity() > SEC_PLAYER && sWorld->getBoolConfig(CONFIG_GM_LOG_TRADE)) { sLog->outCommand(p_caster->GetSession()->GetAccountId(),"GM %s (Account: %u) enchanting(perm): %s (Entry: %d) for player: %s (Account: %u)", p_caster->GetName(),p_caster->GetSession()->GetAccountId(), itemTarget->GetProto()->Name1,itemTarget->GetEntry(), item_owner->GetName(),item_owner->GetSession()->GetAccountId()); } // remove old enchanting before applying new if equipped item_owner->ApplyEnchantment(itemTarget,PERM_ENCHANTMENT_SLOT,false); itemTarget->SetEnchantment(PERM_ENCHANTMENT_SLOT, enchant_id, 0, 0); // add new enchanting if equipped item_owner->ApplyEnchantment(itemTarget,PERM_ENCHANTMENT_SLOT,true); itemTarget->SetSoulboundTradeable(NULL, item_owner, false); } } void Spell::EffectEnchantItemPrismatic(SpellEffIndex effIndex) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; if (!itemTarget) return; Player* p_caster = (Player*)m_caster; uint32 enchant_id = m_spellInfo->EffectMiscValue[effIndex]; if (!enchant_id) return; SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) return; // support only enchantings with add socket in this slot { bool add_socket = false; for (uint8 i = 0; i < MAX_ITEM_ENCHANTMENT_EFFECTS; ++i) { if (pEnchant->type[i] == ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET) { add_socket = true; break; } } if (!add_socket) { sLog->outError("Spell::EffectEnchantItemPrismatic: attempt apply enchant spell %u with SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC (%u) but without ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET (%u), not suppoted yet.", m_spellInfo->Id,SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC,ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET); return; } } // item can be in trade slot and have owner diff. from caster Player* item_owner = itemTarget->GetOwner(); if (!item_owner) return; if (item_owner != p_caster && p_caster->GetSession()->GetSecurity() > SEC_PLAYER && sWorld->getBoolConfig(CONFIG_GM_LOG_TRADE)) { sLog->outCommand(p_caster->GetSession()->GetAccountId(),"GM %s (Account: %u) enchanting(perm): %s (Entry: %d) for player: %s (Account: %u)", p_caster->GetName(),p_caster->GetSession()->GetAccountId(), itemTarget->GetProto()->Name1,itemTarget->GetEntry(), item_owner->GetName(),item_owner->GetSession()->GetAccountId()); } // remove old enchanting before applying new if equipped item_owner->ApplyEnchantment(itemTarget,PRISMATIC_ENCHANTMENT_SLOT,false); itemTarget->SetEnchantment(PRISMATIC_ENCHANTMENT_SLOT, enchant_id, 0, 0); // add new enchanting if equipped item_owner->ApplyEnchantment(itemTarget,PRISMATIC_ENCHANTMENT_SLOT,true); itemTarget->SetSoulboundTradeable(NULL, item_owner, false); } void Spell::EffectEnchantItemTmp(SpellEffIndex effIndex) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player* p_caster = (Player*)m_caster; // Rockbiter Weapon apply to both weapon if (!itemTarget) return; if (m_spellInfo->SpellFamilyName == SPELLFAMILY_SHAMAN && m_spellInfo->SpellFamilyFlags[0] & 0x400000) { uint32 spell_id = 0; // enchanting spell selected by calculated damage-per-sec stored in Effect[1] base value // Note: damage calculated (correctly) with rounding int32(float(v)) but // RW enchantments applied damage int32(float(v)+0.5), this create 0..1 difference sometime switch(damage) { // Rank 1 case 2: spell_id = 36744; break; // 0% [ 7% == 2, 14% == 2, 20% == 2] // Rank 2 case 4: spell_id = 36753; break; // 0% [ 7% == 4, 14% == 4] case 5: spell_id = 36751; break; // 20% // Rank 3 case 6: spell_id = 36754; break; // 0% [ 7% == 6, 14% == 6] case 7: spell_id = 36755; break; // 20% // Rank 4 case 9: spell_id = 36761; break; // 0% [ 7% == 6] case 10: spell_id = 36758; break; // 14% case 11: spell_id = 36760; break; // 20% default: sLog->outError("Spell::EffectEnchantItemTmp: Damage %u not handled in S'RW",damage); return; } SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id); if (!spellInfo) { sLog->outError("Spell::EffectEnchantItemTmp: unknown spell id %i", spell_id); return; } for (int j = BASE_ATTACK; j <= OFF_ATTACK; ++j) { if (Item* item = p_caster->GetWeaponForAttack(WeaponAttackType(j))) { if (item->IsFitToSpellRequirements(m_spellInfo)) { Spell *spell = new Spell(m_caster, spellInfo, true); SpellCastTargets targets; targets.setItemTarget(item); spell->prepare(&targets); } } } return; } if (!itemTarget) return; uint32 enchant_id = m_spellInfo->EffectMiscValue[effIndex]; if (!enchant_id) { sLog->outError("Spell %u Effect %u (SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY) have 0 as enchanting id",m_spellInfo->Id,effIndex); return; } SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) { sLog->outError("Spell %u Effect %u (SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY) have not existed enchanting id %u ",m_spellInfo->Id,effIndex,enchant_id); return; } // select enchantment duration uint32 duration; // rogue family enchantments exception by duration if (m_spellInfo->Id == 38615) duration = 1800; // 30 mins // other rogue family enchantments always 1 hour (some have spell damage=0, but some have wrong data in EffBasePoints) else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE) duration = 3600; // 1 hour // shaman family enchantments else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_SHAMAN) duration = 1800; // 30 mins // other cases with this SpellVisual already selected else if (m_spellInfo->SpellVisual[0] == 215) duration = 1800; // 30 mins // some fishing pole bonuses except Glow Worm which lasts full hour else if (m_spellInfo->SpellVisual[0] == 563 && m_spellInfo->Id != 64401) duration = 600; // 10 mins // shaman rockbiter enchantments else if (m_spellInfo->SpellVisual[0] == 0) duration = 1800; // 30 mins else if (m_spellInfo->Id == 29702) duration = 300; // 5 mins else if (m_spellInfo->Id == 37360) duration = 300; // 5 mins // default case else duration = 3600; // 1 hour // item can be in trade slot and have owner diff. from caster Player* item_owner = itemTarget->GetOwner(); if (!item_owner) return; if (item_owner != p_caster && p_caster->GetSession()->GetSecurity() > SEC_PLAYER && sWorld->getBoolConfig(CONFIG_GM_LOG_TRADE)) { sLog->outCommand(p_caster->GetSession()->GetAccountId(),"GM %s (Account: %u) enchanting(temp): %s (Entry: %d) for player: %s (Account: %u)", p_caster->GetName(), p_caster->GetSession()->GetAccountId(), itemTarget->GetProto()->Name1, itemTarget->GetEntry(), item_owner->GetName(), item_owner->GetSession()->GetAccountId()); } // remove old enchanting before applying new if equipped item_owner->ApplyEnchantment(itemTarget,TEMP_ENCHANTMENT_SLOT, false); itemTarget->SetEnchantment(TEMP_ENCHANTMENT_SLOT, enchant_id, duration * 1000, 0); // add new enchanting if equipped item_owner->ApplyEnchantment(itemTarget, TEMP_ENCHANTMENT_SLOT, true); } void Spell::EffectTameCreature(SpellEffIndex /*effIndex*/) { if (m_caster->GetPetGUID()) return; if (!unitTarget) return; if (unitTarget->GetTypeId() != TYPEID_UNIT) return; Creature* creatureTarget = unitTarget->ToCreature(); if (creatureTarget->isPet()) return; if (m_caster->getClass() != CLASS_HUNTER) return; // cast finish successfully //SendChannelUpdate(0); finish(); Pet* pet = m_caster->CreateTamedPetFrom(creatureTarget,m_spellInfo->Id); if (!pet) // in very specific state like near world end/etc. return; // "kill" original creature creatureTarget->ForcedDespawn(); uint8 level = (creatureTarget->getLevel() < (m_caster->getLevel() - 5)) ? (m_caster->getLevel() - 5) : creatureTarget->getLevel(); // prepare visual effect for levelup pet->SetUInt32Value(UNIT_FIELD_LEVEL, level - 1); // add to world pet->GetMap()->Add(pet->ToCreature()); // visual effect for levelup pet->SetUInt32Value(UNIT_FIELD_LEVEL, level); // caster have pet now m_caster->SetMinion(pet, true); pet->InitTalentForLevel(); if (m_caster->GetTypeId() == TYPEID_PLAYER) { pet->SavePetToDB(PET_SAVE_AS_CURRENT); m_caster->ToPlayer()->PetSpellInitialize(); } } void Spell::EffectSummonPet(SpellEffIndex effIndex) { Player *owner = NULL; if (m_originalCaster) { if (m_originalCaster->GetTypeId() == TYPEID_PLAYER) owner = (Player*)m_originalCaster; else if (m_originalCaster->ToCreature()->isTotem()) owner = m_originalCaster->GetCharmerOrOwnerPlayerOrPlayerItself(); } uint32 petentry = m_spellInfo->EffectMiscValue[effIndex]; if (!owner) { SummonPropertiesEntry const *properties = sSummonPropertiesStore.LookupEntry(67); if (properties) SummonGuardian(effIndex, petentry, properties); return; } Pet *OldSummon = owner->GetPet(); // if pet requested type already exist if (OldSummon) { if (petentry == 0 || OldSummon->GetEntry() == petentry) { // pet in corpse state can't be summoned if (OldSummon->isDead()) return; ASSERT(OldSummon->GetMap() == owner->GetMap()); //OldSummon->GetMap()->Remove(OldSummon->ToCreature(),false); float px, py, pz; owner->GetClosePoint(px, py, pz, OldSummon->GetObjectSize()); OldSummon->NearTeleportTo(px, py, pz, OldSummon->GetOrientation()); //OldSummon->Relocate(px, py, pz, OldSummon->GetOrientation()); //OldSummon->SetMap(owner->GetMap()); //owner->GetMap()->Add(OldSummon->ToCreature()); if (owner->GetTypeId() == TYPEID_PLAYER && OldSummon->isControlled()) owner->ToPlayer()->PetSpellInitialize(); return; } if (owner->GetTypeId() == TYPEID_PLAYER) owner->ToPlayer()->RemovePet(OldSummon,(OldSummon->getPetType() == HUNTER_PET ? PET_SAVE_AS_DELETED : PET_SAVE_NOT_IN_SLOT),false); else return; } float x, y, z; owner->GetClosePoint(x, y, z, owner->GetObjectSize()); Pet* pet = owner->SummonPet(petentry, x, y, z, owner->GetOrientation(), SUMMON_PET, 0); if (!pet) return; if (m_caster->GetTypeId() == TYPEID_UNIT) { if (m_caster->ToCreature()->isTotem()) pet->SetReactState(REACT_AGGRESSIVE); else pet->SetReactState(REACT_DEFENSIVE); } pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, m_spellInfo->Id); // generate new name for summon pet std::string new_name=sObjectMgr->GeneratePetName(petentry); if (!new_name.empty()) pet->SetName(new_name); ExecuteLogEffectSummonObject(effIndex, pet); } void Spell::EffectLearnPetSpell(SpellEffIndex effIndex) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player *_player = (Player*)m_caster; Pet *pet = _player->GetPet(); if (!pet) return; if (!pet->isAlive()) return; SpellEntry const *learn_spellproto = sSpellStore.LookupEntry(m_spellInfo->EffectTriggerSpell[effIndex]); if (!learn_spellproto) return; pet->learnSpell(learn_spellproto->Id); pet->SavePetToDB(PET_SAVE_AS_CURRENT); _player->PetSpellInitialize(); } void Spell::EffectTaunt(SpellEffIndex /*effIndex*/) { if (!unitTarget) return; // this effect use before aura Taunt apply for prevent taunt already attacking target // for spell as marked "non effective at already attacking target" if (!unitTarget || !unitTarget->CanHaveThreatList() || unitTarget->getVictim() == m_caster) { SendCastResult(SPELL_FAILED_DONT_REPORT); return; } if (m_spellInfo->Id == 62124) { int32 damageDone = int32(1 + m_caster->GetTotalAttackPowerValue(BASE_ATTACK) * 0.5f); bool is_crit = m_caster->isSpellCrit(unitTarget, m_spellInfo, m_spellSchoolMask, m_attackType); if (is_crit) damageDone *= 2; m_caster->DealDamage(unitTarget, damageDone, NULL, SPELL_DIRECT_DAMAGE, SPELL_SCHOOL_MASK_HOLY, m_spellInfo, false); m_caster->SendSpellNonMeleeDamageLog(unitTarget, m_spellInfo->Id, damageDone, SPELL_SCHOOL_MASK_HOLY, 0, 0, false, false, is_crit); } // Also use this effect to set the taunter's threat to the taunted creature's highest value if (unitTarget->getThreatManager().getCurrentVictim()) { float myThreat = unitTarget->getThreatManager().getThreat(m_caster); float itsThreat = unitTarget->getThreatManager().getCurrentVictim()->getThreat(); if (itsThreat > myThreat) unitTarget->getThreatManager().addThreat(m_caster, itsThreat - myThreat); } //Set aggro victim to caster if (!unitTarget->getThreatManager().getOnlineContainer().empty()) if (HostileReference* forcedVictim = unitTarget->getThreatManager().getOnlineContainer().getReferenceByTarget(m_caster)) unitTarget->getThreatManager().setCurrentVictim(forcedVictim); if (unitTarget->ToCreature()->IsAIEnabled && !unitTarget->ToCreature()->HasReactState(REACT_PASSIVE)) unitTarget->ToCreature()->AI()->AttackStart(m_caster); } void Spell::EffectWeaponDmg(SpellEffIndex /*effIndex*/) { } void Spell::SpellDamageWeaponDmg(SpellEffIndex effIndex) { if (!unitTarget) return; if (!unitTarget->isAlive()) return; // multiple weapon dmg effect workaround // execute only the last weapon damage // and handle all effects at once for (uint32 j = effIndex + 1; j < MAX_SPELL_EFFECTS; ++j) { switch (m_spellInfo->Effect[j]) { case SPELL_EFFECT_WEAPON_DAMAGE: case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL: case SPELL_EFFECT_NORMALIZED_WEAPON_DMG: case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE: return; // we must calculate only at last weapon effect break; } } // some spell specific modifiers float totalDamagePercentMod = 1.0f; // applied to final bonus+weapon damage int32 fixed_bonus = 0; int32 spell_bonus = 0; // bonus specific for spell switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: { switch (m_spellInfo->Id) { case 69055: // Saber Lash case 70814: // Saber Lash { uint32 count = 0; for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) if (ihit->effectMask & (1 << effIndex)) ++count; totalDamagePercentMod /= count; break; } } break; } case SPELLFAMILY_WARRIOR: { // Devastate (player ones) if (m_spellInfo->SpellFamilyFlags[1] & 0x40) { // Player can apply only 58567 Sunder Armor effect. bool needCast = !unitTarget->HasAura(58567, m_caster->GetGUID()); if (needCast) m_caster->CastSpell(unitTarget, 58567, true); if (Aura * aur = unitTarget->GetAura(58567, m_caster->GetGUID())) { // 58388 - Glyph of Devastate dummy aura. if (int32 num = (needCast ? 0 : 1) + (m_caster->HasAura(58388) ? 1 : 0)) aur->ModStackAmount(num); fixed_bonus += (aur->GetStackAmount() - 1) * CalculateDamage(2, unitTarget); } } break; } case SPELLFAMILY_ROGUE: { // Fan of Knives, Hemorrhage, Ghostly Strike if ((m_spellInfo->SpellFamilyFlags[1] & 0x40000) || (m_spellInfo->SpellFamilyFlags[0] & 0x6000000)) { // Hemorrhage if (m_spellInfo->SpellFamilyFlags[0] & 0x2000000) { if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->AddComboPoints(unitTarget, 1, this); } // 50% more damage with daggers if (m_caster->GetTypeId() == TYPEID_PLAYER) if (Item* item = m_caster->ToPlayer()->GetWeaponForAttack(m_attackType, true)) if (item->GetProto()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER) totalDamagePercentMod *= 1.5f; } // Mutilate (for each hand) else if (m_spellInfo->SpellFamilyFlags[1] & 0x6) { bool found = false; // fast check if (unitTarget->HasAuraState(AURA_STATE_DEADLY_POISON, m_spellInfo, m_caster)) found = true; // full aura scan else { Unit::AuraApplicationMap const& auras = unitTarget->GetAppliedAuras(); for (Unit::AuraApplicationMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { if (itr->second->GetBase()->GetSpellProto()->Dispel == DISPEL_POISON) { found = true; break; } } } if (found) totalDamagePercentMod *= 1.2f; // 120% if poisoned } break; } case SPELLFAMILY_PALADIN: { // Seal of Command - Increase damage by 36% on every swing if (m_spellInfo->SpellFamilyFlags[0] & 0x2000000) { totalDamagePercentMod *= 1.36f; // 136% damage } // Seal of Command Unleashed else if (m_spellInfo->Id == 20467) { spell_bonus += int32(0.08f * m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); spell_bonus += int32(0.13f * m_caster->SpellBaseDamageBonus(GetSpellSchoolMask(m_spellInfo))); } break; } case SPELLFAMILY_SHAMAN: { // Skyshatter Harness item set bonus // Stormstrike if (AuraEffect * aurEff = m_caster->IsScriptOverriden(m_spellInfo, 5634)) m_caster->CastSpell(m_caster, 38430, true, NULL, aurEff); break; } case SPELLFAMILY_DRUID: { // Mangle (Cat): CP if (m_spellInfo->SpellFamilyFlags[1] & 0x400) { if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->AddComboPoints(unitTarget, 1, this); } // Shred, Maul - Rend and Tear else if (m_spellInfo->SpellFamilyFlags[0] & 0x00008800 && unitTarget->HasAuraState(AURA_STATE_BLEEDING)) { if (AuraEffect const* rendAndTear = m_caster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 2859, 0)) AddPctN(totalDamagePercentMod, rendAndTear->GetAmount()); } break; } case SPELLFAMILY_HUNTER: { // Kill Shot - bonus damage from Ranged Attack Power if (m_spellInfo->SpellFamilyFlags[1] & 0x800000) spell_bonus += int32(0.4f * m_caster->GetTotalAttackPowerValue(RANGED_ATTACK)); break; } case SPELLFAMILY_DEATHKNIGHT: { // Plague Strike if (m_spellInfo->SpellFamilyFlags[EFFECT_0] & 0x1) { // Glyph of Plague Strike if (AuraEffect const * aurEff = m_caster->GetAuraEffect(58657, EFFECT_0)) AddPctN(totalDamagePercentMod, aurEff->GetAmount()); break; } // Blood Strike if (m_spellInfo->SpellFamilyFlags[EFFECT_0] & 0x400000) { AddPctF(totalDamagePercentMod, SpellMgr::CalculateSpellEffectAmount(m_spellInfo, EFFECT_2) * unitTarget->GetDiseasesByCaster(m_caster->GetGUID()) / 2.0f); // Glyph of Blood Strike if (m_caster->GetAuraEffect(59332, EFFECT_0)) if (unitTarget->HasAuraType(SPELL_AURA_MOD_DECREASE_SPEED)) AddPctN(totalDamagePercentMod, 20); break; } // Death Strike if (m_spellInfo->SpellFamilyFlags[EFFECT_0] & 0x10) { // Glyph of Death Strike if (AuraEffect const * aurEff = m_caster->GetAuraEffect(59336, EFFECT_0)) if (uint32 runic = std::min<uint32>(m_caster->GetPower(POWER_RUNIC_POWER), SpellMgr::CalculateSpellEffectAmount(aurEff->GetSpellProto(), EFFECT_1))) AddPctN(totalDamagePercentMod, runic); break; } // Obliterate (12.5% more damage per disease) if (m_spellInfo->SpellFamilyFlags[EFFECT_1] & 0x20000) { bool consumeDiseases = true; // Annihilation if (AuraEffect const * aurEff = m_caster->GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 2710, EFFECT_0)) // Do not consume diseases if roll sucesses if (roll_chance_i(aurEff->GetAmount())) consumeDiseases = false; AddPctF(totalDamagePercentMod, SpellMgr::CalculateSpellEffectAmount(m_spellInfo, EFFECT_2) * unitTarget->GetDiseasesByCaster(m_caster->GetGUID(), consumeDiseases) / 2.0f); break; } // Blood-Caked Strike - Blood-Caked Blade if (m_spellInfo->SpellIconID == 1736) { AddPctF(totalDamagePercentMod, unitTarget->GetDiseasesByCaster(m_caster->GetGUID()) * 12.5f); break; } // Heart Strike if (m_spellInfo->SpellFamilyFlags[EFFECT_0] & 0x1000000) { AddPctN(totalDamagePercentMod, SpellMgr::CalculateSpellEffectAmount(m_spellInfo, EFFECT_2) * unitTarget->GetDiseasesByCaster(m_caster->GetGUID())); break; } break; } } bool normalized = false; float weaponDamagePercentMod = 1.0f; for (int j = 0; j < MAX_SPELL_EFFECTS; ++j) { switch (m_spellInfo->Effect[j]) { case SPELL_EFFECT_WEAPON_DAMAGE: case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL: fixed_bonus += CalculateDamage(j, unitTarget); break; case SPELL_EFFECT_NORMALIZED_WEAPON_DMG: fixed_bonus += CalculateDamage(j, unitTarget); normalized = true; break; case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE: ApplyPctN(weaponDamagePercentMod, CalculateDamage(j, unitTarget)); break; default: break; // not weapon damage effect, just skip } } // apply to non-weapon bonus weapon total pct effect, weapon total flat effect included in weapon damage if (fixed_bonus || spell_bonus) { UnitMods unitMod; switch (m_attackType) { default: case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break; case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break; case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break; } float weapon_total_pct = 1.0f; if (m_spellInfo->SchoolMask & SPELL_SCHOOL_MASK_NORMAL) weapon_total_pct = m_caster->GetModifierValue(unitMod, TOTAL_PCT); if (fixed_bonus) fixed_bonus = int32(fixed_bonus * weapon_total_pct); if (spell_bonus) spell_bonus = int32(spell_bonus * weapon_total_pct); } int32 weaponDamage = m_caster->CalculateDamage(m_attackType, normalized, true); // Sequence is important for (int j = 0; j < MAX_SPELL_EFFECTS; ++j) { // We assume that a spell have at most one fixed_bonus // and at most one weaponDamagePercentMod switch(m_spellInfo->Effect[j]) { case SPELL_EFFECT_WEAPON_DAMAGE: case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL: case SPELL_EFFECT_NORMALIZED_WEAPON_DMG: weaponDamage += fixed_bonus; break; case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE: weaponDamage = int32(weaponDamage * weaponDamagePercentMod); default: break; // not weapon damage effect, just skip } } if (spell_bonus) weaponDamage += spell_bonus; if (totalDamagePercentMod != 1.0f) weaponDamage = int32(weaponDamage * totalDamagePercentMod); // prevent negative damage uint32 eff_damage(std::max(weaponDamage, 0)); // Add melee damage bonuses (also check for negative) m_caster->MeleeDamageBonus(unitTarget, &eff_damage, m_attackType, m_spellInfo); m_damage += eff_damage; } void Spell::EffectThreat(SpellEffIndex /*effIndex*/) { if (!unitTarget || !unitTarget->isAlive() || !m_caster->isAlive()) return; if (!unitTarget->CanHaveThreatList()) return; unitTarget->AddThreat(m_caster, float(damage)); } void Spell::EffectHealMaxHealth(SpellEffIndex /*effIndex*/) { if (!unitTarget || !unitTarget->isAlive()) return; int32 addhealth; if (m_spellInfo->SpellFamilyName == SPELLFAMILY_PALADIN) // Lay on Hands { if (m_caster->GetGUID() == unitTarget->GetGUID()) { m_caster->CastSpell(m_caster, 25771, true); // Forbearance m_caster->CastSpell(m_caster, 61988, true); // Immune shield marker (serverside) m_caster->CastSpell(m_caster, 61987, true); // Avenging Wrath marker } } // damage == 0 - heal for caster max health if (damage == 0) addhealth = m_caster->GetMaxHealth(); else addhealth = unitTarget->GetMaxHealth() - unitTarget->GetHealth(); if (m_originalCaster) m_healing += m_originalCaster->SpellHealingBonus(unitTarget, m_spellInfo, addhealth, HEAL); } void Spell::EffectInterruptCast(SpellEffIndex effIndex) { if (!unitTarget || !unitTarget->isAlive()) return; // TODO: not all spells that used this effect apply cooldown at school spells // also exist case: apply cooldown to interrupted cast only and to all spells for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_MAX_SPELL; ++i) { if (Spell* spell = unitTarget->GetCurrentSpell(CurrentSpellTypes(i))) { SpellEntry const* curSpellInfo = spell->m_spellInfo; // check if we can interrupt spell if ((spell->getState() == SPELL_STATE_CASTING || (spell->getState() == SPELL_STATE_PREPARING && spell->GetCastTime() > 0.0f)) && curSpellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_INTERRUPT && curSpellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE) { if (m_originalCaster) { int32 duration = m_originalCaster->ModSpellDuration(m_spellInfo, unitTarget, m_originalCaster->CalcSpellDuration(m_spellInfo), false); unitTarget->ProhibitSpellScholl(GetSpellSchoolMask(curSpellInfo), duration/*GetSpellDuration(m_spellInfo)*/); } ExecuteLogEffectInterruptCast(effIndex, unitTarget, curSpellInfo->Id); unitTarget->InterruptSpell(CurrentSpellTypes(i), false); } } } } void Spell::EffectSummonObjectWild(SpellEffIndex effIndex) { uint32 gameobject_id = m_spellInfo->EffectMiscValue[effIndex]; GameObject* pGameObj = new GameObject; WorldObject* target = focusObject; if (!target) target = m_caster; float x, y, z; if (m_targets.HasDst()) m_targets.m_dstPos.GetPosition(x, y, z); else m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE); Map *map = target->GetMap(); if (!pGameObj->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_GAMEOBJECT), gameobject_id, map, m_caster->GetPhaseMask(), x, y, z, target->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 100, GO_STATE_READY)) { delete pGameObj; return; } int32 duration = GetSpellDuration(m_spellInfo); pGameObj->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); pGameObj->SetSpellId(m_spellInfo->Id); ExecuteLogEffectSummonObject(effIndex, pGameObj); // Wild object not have owner and check clickable by players map->Add(pGameObj); if (pGameObj->GetGoType() == GAMEOBJECT_TYPE_FLAGDROP && m_caster->GetTypeId() == TYPEID_PLAYER) { Player *pl = m_caster->ToPlayer(); Battleground* bg = pl->GetBattleground(); switch(pGameObj->GetMapId()) { case 489: //WS { if (bg && bg->GetTypeID(true) == BATTLEGROUND_WS && bg->GetStatus() == STATUS_IN_PROGRESS) { uint32 team = ALLIANCE; if (pl->GetTeam() == team) team = HORDE; ((BattlegroundWS*)bg)->SetDroppedFlagGUID(pGameObj->GetGUID(),team); } break; } case 566: //EY { if (bg && bg->GetTypeID(true) == BATTLEGROUND_EY && bg->GetStatus() == STATUS_IN_PROGRESS) { ((BattlegroundEY*)bg)->SetDroppedFlagGUID(pGameObj->GetGUID()); } break; } } } if (uint32 linkedEntry = pGameObj->GetGOInfo()->GetLinkedGameObjectEntry()) { GameObject* linkedGO = new GameObject; if (linkedGO->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_GAMEOBJECT), linkedEntry, map, m_caster->GetPhaseMask(), x, y, z, target->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 100, GO_STATE_READY)) { linkedGO->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); linkedGO->SetSpellId(m_spellInfo->Id); ExecuteLogEffectSummonObject(effIndex, linkedGO); // Wild object not have owner and check clickable by players map->Add(linkedGO); } else { delete linkedGO; linkedGO = NULL; return; } } } void Spell::EffectScriptEffect(SpellEffIndex effIndex) { // TODO: we must implement hunter pet summon at login there (spell 6962) switch(m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: { switch(m_spellInfo->Id) { // Glyph of Backstab case 63975: { if (AuraEffect const * aurEff = unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE,SPELLFAMILY_ROGUE,0x00100000,0,0,m_caster->GetGUID())) { uint32 countMin = aurEff->GetBase()->GetMaxDuration(); uint32 countMax = 12000; countMax += m_caster->HasAura(56801) ? 4000 : 0; if (countMin < countMax) { aurEff->GetBase()->SetDuration(uint32(aurEff->GetBase()->GetDuration()+3000)); aurEff->GetBase()->SetMaxDuration(countMin+2000); } } return; } case 45204: // Clone Me! case 41055: // Copy Weapon case 45206: // Copy Off-hand Weapon unitTarget->CastSpell(m_caster, damage, false); break; case 45205: // Copy Offhand Weapon case 41054: // Copy Weapon m_caster->CastSpell(unitTarget, damage, false); break; case 55693: // Remove Collapsing Cave Aura if (!unitTarget) return; unitTarget->RemoveAurasDueToSpell(SpellMgr::CalculateSpellEffectAmount(m_spellInfo, effIndex)); break; // PX-238 Winter Wondervolt TRAP case 26275: { uint32 spells[4] = { 26272, 26157, 26273, 26274 }; // check presence for (uint8 j = 0; j < 4; ++j) if (unitTarget->HasAuraEffect(spells[j],0)) return; // select spell uint32 iTmpSpellId = spells[urand(0,3)]; // cast unitTarget->CastSpell(unitTarget, iTmpSpellId, true); return; } // Bending Shinbone case 8856: { if (!itemTarget && m_caster->GetTypeId() != TYPEID_PLAYER) return; uint32 spell_id = 0; switch(urand(1, 5)) { case 1: spell_id = 8854; break; default: spell_id = 8855; break; } m_caster->CastSpell(m_caster,spell_id,true,NULL); return; } // Brittle Armor - need remove one 24575 Brittle Armor aura case 24590: unitTarget->RemoveAuraFromStack(24575); return; // Mercurial Shield - need remove one 26464 Mercurial Shield aura case 26465: unitTarget->RemoveAuraFromStack(26464); return; // Shadow Flame (All script effects, not just end ones to prevent player from dodging the last triggered spell) case 22539: case 22972: case 22975: case 22976: case 22977: case 22978: case 22979: case 22980: case 22981: case 22982: case 22983: case 22984: case 22985: { if (!unitTarget || !unitTarget->isAlive()) return; // Onyxia Scale Cloak if (unitTarget->HasAura(22683)) return; // Shadow Flame m_caster->CastSpell(unitTarget, 22682, true); return; } // Piccolo of the Flaming Fire case 17512: { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; unitTarget->HandleEmoteCommand(EMOTE_STATE_DANCE); return; } // Escape artist case 20589: m_caster->RemoveMovementImpairingAuras(); return; // Decimate case 28374: case 54426: if (unitTarget) { int32 damage = int32(unitTarget->GetHealth()) - int32(unitTarget->CountPctFromMaxHealth(5)); if (damage > 0) m_caster->CastCustomSpell(28375, SPELLVALUE_BASE_POINT0, damage, unitTarget); } return; // Mirren's Drinking Hat case 29830: { uint32 item = 0; switch (urand(1, 6)) { case 1: case 2: case 3: item = 23584; break; // Loch Modan Lager case 4: case 5: item = 23585; break; // Stouthammer Lite case 6: item = 23586; break; // Aerie Peak Pale Ale } if (item) DoCreateItem(effIndex,item); break; } // Improved Sprint case 30918: { // Removes snares and roots. unitTarget->RemoveMovementImpairingAuras(); break; } // Spirit Walk case 58876: { // Removes snares and roots. unitTarget->RemoveMovementImpairingAuras(); break; } // Plant Warmaul Ogre Banner case 32307: { Player *p_caster = dynamic_cast<Player*>(m_caster); if (!p_caster) break; p_caster->RewardPlayerAndGroupAtEvent(18388, unitTarget); Creature *cTarget = dynamic_cast<Creature*>(unitTarget); if (!cTarget) break; cTarget->setDeathState(CORPSE); cTarget->RemoveCorpse(); break; } case 48025: // Headless Horseman's Mount { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; // Prevent stacking of mounts and client crashes upon dismounting unitTarget->RemoveAurasByType(SPELL_AURA_MOUNTED); // Triggered spell id dependent on riding skill and zone bool canFly = true; uint32 v_map = GetVirtualMapForMapAndZone(unitTarget->GetMapId(), unitTarget->GetZoneId()); if (v_map != 530 && v_map != 571) canFly = false; if (canFly && v_map == 571 && !unitTarget->ToPlayer()->HasSpell(54197)) canFly = false; float x, y, z; unitTarget->GetPosition(x, y, z); uint32 areaFlag = unitTarget->GetBaseMap()->GetAreaFlag(x, y, z); AreaTableEntry const *pArea = sAreaStore.LookupEntry(areaFlag); if (!pArea || (canFly && (pArea->flags & AREA_FLAG_NO_FLY_ZONE))) canFly = false; switch(unitTarget->ToPlayer()->GetBaseSkillValue(SKILL_RIDING)) { case 75: unitTarget->CastSpell(unitTarget, 51621, true); break; case 150: unitTarget->CastSpell(unitTarget, 48024, true); break; case 225: { if (canFly) unitTarget->CastSpell(unitTarget, 51617, true); else unitTarget->CastSpell(unitTarget, 48024, true); }break; case 300: { if (canFly) unitTarget->CastSpell(unitTarget, 48023, true); else unitTarget->CastSpell(unitTarget, 48024, true); }break; } return; } case 47977: // Magic Broom { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; // Prevent stacking of mounts and client crashes upon dismounting unitTarget->RemoveAurasByType(SPELL_AURA_MOUNTED); // Triggered spell id dependent on riding skill and zone bool canFly = true; uint32 v_map = GetVirtualMapForMapAndZone(unitTarget->GetMapId(), unitTarget->GetZoneId()); if (v_map != 530 && v_map != 571) canFly = false; if (canFly && v_map == 571 && !unitTarget->ToPlayer()->HasSpell(54197)) canFly = false; float x, y, z; unitTarget->GetPosition(x, y, z); uint32 areaFlag = unitTarget->GetBaseMap()->GetAreaFlag(x, y, z); AreaTableEntry const *pArea = sAreaStore.LookupEntry(areaFlag); if (!pArea || (canFly && (pArea->flags & AREA_FLAG_NO_FLY_ZONE))) canFly = false; switch(unitTarget->ToPlayer()->GetBaseSkillValue(SKILL_RIDING)) { case 75: unitTarget->CastSpell(unitTarget, 42680, true); break; case 150: unitTarget->CastSpell(unitTarget, 42683, true); break; case 225: { if (canFly) unitTarget->CastSpell(unitTarget, 42667, true); else unitTarget->CastSpell(unitTarget, 42683, true); }break; case 300: { if (canFly) unitTarget->CastSpell(unitTarget, 42668, true); else unitTarget->CastSpell(unitTarget, 42683, true); }break; } return; } // Mug Transformation case 41931: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; uint8 bag = 19; uint8 slot = 0; Item *item = NULL; while (bag) // 256 = 0 due to var type { item = m_caster->ToPlayer()->GetItemByPos(bag, slot); if (item && item->GetEntry() == 38587) break; ++slot; if (slot == 39) { slot = 0; ++bag; } } if (bag) { if (m_caster->ToPlayer()->GetItemByPos(bag,slot)->GetCount() == 1) m_caster->ToPlayer()->RemoveItem(bag,slot,true); else m_caster->ToPlayer()->GetItemByPos(bag,slot)->SetCount(m_caster->ToPlayer()->GetItemByPos(bag,slot)->GetCount()-1); // Spell 42518 (Braufest - Gratisprobe des Braufest herstellen) m_caster->CastSpell(m_caster, 42518, true); return; } break; } // Brutallus - Burn case 45141: case 45151: { //Workaround for Range ... should be global for every ScriptEffect float radius = GetSpellRadiusForHostile(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[effIndex])); if (unitTarget && unitTarget->GetTypeId() == TYPEID_PLAYER && unitTarget->GetDistance(m_caster) >= radius && !unitTarget->HasAura(46394) && unitTarget != m_caster) unitTarget->CastSpell(unitTarget, 46394, true); break; } // Goblin Weather Machine case 46203: { if (!unitTarget) return; uint32 spellId = 0; switch(rand() % 4) { case 0: spellId = 46740; break; case 1: spellId = 46739; break; case 2: spellId = 46738; break; case 3: spellId = 46736; break; } unitTarget->CastSpell(unitTarget, spellId, true); break; } // 5,000 Gold case 46642: { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; unitTarget->ToPlayer()->ModifyMoney(5000 * GOLD); break; } // Roll Dice - Decahedral Dwarven Dice case 47770: { char buf[128]; const char *gender = "his"; if (m_caster->getGender() > 0) gender = "her"; sprintf(buf, "%s rubs %s [Decahedral Dwarven Dice] between %s hands and rolls. One %u and one %u.", m_caster->GetName(), gender, gender, urand(1,10), urand(1,10)); m_caster->MonsterTextEmote(buf, 0); break; } // Roll 'dem Bones - Worn Troll Dice case 47776: { char buf[128]; const char *gender = "his"; if (m_caster->getGender() > 0) gender = "her"; sprintf(buf, "%s causually tosses %s [Worn Troll Dice]. One %u and one %u.", m_caster->GetName(), gender, urand(1,6), urand(1,6)); m_caster->MonsterTextEmote(buf, 0); break; } // Vigilance case 50725: { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; // Remove Taunt cooldown unitTarget->ToPlayer()->RemoveSpellCooldown(355, true); return; } // Death Knight Initiate Visual case 51519: { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT) return; uint32 iTmpSpellId = 0; switch (unitTarget->GetDisplayId()) { case 25369: iTmpSpellId = 51552; break; // bloodelf female case 25373: iTmpSpellId = 51551; break; // bloodelf male case 25363: iTmpSpellId = 51542; break; // draenei female case 25357: iTmpSpellId = 51541; break; // draenei male case 25361: iTmpSpellId = 51537; break; // dwarf female case 25356: iTmpSpellId = 51538; break; // dwarf male case 25372: iTmpSpellId = 51550; break; // forsaken female case 25367: iTmpSpellId = 51549; break; // forsaken male case 25362: iTmpSpellId = 51540; break; // gnome female case 25359: iTmpSpellId = 51539; break; // gnome male case 25355: iTmpSpellId = 51534; break; // human female case 25354: iTmpSpellId = 51520; break; // human male case 25360: iTmpSpellId = 51536; break; // nightelf female case 25358: iTmpSpellId = 51535; break; // nightelf male case 25368: iTmpSpellId = 51544; break; // orc female case 25364: iTmpSpellId = 51543; break; // orc male case 25371: iTmpSpellId = 51548; break; // tauren female case 25366: iTmpSpellId = 51547; break; // tauren male case 25370: iTmpSpellId = 51545; break; // troll female case 25365: iTmpSpellId = 51546; break; // troll male default: return; } unitTarget->CastSpell(unitTarget, iTmpSpellId, true); Creature* npc = unitTarget->ToCreature(); npc->LoadEquipment(npc->GetEquipmentId()); return; } // Emblazon Runeblade case 51770: { if (!m_originalCaster) return; m_originalCaster->CastSpell(m_originalCaster, damage, false); break; } // Deathbolt from Thalgran Blightbringer // reflected by Freya's Ward // Retribution by Sevenfold Retribution case 51854: { if (!unitTarget) return; if (unitTarget->HasAura(51845)) unitTarget->CastSpell(m_caster, 51856, true); else m_caster->CastSpell(unitTarget, 51855, true); break; } // Summon Ghouls On Scarlet Crusade case 51904: { if (!m_targets.HasDst()) return; float x, y, z; float radius = GetSpellRadius(m_spellInfo, effIndex, true); for (uint8 i = 0; i < 15; ++i) { m_caster->GetRandomPoint(m_targets.m_dstPos, radius, x, y, z); m_caster->CastSpell(x, y, z, 54522, true); } break; } case 52173: // Coyote Spirit Despawn case 60243: // Blood Parrot Despawn if (unitTarget->GetTypeId() == TYPEID_UNIT && unitTarget->ToCreature()->isSummon()) unitTarget->ToTempSummon()->UnSummon(); return; case 52479: // Gift of the Harvester if (unitTarget && m_originalCaster) m_originalCaster->CastSpell(unitTarget, urand(0, 1) ? damage : 52505, true); return; // Death Gate case 52751: { if (!unitTarget || unitTarget->getClass() != CLASS_DEATH_KNIGHT) return; // triggered spell is stored in m_spellInfo->EffectBasePoints[0] unitTarget->CastSpell(unitTarget, damage, false); break; } case 53110: // Devour Humanoid if (unitTarget) unitTarget->CastSpell(m_caster, damage, true); return; // Winged Steed of the Ebon Blade case 54729: { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; // Prevent stacking of mounts and client crashes upon dismounting unitTarget->RemoveAurasByType(SPELL_AURA_MOUNTED); // Triggered spell id dependent on riding skill if (uint16 skillval = unitTarget->ToPlayer()->GetSkillValue(SKILL_RIDING)) { if (skillval >= 300) unitTarget->CastSpell(unitTarget, 54727, true); else unitTarget->CastSpell(unitTarget, 54726, true); } return; } case 58418: // Portal to Orgrimmar case 58420: // Portal to Stormwind { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER || effIndex != 0) return; uint32 spellID = SpellMgr::CalculateSpellEffectAmount(m_spellInfo, 0); uint32 questID = SpellMgr::CalculateSpellEffectAmount(m_spellInfo, 1); if (unitTarget->ToPlayer()->GetQuestStatus(questID) == QUEST_STATUS_COMPLETE && !unitTarget->ToPlayer()->GetQuestRewardStatus (questID)) unitTarget->CastSpell(unitTarget, spellID, true); return; } case 58941: // Rock Shards if (unitTarget && m_originalCaster) { for (uint32 i = 0; i < 3; ++i) { m_originalCaster->CastSpell(unitTarget, 58689, true); m_originalCaster->CastSpell(unitTarget, 58692, true); } if (((InstanceMap*)m_originalCaster->GetMap())->GetDifficulty() == REGULAR_DIFFICULTY) { m_originalCaster->CastSpell(unitTarget, 58695, true); m_originalCaster->CastSpell(unitTarget, 58696, true); } else { m_originalCaster->CastSpell(unitTarget, 60883, true); m_originalCaster->CastSpell(unitTarget, 60884, true); } } return; case 58983: // Big Blizzard Bear { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; // Prevent stacking of mounts and client crashes upon dismounting unitTarget->RemoveAurasByType(SPELL_AURA_MOUNTED); // Triggered spell id dependent on riding skill if (uint16 skillval = unitTarget->ToPlayer()->GetSkillValue(SKILL_RIDING)) { if (skillval >= 150) unitTarget->CastSpell(unitTarget, 58999, true); else unitTarget->CastSpell(unitTarget, 58997, true); } return; } case 63845: // Create Lance { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; if (m_caster->ToPlayer()->GetTeam() == ALLIANCE) m_caster->CastSpell(m_caster, 63914, true); else m_caster->CastSpell(m_caster, 63919, true); return; } case 71342: // Big Love Rocket { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; // Prevent stacking of mounts and client crashes upon dismounting unitTarget->RemoveAurasByType(SPELL_AURA_MOUNTED); // Triggered spell id dependent on riding skill and zone bool canFly = true; uint32 v_map = GetVirtualMapForMapAndZone(unitTarget->GetMapId(), unitTarget->GetZoneId()); if (v_map != 530 && v_map != 571) canFly = false; if (canFly && v_map == 571 && !unitTarget->ToPlayer()->HasSpell(54197)) canFly = false; float x, y, z; unitTarget->GetPosition(x, y, z); uint32 areaFlag = unitTarget->GetBaseMap()->GetAreaFlag(x, y, z); AreaTableEntry const *pArea = sAreaStore.LookupEntry(areaFlag); if (!pArea || (canFly && (pArea->flags & AREA_FLAG_NO_FLY_ZONE))) canFly = false; switch(unitTarget->ToPlayer()->GetBaseSkillValue(SKILL_RIDING)) { case 0: unitTarget->CastSpell(unitTarget, 71343, true); break; case 75: unitTarget->CastSpell(unitTarget, 71344, true); break; case 150: unitTarget->CastSpell(unitTarget, 71345, true); break; case 225: { if (canFly) unitTarget->CastSpell(unitTarget, 71346, true); else unitTarget->CastSpell(unitTarget, 71345, true); }break; case 300: { if (canFly) unitTarget->CastSpell(unitTarget, 71347, true); else unitTarget->CastSpell(unitTarget, 71345, true); }break; } return; } case 72286: // Invincible { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; // Prevent stacking of mounts and client crashes upon dismounting unitTarget->RemoveAurasByType(SPELL_AURA_MOUNTED); // Triggered spell id dependent on riding skill and zone bool canFly = true; uint32 v_map = GetVirtualMapForMapAndZone(unitTarget->GetMapId(), unitTarget->GetZoneId()); if (v_map != 530 && v_map != 571) canFly = false; if (canFly && v_map == 571 && !unitTarget->ToPlayer()->HasSpell(54197)) canFly = false; float x, y, z; unitTarget->GetPosition(x, y, z); uint32 areaFlag = unitTarget->GetBaseMap()->GetAreaFlag(x, y, z); AreaTableEntry const *pArea = sAreaStore.LookupEntry(areaFlag); if (!pArea || (canFly && (pArea->flags & AREA_FLAG_NO_FLY_ZONE))) canFly = false; switch(unitTarget->ToPlayer()->GetBaseSkillValue(SKILL_RIDING)) { case 75: unitTarget->CastSpell(unitTarget, 72281, true); break; case 150: unitTarget->CastSpell(unitTarget, 72282, true); break; case 225: { if (canFly) unitTarget->CastSpell(unitTarget, 72283, true); else unitTarget->CastSpell(unitTarget, 72282, true); }break; case 300: { if (canFly) unitTarget->CastSpell(unitTarget, 72284, true); else unitTarget->CastSpell(unitTarget, 72282, true); }break; } return; } case 74856: // Blazing Hippogryph { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; // Prevent stacking of mounts and client crashes upon dismounting unitTarget->RemoveAurasByType(SPELL_AURA_MOUNTED); // Triggered spell id dependent on riding skill if (uint16 skillval = unitTarget->ToPlayer()->GetSkillValue(SKILL_RIDING)) { if (skillval >= 300) unitTarget->CastSpell(unitTarget, 74855, true); else unitTarget->CastSpell(unitTarget, 74854, true); } return; } case 75614: // Celestial Steed { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; // Prevent stacking of mounts and client crashes upon dismounting unitTarget->RemoveAurasByType(SPELL_AURA_MOUNTED); // Triggered spell id dependent on riding skill and zone bool canFly = true; uint32 v_map = GetVirtualMapForMapAndZone(unitTarget->GetMapId(), unitTarget->GetZoneId()); if (v_map != 530 && v_map != 571) canFly = false; if (canFly && v_map == 571 && !unitTarget->ToPlayer()->HasSpell(54197)) canFly = false; float x, y, z; unitTarget->GetPosition(x, y, z); uint32 areaFlag = unitTarget->GetBaseMap()->GetAreaFlag(x, y, z); AreaTableEntry const *pArea = sAreaStore.LookupEntry(areaFlag); if (!pArea || (canFly && (pArea->flags & AREA_FLAG_NO_FLY_ZONE))) canFly = false; switch(unitTarget->ToPlayer()->GetBaseSkillValue(SKILL_RIDING)) { case 75: unitTarget->CastSpell(unitTarget, 75619, true); break; case 150: unitTarget->CastSpell(unitTarget, 75620, true); break; case 225: { if (canFly) unitTarget->CastSpell(unitTarget, 75617, true); else unitTarget->CastSpell(unitTarget, 75620, true); }break; case 300: { if (canFly) { if (unitTarget->ToPlayer()->Has310Flyer(false)) unitTarget->CastSpell(unitTarget, 76153, true); else unitTarget->CastSpell(unitTarget, 75618, true); } else unitTarget->CastSpell(unitTarget, 75620, true); }break; } return; } case 75973: // X-53 Touring Rocket { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; // Prevent stacking of mounts unitTarget->RemoveAurasByType(SPELL_AURA_MOUNTED); // Triggered spell id dependent on riding skill if (uint16 skillval = unitTarget->ToPlayer()->GetSkillValue(SKILL_RIDING)) { if (skillval >= 300) { if (unitTarget->ToPlayer()->Has310Flyer(false)) unitTarget->CastSpell(unitTarget, 76154, true); else unitTarget->CastSpell(unitTarget, 75972, true); } else unitTarget->CastSpell(unitTarget, 75957, true); } return; } case 59317: // Teleporting if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; // return from top if (unitTarget->ToPlayer()->GetAreaId() == 4637) unitTarget->CastSpell(unitTarget, 59316, true); // teleport atop else unitTarget->CastSpell(unitTarget, 59314, true); return; // random spell learn instead placeholder case 60893: // Northrend Alchemy Research case 61177: // Northrend Inscription Research case 61288: // Minor Inscription Research case 61756: // Northrend Inscription Research (FAST QA VERSION) case 64323: // Book of Glyph Mastery { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; // learn random explicit discovery recipe (if any) if (uint32 discoveredSpell = GetExplicitDiscoverySpell(m_spellInfo->Id, (Player*)m_caster)) m_caster->ToPlayer()->learnSpell(discoveredSpell, false); return; } case 62428: // Load into Catapult { if (Vehicle *seat = m_caster->GetVehicleKit()) if (Unit *passenger = seat->GetPassenger(0)) if (Unit *demolisher = m_caster->GetVehicleBase()) passenger->CastSpell(demolisher, damage, true); return; } case 62482: // Grab Crate { if (unitTarget) { if (Vehicle *seat = m_caster->GetVehicleKit()) { if (Creature *oldContainer = dynamic_cast<Creature*>(seat->GetPassenger(1))) oldContainer->DisappearAndDie(); // TODO: a hack, range = 11, should after some time cast, otherwise too far m_caster->CastSpell(seat->GetBase(), 62496, true); unitTarget->EnterVehicle(seat, 1); } } return; } case 65594: // Cancel Stone Grip { uint32 spellToRemove = unitTarget->GetMap()->GetDifficulty() == RAID_DIFFICULTY_10MAN_NORMAL ? 62166 : 63981; unitTarget->RemoveAurasDueToSpell(spellToRemove); return; } case 60123: // Lightwell { if (m_caster->GetTypeId() != TYPEID_UNIT || !m_caster->ToCreature()->isSummon()) return; uint32 spell_heal; switch(m_caster->GetEntry()) { case 31897: spell_heal = 7001; break; case 31896: spell_heal = 27873; break; case 31895: spell_heal = 27874; break; case 31894: spell_heal = 28276; break; case 31893: spell_heal = 48084; break; case 31883: spell_heal = 48085; break; default: sLog->outError("Unknown Lightwell spell caster %u", m_caster->GetEntry()); return; } Aura * chargesaura = m_caster->GetAura(59907); if (chargesaura && chargesaura->GetCharges() > 1) { chargesaura->SetCharges(chargesaura->GetCharges() - 1); m_caster->CastSpell(unitTarget, spell_heal, true, NULL, NULL, m_caster->ToTempSummon()->GetSummonerGUID()); } else m_caster->ToTempSummon()->UnSummon(); return; } // Stoneclaw Totem case 55328: // Rank 1 case 55329: // Rank 2 case 55330: // Rank 3 case 55332: // Rank 4 case 55333: // Rank 5 case 55335: // Rank 6 case 55278: // Rank 7 case 58589: // Rank 8 case 58590: // Rank 9 case 58591: // Rank 10 { int32 basepoints0 = damage; // Cast Absorb on totems for (uint8 slot = SUMMON_SLOT_TOTEM; slot < MAX_TOTEM_SLOT; ++slot) { if (!unitTarget->m_SummonSlot[slot]) continue; Creature* totem = unitTarget->GetMap()->GetCreature(unitTarget->m_SummonSlot[slot]); if (totem && totem->isTotem()) { m_caster->CastCustomSpell(totem, 55277, &basepoints0, NULL, NULL, true); } } // Glyph of Stoneclaw Totem if (AuraEffect *aur=unitTarget->GetAuraEffect(63298, 0)) { basepoints0 *= aur->GetAmount(); m_caster->CastCustomSpell(unitTarget, 55277, &basepoints0, NULL, NULL, true); } break; } case 66545: //Summon Memory { uint8 uiRandom = urand(0,25); uint32 uiSpells[26] = {66704,66705,66706,66707,66709,66710,66711,66712,66713,66714,66715,66708,66708,66691,66692,66694,66695,66696,66697,66698,66699,66700,66701,66702,66703,66543}; m_caster->CastSpell(m_caster,uiSpells[uiRandom],true); break; } case 45668: // Ultra-Advanced Proto-Typical Shortening Blaster { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT) return; if (roll_chance_i(50)) // chance unknown, using 50 return; static uint32 const spellPlayer[5] = { 45674, // Bigger! 45675, // Shrunk 45678, // Yellow 45682, // Ghost 45684 // Polymorph }; static uint32 const spellTarget[5] = { 45673, // Bigger! 45672, // Shrunk 45677, // Yellow 45681, // Ghost 45683 // Polymorph }; m_caster->CastSpell(m_caster, spellPlayer[urand(0,4)], true); unitTarget->CastSpell(unitTarget, spellTarget[urand(0,4)], true); break; } case 64142: // Upper Deck - Create Foam Sword if (unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player *plr = unitTarget->ToPlayer(); static uint32 const itemId[] = {45061, 45176, 45177, 45178, 45179, 0}; // player can only have one of these items for (uint32 const *itr = &itemId[0]; *itr; ++itr) if (plr->HasItemCount(*itr, 1, true)) return; DoCreateItem(effIndex, itemId[urand(0,4)]); return; } break; } case SPELLFAMILY_PALADIN: { // Judgement (seal trigger) if (m_spellInfo->Category == SPELLCATEGORY_JUDGEMENT) { if (!unitTarget || !unitTarget->isAlive()) return; uint32 spellId1 = 0; uint32 spellId2 = 0; uint32 spellId3 = 0; // Judgement self add switch switch (m_spellInfo->Id) { case 53407: spellId1 = 20184; break; // Judgement of Justice case 20271: // Judgement of Light case 57774: spellId1 = 20185; break; // Judgement of Light case 53408: spellId1 = 20186; break; // Judgement of Wisdom default: sLog->outError("Unsupported Judgement (seal trigger) spell (Id: %u) in Spell::EffectScriptEffect",m_spellInfo->Id); return; } // all seals have aura dummy in 2 effect Unit::AuraApplicationMap & sealAuras = m_caster->GetAppliedAuras(); for (Unit::AuraApplicationMap::iterator iter = sealAuras.begin(); iter != sealAuras.end();) { switch (iter->first) { // Heart of the Crusader case 20335: // Rank 1 spellId3 = 21183; break; case 20336: // Rank 2 spellId3 = 54498; break; case 20337: // Rank 3 spellId3 = 54499; break; } Aura * aura = iter->second->GetBase(); if (IsSealSpell(aura->GetSpellProto())) { if (AuraEffect * aureff = aura->GetEffect(2)) if (aureff->GetAuraType() == SPELL_AURA_DUMMY) { if (sSpellStore.LookupEntry(aureff->GetAmount())) spellId2 = aureff->GetAmount(); break; } if (!spellId2) { switch (iter->first) { // Seal of light, Seal of wisdom, Seal of justice case 20165: case 20166: case 20164: spellId2 = 54158; } } break; } else ++iter; } if (spellId1) m_caster->CastSpell(unitTarget, spellId1, true); if (spellId2) m_caster->CastSpell(unitTarget, spellId2, true); if (spellId3) m_caster->CastSpell(unitTarget, spellId3, true); return; } } case SPELLFAMILY_POTION: { switch(m_spellInfo->Id) { // Netherbloom case 28702: { if (!unitTarget) return; // 25% chance of casting a random buff if (roll_chance_i(75)) return; // triggered spells are 28703 to 28707 // Note: some sources say, that there was the possibility of // receiving a debuff. However, this seems to be removed by a patch. const uint32 spellid = 28703; // don't overwrite an existing aura for (uint8 i = 0; i < 5; ++i) if (unitTarget->HasAura(spellid + i)) return; unitTarget->CastSpell(unitTarget, spellid+urand(0, 4), true); break; } // Nightmare Vine case 28720: { if (!unitTarget) return; // 25% chance of casting Nightmare Pollen if (roll_chance_i(75)) return; unitTarget->CastSpell(unitTarget, 28721, true); break; } } break; } case SPELLFAMILY_DEATHKNIGHT: { // Pestilence if (m_spellInfo->SpellFamilyFlags[1]&0x10000) { // Get diseases on target of spell if (m_targets.getUnitTarget() && // Glyph of Disease - cast on unit target too to refresh aura (m_targets.getUnitTarget() != unitTarget || m_caster->GetAura(63334))) { // And spread them on target // Blood Plague if (m_targets.getUnitTarget()->GetAura(55078)) m_caster->CastSpell(unitTarget, 55078, true); // Frost Fever if (m_targets.getUnitTarget()->GetAura(55095)) m_caster->CastSpell(unitTarget, 55095, true); } } break; } case SPELLFAMILY_WARRIOR: { // Shattering Throw if (m_spellInfo->SpellFamilyFlags[1] & 0x00400000) { if (!unitTarget) return; // remove shields, will still display immune to damage part unitTarget->RemoveAurasWithMechanic(1<<MECHANIC_IMMUNE_SHIELD, AURA_REMOVE_BY_ENEMY_SPELL); return; } break; } } // normal DB scripted effect sLog->outDebug("Spell ScriptStart spellid %u in EffectScriptEffect(%u)", m_spellInfo->Id, effIndex); m_caster->GetMap()->ScriptsStart(sSpellScripts, uint32(m_spellInfo->Id | (effIndex << 24)), m_caster, unitTarget); } void Spell::EffectSanctuary(SpellEffIndex /*effIndex*/) { if (!unitTarget) return; unitTarget->getHostileRefManager().UpdateVisibility(); Unit::AttackerSet const& attackers = unitTarget->getAttackers(); for (Unit::AttackerSet::const_iterator itr = attackers.begin(); itr != attackers.end();) { if (!(*itr)->canSeeOrDetect(unitTarget)) (*(itr++))->AttackStop(); else ++itr; } unitTarget->m_lastSanctuaryTime = getMSTime(); // Vanish allows to remove all threat and cast regular stealth so other spells can be used if (m_caster->GetTypeId() == TYPEID_PLAYER && m_spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE && (m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_ROGUE_VANISH)) { m_caster->ToPlayer()->RemoveAurasByType(SPELL_AURA_MOD_ROOT); // Overkill if (m_caster->ToPlayer()->HasSpell(58426)) m_caster->CastSpell(m_caster, 58427, true); } } void Spell::EffectAddComboPoints(SpellEffIndex /*effIndex*/) { if (!unitTarget) return; if (!m_caster->m_movedPlayer) return; if (damage <= 0) return; m_caster->m_movedPlayer->AddComboPoints(unitTarget, damage, this); } void Spell::EffectDuel(SpellEffIndex effIndex) { if (!unitTarget || m_caster->GetTypeId() != TYPEID_PLAYER || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player *caster = (Player*)m_caster; Player *target = (Player*)unitTarget; // caster or target already have requested duel if (caster->duel || target->duel || !target->GetSocial() || target->GetSocial()->HasIgnore(caster->GetGUIDLow())) return; // Players can only fight a duel with each other outside (=not inside dungeons and not in capital cities) // Don't have to check the target's map since you cannot challenge someone across maps if (caster->GetMap()->Instanceable()) //if (mapid != 0 && mapid != 1 && mapid != 530 && mapid != 571 && mapid != 609) { SendCastResult(SPELL_FAILED_NO_DUELING); // Dueling isn't allowed here return; } AreaTableEntry const* casterAreaEntry = GetAreaEntryByAreaID(caster->GetZoneId()); if (casterAreaEntry && (casterAreaEntry->flags & AREA_FLAG_CAPITAL)) { SendCastResult(SPELL_FAILED_NO_DUELING); // Dueling isn't allowed here return; } AreaTableEntry const* targetAreaEntry = GetAreaEntryByAreaID(target->GetZoneId()); if (targetAreaEntry && (targetAreaEntry->flags & AREA_FLAG_CAPITAL)) { SendCastResult(SPELL_FAILED_NO_DUELING); // Dueling isn't allowed here return; } //CREATE DUEL FLAG OBJECT GameObject* pGameObj = new GameObject; uint32 gameobject_id = m_spellInfo->EffectMiscValue[effIndex]; Map *map = m_caster->GetMap(); if (!pGameObj->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_GAMEOBJECT), gameobject_id, map, m_caster->GetPhaseMask(), m_caster->GetPositionX()+(unitTarget->GetPositionX()-m_caster->GetPositionX())/2 , m_caster->GetPositionY()+(unitTarget->GetPositionY()-m_caster->GetPositionY())/2 , m_caster->GetPositionZ(), m_caster->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 0, GO_STATE_READY)) { delete pGameObj; return; } pGameObj->SetUInt32Value(GAMEOBJECT_FACTION, m_caster->getFaction()); pGameObj->SetUInt32Value(GAMEOBJECT_LEVEL, m_caster->getLevel()+1); int32 duration = GetSpellDuration(m_spellInfo); pGameObj->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); pGameObj->SetSpellId(m_spellInfo->Id); ExecuteLogEffectSummonObject(effIndex, pGameObj); m_caster->AddGameObject(pGameObj); map->Add(pGameObj); //END // Send request WorldPacket data(SMSG_DUEL_REQUESTED, 8 + 8); data << uint64(pGameObj->GetGUID()); data << uint64(caster->GetGUID()); caster->GetSession()->SendPacket(&data); target->GetSession()->SendPacket(&data); // create duel-info DuelInfo *duel = new DuelInfo; duel->initiator = caster; duel->opponent = target; duel->startTime = 0; duel->startTimer = 0; caster->duel = duel; DuelInfo *duel2 = new DuelInfo; duel2->initiator = caster; duel2->opponent = caster; duel2->startTime = 0; duel2->startTimer = 0; target->duel = duel2; caster->SetUInt64Value(PLAYER_DUEL_ARBITER, pGameObj->GetGUID()); target->SetUInt64Value(PLAYER_DUEL_ARBITER, pGameObj->GetGUID()); sScriptMgr->OnPlayerDuelRequest(target, caster); } void Spell::EffectStuck(SpellEffIndex /*effIndex*/) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; if (!sWorld->getBoolConfig(CONFIG_CAST_UNSTUCK)) return; Player* pTarget = (Player*)unitTarget; sLog->outDebug("Spell Effect: Stuck"); sLog->outDetail("Player %s (guid %u) used auto-unstuck future at map %u (%f, %f, %f)", pTarget->GetName(), pTarget->GetGUIDLow(), m_caster->GetMapId(), m_caster->GetPositionX(), pTarget->GetPositionY(), pTarget->GetPositionZ()); if (pTarget->isInFlight()) return; pTarget->TeleportTo(pTarget->GetStartPosition(), unitTarget == m_caster ? TELE_TO_SPELL : 0); // homebind location is loaded always // pTarget->TeleportTo(pTarget->m_homebindMapId,pTarget->m_homebindX,pTarget->m_homebindY,pTarget->m_homebindZ,pTarget->GetOrientation(), (unitTarget == m_caster ? TELE_TO_SPELL : 0)); // Stuck spell trigger Hearthstone cooldown SpellEntry const *spellInfo = sSpellStore.LookupEntry(8690); if (!spellInfo) return; Spell spell(pTarget, spellInfo, true, 0); spell.SendSpellCooldown(); } void Spell::EffectSummonPlayer(SpellEffIndex /*effIndex*/) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; // Evil Twin (ignore player summon, but hide this for summoner) if (unitTarget->HasAura(23445)) return; float x, y, z; m_caster->GetClosePoint(x, y, z, unitTarget->GetObjectSize()); unitTarget->ToPlayer()->SetSummonPoint(m_caster->GetMapId(),x,y,z); WorldPacket data(SMSG_SUMMON_REQUEST, 8+4+4); data << uint64(m_caster->GetGUID()); // summoner guid data << uint32(m_caster->GetZoneId()); // summoner zone data << uint32(MAX_PLAYER_SUMMON_DELAY*IN_MILLISECONDS); // auto decline after msecs unitTarget->ToPlayer()->GetSession()->SendPacket(&data); } static ScriptInfo generateActivateCommand() { ScriptInfo si; si.command = SCRIPT_COMMAND_ACTIVATE_OBJECT; return si; } void Spell::EffectActivateObject(SpellEffIndex effIndex) { if (!gameObjTarget) return; static ScriptInfo activateCommand = generateActivateCommand(); int32 delay_secs = m_spellInfo->EffectMiscValue[effIndex]; gameObjTarget->GetMap()->ScriptCommandStart(activateCommand, delay_secs, m_caster, gameObjTarget); } void Spell::EffectApplyGlyph(SpellEffIndex effIndex) { if (m_caster->GetTypeId() != TYPEID_PLAYER || m_glyphIndex >= MAX_GLYPH_SLOT_INDEX) return; Player *player = (Player*)m_caster; // glyph sockets level requirement uint8 minLevel = 0; switch (m_glyphIndex) { case 0: case 1: minLevel = 15; break; case 2: minLevel = 50; break; case 3: minLevel = 30; break; case 4: minLevel = 70; break; case 5: minLevel = 80; break; } if (minLevel && m_caster->getLevel() < minLevel) { SendCastResult(SPELL_FAILED_GLYPH_SOCKET_LOCKED); return; } // apply new one if (uint32 glyph = m_spellInfo->EffectMiscValue[effIndex]) { if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph)) { if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(player->GetGlyphSlot(m_glyphIndex))) { if (gp->TypeFlags != gs->TypeFlags) { SendCastResult(SPELL_FAILED_INVALID_GLYPH); return; // glyph slot mismatch } } // remove old glyph if (uint32 oldglyph = player->GetGlyph(m_glyphIndex)) { if (GlyphPropertiesEntry const *old_gp = sGlyphPropertiesStore.LookupEntry(oldglyph)) { player->RemoveAurasDueToSpell(old_gp->SpellId); player->SetGlyph(m_glyphIndex, 0); } } player->CastSpell(m_caster, gp->SpellId, true); player->SetGlyph(m_glyphIndex, glyph); player->SendTalentsInfoData(false); } } } void Spell::EffectEnchantHeldItem(SpellEffIndex effIndex) { // this is only item spell effect applied to main-hand weapon of target player (players in area) if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* item_owner = (Player*)unitTarget; Item* item = item_owner->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND); if (!item) return; // must be equipped if (!item ->IsEquipped()) return; if (m_spellInfo->EffectMiscValue[effIndex]) { uint32 enchant_id = m_spellInfo->EffectMiscValue[effIndex]; int32 duration = GetSpellDuration(m_spellInfo); //Try duration index first .. if (!duration) duration = damage;//+1; //Base points after .. if (!duration) duration = 10; //10 seconds for enchants which don't have listed duration SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) return; // Always go to temp enchantment slot EnchantmentSlot slot = TEMP_ENCHANTMENT_SLOT; // Enchantment will not be applied if a different one already exists if (item->GetEnchantmentId(slot) && item->GetEnchantmentId(slot) != enchant_id) return; // Apply the temporary enchantment item->SetEnchantment(slot, enchant_id, duration*IN_MILLISECONDS, 0); item_owner->ApplyEnchantment(item, slot, true); } } void Spell::EffectDisEnchant(SpellEffIndex /*effIndex*/) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player* p_caster = (Player*)m_caster; if (!itemTarget || !itemTarget->GetProto()->DisenchantID) return; p_caster->UpdateCraftSkill(m_spellInfo->Id); m_caster->ToPlayer()->SendLoot(itemTarget->GetGUID(),LOOT_DISENCHANTING); // item will be removed at disenchanting end } void Spell::EffectInebriate(SpellEffIndex /*effIndex*/) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player *player = (Player*)unitTarget; uint16 currentDrunk = player->GetDrunkValue(); uint16 drunkMod = damage * 256; if (currentDrunk + drunkMod > 0xFFFF) currentDrunk = 0xFFFF; else currentDrunk += drunkMod; player->SetDrunkValue(currentDrunk, m_CastItem ? m_CastItem->GetEntry() : 0); } void Spell::EffectFeedPet(SpellEffIndex effIndex) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player *_player = (Player*)m_caster; Item* foodItem = m_targets.getItemTarget(); if (!foodItem) return; Pet *pet = _player->GetPet(); if (!pet) return; if (!pet->isAlive()) return; int32 benefit = pet->GetCurrentFoodBenefitLevel(foodItem->GetProto()->ItemLevel); if (benefit <= 0) return; ExecuteLogEffectDestroyItem(effIndex, foodItem->GetEntry()); uint32 count = 1; _player->DestroyItemCount(foodItem, count, true); // TODO: fix crash when a spell has two effects, both pointed at the same item target m_caster->CastCustomSpell(pet, m_spellInfo->EffectTriggerSpell[effIndex], &benefit, NULL, NULL, true); } void Spell::EffectDismissPet(SpellEffIndex effIndex) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Pet* pet = m_caster->ToPlayer()->GetPet(); // not let dismiss dead pet if (!pet||!pet->isAlive()) return; ExecuteLogEffectUnsummonObject(effIndex, pet); m_caster->ToPlayer()->RemovePet(pet, PET_SAVE_NOT_IN_SLOT); } void Spell::EffectSummonObject(SpellEffIndex effIndex) { uint32 go_id = m_spellInfo->EffectMiscValue[effIndex]; uint8 slot = 0; switch(m_spellInfo->Effect[effIndex]) { case SPELL_EFFECT_SUMMON_OBJECT_SLOT1: slot = 0; break; case SPELL_EFFECT_SUMMON_OBJECT_SLOT2: slot = 1; break; case SPELL_EFFECT_SUMMON_OBJECT_SLOT3: slot = 2; break; case SPELL_EFFECT_SUMMON_OBJECT_SLOT4: slot = 3; break; default: return; } uint64 guid = m_caster->m_ObjectSlot[slot]; if (guid != 0) { GameObject* obj = NULL; if (m_caster) obj = m_caster->GetMap()->GetGameObject(guid); if (obj) { // Recast case - null spell id to make auras not be removed on object remove from world if (m_spellInfo->Id == obj->GetSpellId()) obj->SetSpellId(0); m_caster->RemoveGameObject(obj, true); } m_caster->m_ObjectSlot[slot] = 0; } GameObject* pGameObj = new GameObject; float x, y, z; // If dest location if present if (m_targets.HasDst()) m_targets.m_dstPos.GetPosition(x, y, z); // Summon in random point all other units if location present else m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE); Map *map = m_caster->GetMap(); if (!pGameObj->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_GAMEOBJECT), go_id, map, m_caster->GetPhaseMask(), x, y, z, m_caster->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 0, GO_STATE_READY)) { delete pGameObj; return; } //pGameObj->SetUInt32Value(GAMEOBJECT_LEVEL,m_caster->getLevel()); int32 duration = GetSpellDuration(m_spellInfo); pGameObj->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); pGameObj->SetSpellId(m_spellInfo->Id); m_caster->AddGameObject(pGameObj); ExecuteLogEffectSummonObject(effIndex, pGameObj); map->Add(pGameObj); m_caster->m_ObjectSlot[slot] = pGameObj->GetGUID(); } void Spell::EffectResurrect(SpellEffIndex effIndex) { if (!unitTarget) return; if (unitTarget->GetTypeId() != TYPEID_PLAYER) return; if (unitTarget->isAlive()) return; if (!unitTarget->IsInWorld()) return; switch (m_spellInfo->Id) { // Defibrillate (Goblin Jumper Cables) have 33% chance on success case 8342: if (roll_chance_i(67)) { m_caster->CastSpell(m_caster, 8338, true, m_CastItem); return; } break; // Defibrillate (Goblin Jumper Cables XL) have 50% chance on success case 22999: if (roll_chance_i(50)) { m_caster->CastSpell(m_caster, 23055, true, m_CastItem); return; } break; // Defibrillate ( Gnomish Army Knife) have 67% chance on success_list case 54732: if (roll_chance_i(33)) { return; } break; default: break; } Player* pTarget = unitTarget->ToPlayer(); if (pTarget->isRessurectRequested()) // already have one active request return; uint32 health = pTarget->CountPctFromMaxHealth(damage); uint32 mana = CalculatePctN(pTarget->GetMaxPower(POWER_MANA), damage); ExecuteLogEffectResurrect(effIndex, pTarget); pTarget->setResurrectRequestData(m_caster->GetGUID(), m_caster->GetMapId(), m_caster->GetPositionX(), m_caster->GetPositionY(), m_caster->GetPositionZ(), health, mana); SendResurrectRequest(pTarget); } void Spell::EffectAddExtraAttacks(SpellEffIndex effIndex) { if (!unitTarget || !unitTarget->isAlive() || !unitTarget->getVictim()) return; if (unitTarget->m_extraAttacks) return; unitTarget->m_extraAttacks = damage; ExecuteLogEffectExtraAttacks(effIndex, unitTarget->getVictim(), damage); } void Spell::EffectParry(SpellEffIndex /*effIndex*/) { if (unitTarget && unitTarget->GetTypeId() == TYPEID_PLAYER) unitTarget->ToPlayer()->SetCanParry(true); } void Spell::EffectBlock(SpellEffIndex /*effIndex*/) { if (unitTarget && unitTarget->GetTypeId() == TYPEID_PLAYER) unitTarget->ToPlayer()->SetCanBlock(true); } void Spell::EffectLeap(SpellEffIndex /*effIndex*/) { if (unitTarget->isInFlight()) return; if (!m_targets.HasDst()) return; unitTarget->NearTeleportTo(m_targets.m_dstPos.GetPositionX(), m_targets.m_dstPos.GetPositionY(), m_targets.m_dstPos.GetPositionZ(), m_targets.m_dstPos.GetOrientation(), unitTarget == m_caster); } void Spell::EffectReputation(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player *_player = (Player*)unitTarget; int32 rep_change = damage;//+1; // field store reputation change -1 uint32 faction_id = m_spellInfo->EffectMiscValue[effIndex]; FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction_id); if (!factionEntry) return; if (RepRewardRate const * repData = sObjectMgr->GetRepRewardRate(faction_id)) { rep_change = int32((float)rep_change * repData->spell_rate); } _player->GetReputationMgr().ModifyReputation(factionEntry, rep_change); } void Spell::EffectQuestComplete(SpellEffIndex effIndex) { Player *pPlayer; if (m_caster->GetTypeId() == TYPEID_PLAYER) pPlayer = (Player*)m_caster; else if (unitTarget && unitTarget->GetTypeId() == TYPEID_PLAYER) pPlayer = (Player*)unitTarget; else return; uint32 quest_id = m_spellInfo->EffectMiscValue[effIndex]; if (quest_id) { uint16 log_slot = pPlayer->FindQuestSlot(quest_id); if (log_slot < MAX_QUEST_LOG_SIZE) pPlayer->AreaExploredOrEventHappens(quest_id); else if (!pPlayer->GetQuestRewardStatus(quest_id)) // never rewarded before pPlayer->CompleteQuest(quest_id); // quest not in log - for internal use } } void Spell::EffectForceDeselect(SpellEffIndex /*effIndex*/) { WorldPacket data(SMSG_CLEAR_TARGET, 8); data << uint64(m_caster->GetGUID()); m_caster->SendMessageToSet(&data, true); } void Spell::EffectSelfResurrect(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->isAlive()) return; if (unitTarget->GetTypeId() != TYPEID_PLAYER) return; if (!unitTarget->IsInWorld()) return; uint32 health = 0; uint32 mana = 0; // flat case if (damage < 0) { health = uint32(-damage); mana = m_spellInfo->EffectMiscValue[effIndex]; } // percent case else { health = unitTarget->CountPctFromMaxHealth(damage); if (unitTarget->GetMaxPower(POWER_MANA) > 0) mana = CalculatePctN(unitTarget->GetMaxPower(POWER_MANA), damage); } Player *plr = unitTarget->ToPlayer(); plr->ResurrectPlayer(0.0f); plr->SetHealth(health); plr->SetPower(POWER_MANA, mana); plr->SetPower(POWER_RAGE, 0); plr->SetPower(POWER_ENERGY, plr->GetMaxPower(POWER_ENERGY)); plr->SpawnCorpseBones(); } void Spell::EffectSkinning(SpellEffIndex /*effIndex*/) { if (unitTarget->GetTypeId() != TYPEID_UNIT) return; if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Creature* creature = unitTarget->ToCreature(); int32 targetLevel = creature->getLevel(); uint32 skill = creature->GetCreatureInfo()->GetRequiredLootSkill(); m_caster->ToPlayer()->SendLoot(creature->GetGUID(),LOOT_SKINNING); creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); int32 reqValue = targetLevel < 10 ? 0 : targetLevel < 20 ? (targetLevel-10)*10 : targetLevel*5; int32 skillValue = m_caster->ToPlayer()->GetPureSkillValue(skill); // Double chances for elites m_caster->ToPlayer()->UpdateGatherSkill(skill, skillValue, reqValue, creature->isElite() ? 2 : 1); } void Spell::EffectCharge(SpellEffIndex /*effIndex*/) { Unit *target = m_targets.getUnitTarget(); if (!target) return; float x, y, z; target->GetContactPoint(m_caster, x, y, z); m_caster->GetMotionMaster()->MoveCharge(x, y, z); // not all charge effects used in negative spells if (!IsPositiveSpell(m_spellInfo->Id) && m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->Attack(target, true); } void Spell::EffectChargeDest(SpellEffIndex /*effIndex*/) { if (m_targets.HasDst()) { float x, y, z; m_targets.m_dstPos.GetPosition(x, y, z); m_caster->GetMotionMaster()->MoveCharge(x, y, z); } } void Spell::EffectKnockBack(SpellEffIndex effIndex) { if (!unitTarget) return; // Instantly interrupt non melee spells being casted if (unitTarget->IsNonMeleeSpellCasted(true)) unitTarget->InterruptNonMeleeSpells(true); // Typhoon if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DRUID && m_spellInfo->SpellFamilyFlags[1] & 0x01000000) { // Glyph of Typhoon if (m_caster->HasAura(62135)) return; } // Thunderstorm if (m_spellInfo->SpellFamilyName == SPELLFAMILY_SHAMAN && m_spellInfo->SpellFamilyFlags[1] & 0x00002000) { // Glyph of Thunderstorm if (m_caster->HasAura(62132)) return; } float ratio = m_caster->GetCombatReach() / std::max(unitTarget->GetCombatReach(), 1.0f); if (ratio < 1.0f) ratio = ratio * ratio * ratio * 0.1f; // volume = length^3 else ratio = 0.1f; // dbc value ratio float speedxy = float(m_spellInfo->EffectMiscValue[effIndex]) * ratio; float speedz = float(damage) * ratio; if (speedxy < 0.1f && speedz < 0.1f) return; float x, y; if (m_spellInfo->Effect[effIndex] == SPELL_EFFECT_KNOCK_BACK_DEST) { if (m_targets.HasDst()) m_targets.m_dstPos.GetPosition(x, y); else return; } else //if (m_spellInfo->Effect[i] == SPELL_EFFECT_KNOCK_BACK) { m_caster->GetPosition(x, y); } unitTarget->KnockbackFrom(x, y, speedxy, speedz); } void Spell::EffectLeapBack(SpellEffIndex effIndex) { float speedxy = float(m_spellInfo->EffectMiscValue[effIndex])/10; float speedz = float(damage/10); if (!speedxy) { if (m_targets.getUnitTarget()) m_caster->JumpTo(m_targets.getUnitTarget(), speedz); } else { //1891: Disengage m_caster->JumpTo(speedxy, speedz, m_spellInfo->SpellIconID != 1891); } } void Spell::EffectQuestClear(SpellEffIndex effIndex) { Player *pPlayer = NULL; if (m_caster->GetTypeId() == TYPEID_PLAYER) pPlayer = m_caster->ToPlayer(); else if (unitTarget && unitTarget->GetTypeId() == TYPEID_PLAYER) pPlayer = unitTarget->ToPlayer(); if (!pPlayer) return; uint32 quest_id = m_spellInfo->EffectMiscValue[effIndex]; Quest const* pQuest = sObjectMgr->GetQuestTemplate(quest_id); if (!pQuest) return; // Player has never done this quest if (pPlayer->GetQuestStatus(quest_id) == QUEST_STATUS_NONE) return; // remove all quest entries for 'entry' from quest log for (uint8 slot = 0; slot < MAX_QUEST_LOG_SIZE; ++slot) { uint32 quest = pPlayer->GetQuestSlotQuestId(slot); if (quest == quest_id) { pPlayer->SetQuestSlot(slot, 0); // we ignore unequippable quest items in this case, its' still be equipped pPlayer->TakeQuestSourceItem(quest, false); } } pPlayer->RemoveActiveQuest(quest_id); pPlayer->RemoveRewardedQuest(quest_id); } void Spell::EffectSendTaxi(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; unitTarget->ToPlayer()->ActivateTaxiPathTo(m_spellInfo->EffectMiscValue[effIndex],m_spellInfo->Id); } void Spell::EffectPullTowards(SpellEffIndex effIndex) { if (!unitTarget) return; float speedZ = (float)(SpellMgr::CalculateSpellEffectAmount(m_spellInfo, effIndex) / 10); float speedXY = (float)(m_spellInfo->EffectMiscValue[effIndex]/10); Position pos; if (m_spellInfo->Effect[effIndex] == SPELL_EFFECT_PULL_TOWARDS_DEST) { if (m_targets.HasDst()) pos.Relocate(m_targets.m_dstPos); else return; } else //if (m_spellInfo->Effect[i] == SPELL_EFFECT_PULL_TOWARDS) { pos.Relocate(m_caster); } unitTarget->GetMotionMaster()->MoveJump(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), speedXY, speedZ); } void Spell::EffectDispelMechanic(SpellEffIndex effIndex) { if (!unitTarget) return; uint32 mechanic = m_spellInfo->EffectMiscValue[effIndex]; std::queue < std::pair < uint32, uint64 > > dispel_list; Unit::AuraMap const& auras = unitTarget->GetOwnedAuras(); for (Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { Aura * aura = itr->second; if (!aura->GetApplicationOfTarget(unitTarget->GetGUID())) continue; bool success = false; GetDispelChance(aura->GetCaster(), unitTarget, aura->GetId(), !unitTarget->IsFriendlyTo(m_caster), &success); if ((GetAllSpellMechanicMask(aura->GetSpellProto()) & (1 << mechanic)) && success) dispel_list.push(std::make_pair(aura->GetId(), aura->GetCasterGUID())); } for (; dispel_list.size(); dispel_list.pop()) { unitTarget->RemoveAura(dispel_list.front().first, dispel_list.front().second, 0, AURA_REMOVE_BY_ENEMY_SPELL); } } void Spell::EffectSummonDeadPet(SpellEffIndex /*effIndex*/) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player *_player = (Player*)m_caster; Pet *pet = _player->GetPet(); if (!pet) return; if (pet->isAlive()) return; if (damage < 0) return; float x,y,z; _player->GetPosition(x, y, z); _player->GetMap()->CreatureRelocation(pet, x, y, z, _player->GetOrientation()); pet->SetUInt32Value(UNIT_DYNAMIC_FLAGS, 0); pet->RemoveFlag (UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); pet->setDeathState(ALIVE); pet->ClearUnitState(UNIT_STAT_ALL_STATE); pet->SetHealth(pet->CountPctFromMaxHealth(damage)); //pet->AIM_Initialize(); //_player->PetSpellInitialize(); pet->SavePetToDB(PET_SAVE_AS_CURRENT); } void Spell::EffectDestroyAllTotems(SpellEffIndex /*effIndex*/) { int32 mana = 0; for (uint8 slot = SUMMON_SLOT_TOTEM; slot < MAX_TOTEM_SLOT; ++slot) { if (!m_caster->m_SummonSlot[slot]) continue; Creature* totem = m_caster->GetMap()->GetCreature(m_caster->m_SummonSlot[slot]); if (totem && totem->isTotem()) { uint32 spell_id = totem->GetUInt32Value(UNIT_CREATED_BY_SPELL); SpellEntry const* spellInfo = sSpellStore.LookupEntry(spell_id); if (spellInfo) { mana += spellInfo->manaCost; mana += int32(CalculatePctU(m_caster->GetCreateMana(), spellInfo->ManaCostPercentage)); } totem->ToTotem()->UnSummon(); } } ApplyPctN(mana, damage); if (mana) m_caster->CastCustomSpell(m_caster, 39104, &mana, NULL, NULL, true); } void Spell::EffectDurabilityDamage(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; int32 slot = m_spellInfo->EffectMiscValue[effIndex]; // FIXME: some spells effects have value -1/-2 // Possibly its mean -1 all player equipped items and -2 all items if (slot < 0) { unitTarget->ToPlayer()->DurabilityPointsLossAll(damage, (slot < -1)); return; } // invalid slot value if (slot >= INVENTORY_SLOT_BAG_END) return; if (Item* item = unitTarget->ToPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, slot)) unitTarget->ToPlayer()->DurabilityPointsLoss(item, damage); ExecuteLogEffectDurabilityDamage(effIndex, unitTarget, slot, damage); } void Spell::EffectDurabilityDamagePCT(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; int32 slot = m_spellInfo->EffectMiscValue[effIndex]; // FIXME: some spells effects have value -1/-2 // Possibly its mean -1 all player equipped items and -2 all items if (slot < 0) { unitTarget->ToPlayer()->DurabilityLossAll(float(damage) / 100.0f, (slot < -1)); return; } // invalid slot value if (slot >= INVENTORY_SLOT_BAG_END) return; if (damage <= 0) return; if (Item* item = unitTarget->ToPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, slot)) unitTarget->ToPlayer()->DurabilityLoss(item, float(damage) / 100.0f); } void Spell::EffectModifyThreatPercent(SpellEffIndex /*effIndex*/) { if (!unitTarget) return; unitTarget->getThreatManager().modifyThreatPercent(m_caster, damage); } void Spell::EffectTransmitted(SpellEffIndex effIndex) { uint32 name_id = m_spellInfo->EffectMiscValue[effIndex]; GameObjectInfo const* goinfo = ObjectMgr::GetGameObjectInfo(name_id); if (!goinfo) { sLog->outErrorDb("Gameobject (Entry: %u) not exist and not created at spell (ID: %u) cast",name_id, m_spellInfo->Id); return; } float fx, fy, fz; if (m_targets.HasDst()) m_targets.m_dstPos.GetPosition(fx, fy, fz); //FIXME: this can be better check for most objects but still hack else if (m_spellInfo->EffectRadiusIndex[effIndex] && m_spellInfo->speed == 0) { float dis = GetSpellRadiusForFriend(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[effIndex])); m_caster->GetClosePoint(fx, fy, fz, DEFAULT_WORLD_OBJECT_SIZE, dis); } else { //GO is always friendly to it's creator, get range for friends float min_dis = GetSpellMinRangeForFriend(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex)); float max_dis = GetSpellMaxRangeForFriend(sSpellRangeStore.LookupEntry(m_spellInfo->rangeIndex)); float dis = (float)rand_norm() * (max_dis - min_dis) + min_dis; m_caster->GetClosePoint(fx, fy, fz, DEFAULT_WORLD_OBJECT_SIZE, dis); } Map *cMap = m_caster->GetMap(); if (goinfo->type == GAMEOBJECT_TYPE_FISHINGNODE || goinfo->type == GAMEOBJECT_TYPE_FISHINGHOLE) { LiquidData liqData; if ( !cMap->IsInWater(fx, fy, fz + 1.f/* -0.5f */, &liqData)) // Hack to prevent fishing bobber from failing to land on fishing hole { // but this is not proper, we really need to ignore not materialized objects SendCastResult(SPELL_FAILED_NOT_HERE); SendChannelUpdate(0); return; } // replace by water level in this case //fz = cMap->GetWaterLevel(fx, fy); fz = liqData.level; } // if gameobject is summoning object, it should be spawned right on caster's position else if (goinfo->type == GAMEOBJECT_TYPE_SUMMONING_RITUAL) { m_caster->GetPosition(fx, fy, fz); } GameObject* pGameObj = new GameObject; if (!pGameObj->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_GAMEOBJECT), name_id, cMap, m_caster->GetPhaseMask(), fx, fy, fz, m_caster->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 100, GO_STATE_READY)) { delete pGameObj; return; } int32 duration = GetSpellDuration(m_spellInfo); switch(goinfo->type) { case GAMEOBJECT_TYPE_FISHINGNODE: { m_caster->SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT,pGameObj->GetGUID()); m_caster->AddGameObject(pGameObj); // will removed at spell cancel // end time of range when possible catch fish (FISHING_BOBBER_READY_TIME..GetDuration(m_spellInfo)) // start time == fish-FISHING_BOBBER_READY_TIME (0..GetDuration(m_spellInfo)-FISHING_BOBBER_READY_TIME) int32 lastSec = 0; switch(urand(0, 3)) { case 0: lastSec = 3; break; case 1: lastSec = 7; break; case 2: lastSec = 13; break; case 3: lastSec = 17; break; } duration = duration - lastSec*IN_MILLISECONDS + FISHING_BOBBER_READY_TIME*IN_MILLISECONDS; break; } case GAMEOBJECT_TYPE_SUMMONING_RITUAL: { if (m_caster->GetTypeId() == TYPEID_PLAYER) { pGameObj->AddUniqueUse(m_caster->ToPlayer()); m_caster->AddGameObject(pGameObj); // will removed at spell cancel } break; } case GAMEOBJECT_TYPE_DUEL_ARBITER: // 52991 m_caster->AddGameObject(pGameObj); break; case GAMEOBJECT_TYPE_FISHINGHOLE: case GAMEOBJECT_TYPE_CHEST: default: break; } pGameObj->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); pGameObj->SetOwnerGUID(m_caster->GetGUID()); //pGameObj->SetUInt32Value(GAMEOBJECT_LEVEL, m_caster->getLevel()); pGameObj->SetSpellId(m_spellInfo->Id); ExecuteLogEffectSummonObject(effIndex, pGameObj); sLog->outStaticDebug("AddObject at SpellEfects.cpp EffectTransmitted"); //m_caster->AddGameObject(pGameObj); //m_ObjToDel.push_back(pGameObj); cMap->Add(pGameObj); if (uint32 linkedEntry = pGameObj->GetGOInfo()->GetLinkedGameObjectEntry()) { GameObject* linkedGO = new GameObject; if (linkedGO->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_GAMEOBJECT), linkedEntry, cMap, m_caster->GetPhaseMask(), fx, fy, fz, m_caster->GetOrientation(), 0.0f, 0.0f, 0.0f, 0.0f, 100, GO_STATE_READY)) { linkedGO->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); //linkedGO->SetUInt32Value(GAMEOBJECT_LEVEL, m_caster->getLevel()); linkedGO->SetSpellId(m_spellInfo->Id); linkedGO->SetOwnerGUID(m_caster->GetGUID()); ExecuteLogEffectSummonObject(effIndex, linkedGO); linkedGO->GetMap()->Add(linkedGO); } else { delete linkedGO; linkedGO = NULL; return; } } } void Spell::EffectProspecting(SpellEffIndex /*effIndex*/) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player* p_caster = (Player*)m_caster; if (!itemTarget || !(itemTarget->GetProto()->Flags & ITEM_PROTO_FLAG_PROSPECTABLE)) return; if (itemTarget->GetCount() < 5) return; if (sWorld->getBoolConfig(CONFIG_SKILL_PROSPECTING)) { uint32 SkillValue = p_caster->GetPureSkillValue(SKILL_JEWELCRAFTING); uint32 reqSkillValue = itemTarget->GetProto()->RequiredSkillRank; p_caster->UpdateGatherSkill(SKILL_JEWELCRAFTING, SkillValue, reqSkillValue); } m_caster->ToPlayer()->SendLoot(itemTarget->GetGUID(), LOOT_PROSPECTING); } void Spell::EffectMilling(SpellEffIndex /*effIndex*/) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player* p_caster = (Player*)m_caster; if (!itemTarget || !(itemTarget->GetProto()->Flags & ITEM_PROTO_FLAG_MILLABLE)) return; if (itemTarget->GetCount() < 5) return; if (sWorld->getBoolConfig(CONFIG_SKILL_MILLING)) { uint32 SkillValue = p_caster->GetPureSkillValue(SKILL_INSCRIPTION); uint32 reqSkillValue = itemTarget->GetProto()->RequiredSkillRank; p_caster->UpdateGatherSkill(SKILL_INSCRIPTION, SkillValue, reqSkillValue); } m_caster->ToPlayer()->SendLoot(itemTarget->GetGUID(), LOOT_MILLING); } void Spell::EffectSkill(SpellEffIndex /*effIndex*/) { sLog->outDebug("WORLD: SkillEFFECT"); } /* There is currently no need for this effect. We handle it in Battleground.cpp If we would handle the resurrection here, the spiritguide would instantly disappear as the player revives, and so we wouldn't see the spirit heal visual effect on the npc. This is why we use a half sec delay between the visual effect and the resurrection itself */ void Spell::EffectSpiritHeal(SpellEffIndex /*effIndex*/) { /* if (!unitTarget || unitTarget->isAlive()) return; if (unitTarget->GetTypeId() != TYPEID_PLAYER) return; if (!unitTarget->IsInWorld()) return; //m_spellInfo->EffectBasePoints[i]; == 99 (percent?) //unitTarget->ToPlayer()->setResurrect(m_caster->GetGUID(), unitTarget->GetPositionX(), unitTarget->GetPositionY(), unitTarget->GetPositionZ(), unitTarget->GetMaxHealth(), unitTarget->GetMaxPower(POWER_MANA)); unitTarget->ToPlayer()->ResurrectPlayer(1.0f); unitTarget->ToPlayer()->SpawnCorpseBones(); */ } // remove insignia spell effect void Spell::EffectSkinPlayerCorpse(SpellEffIndex /*effIndex*/) { sLog->outDebug("Effect: SkinPlayerCorpse"); if ((m_caster->GetTypeId() != TYPEID_PLAYER) || (unitTarget->GetTypeId() != TYPEID_PLAYER) || (unitTarget->isAlive())) return; unitTarget->ToPlayer()->RemovedInsignia((Player*)m_caster); } void Spell::EffectStealBeneficialBuff(SpellEffIndex effIndex) { sLog->outDebug("Effect: StealBeneficialBuff"); if (!unitTarget || unitTarget == m_caster) // can't steal from self return; DispelChargesList steal_list; // Create dispel mask by dispel type uint32 dispelMask = GetDispellMask(DispelType(m_spellInfo->EffectMiscValue[effIndex])); Unit::AuraMap const& auras = unitTarget->GetOwnedAuras(); for (Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { Aura * aura = itr->second; AuraApplication * aurApp = aura->GetApplicationOfTarget(unitTarget->GetGUID()); if (!aurApp) continue; if ((1<<aura->GetSpellProto()->Dispel) & dispelMask) { // Need check for passive? this if (!aurApp->IsPositive() || aura->IsPassive() || aura->GetSpellProto()->AttributesEx4 & SPELL_ATTR4_NOT_STEALABLE) continue; // The charges / stack amounts don't count towards the total number of auras that can be dispelled. // Ie: A dispel on a target with 5 stacks of Winters Chill and a Polymorph has 1 / (1 + 1) -> 50% chance to dispell // Polymorph instead of 1 / (5 + 1) -> 16%. bool dispel_charges = aura->GetSpellProto()->AttributesEx7 & SPELL_ATTR7_DISPEL_CHARGES; uint8 charges = dispel_charges ? aura->GetCharges() : aura->GetStackAmount(); if (charges > 0) steal_list.push_back(std::make_pair(aura, charges)); } } if (steal_list.empty()) return; // Ok if exist some buffs for dispel try dispel it uint32 failCount = 0; DispelList success_list; WorldPacket dataFail(SMSG_DISPEL_FAILED, 8+8+4+4+damage*4); // dispel N = damage buffs (or while exist buffs for dispel) for (int32 count = 0; count < damage && !steal_list.empty();) { // Random select buff for dispel DispelChargesList::iterator itr = steal_list.begin(); std::advance(itr, urand(0, steal_list.size() - 1)); bool success = false; // 2.4.3 Patch Notes: "Dispel effects will no longer attempt to remove effects that have 100% dispel resistance." if (!GetDispelChance(itr->first->GetCaster(), unitTarget, itr->first->GetId(), !unitTarget->IsFriendlyTo(m_caster), &success)) { steal_list.erase(itr); continue; } else { if (success) { success_list.push_back(std::make_pair(itr->first->GetId(), itr->first->GetCasterGUID())); --itr->second; if (itr->second <= 0) steal_list.erase(itr); } else { if (!failCount) { // Failed to dispell dataFail << uint64(m_caster->GetGUID()); // Caster GUID dataFail << uint64(unitTarget->GetGUID()); // Victim GUID dataFail << uint32(m_spellInfo->Id); // dispel spell id } ++failCount; dataFail << uint32(itr->first->GetId()); // Spell Id } ++count; } } if (failCount) m_caster->SendMessageToSet(&dataFail, true); if (success_list.empty()) return; WorldPacket dataSuccess(SMSG_SPELLSTEALLOG, 8+8+4+1+4+damage*5); dataSuccess.append(unitTarget->GetPackGUID()); // Victim GUID dataSuccess.append(m_caster->GetPackGUID()); // Caster GUID dataSuccess << uint32(m_spellInfo->Id); // dispel spell id dataSuccess << uint8(0); // not used dataSuccess << uint32(success_list.size()); // count for (DispelList::iterator itr = success_list.begin(); itr!=success_list.end(); ++itr) { dataSuccess << uint32(itr->first); // Spell Id dataSuccess << uint8(0); // 0 - steals !=0 transfers unitTarget->RemoveAurasDueToSpellBySteal(itr->first, itr->second, m_caster); } m_caster->SendMessageToSet(&dataSuccess, true); } void Spell::EffectKillCreditPersonal(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; unitTarget->ToPlayer()->KilledMonsterCredit(m_spellInfo->EffectMiscValue[effIndex], 0); } void Spell::EffectKillCredit(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; int32 creatureEntry = m_spellInfo->EffectMiscValue[effIndex]; if (!creatureEntry) { if (m_spellInfo->Id == 42793) // Burn Body creatureEntry = 24008; // Fallen Combatant } if (creatureEntry) unitTarget->ToPlayer()->RewardPlayerAndGroupAtEvent(creatureEntry, unitTarget); } void Spell::EffectQuestFail(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; unitTarget->ToPlayer()->FailQuest(m_spellInfo->EffectMiscValue[effIndex]); } void Spell::EffectQuestStart(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player * player = unitTarget->ToPlayer(); if (Quest const* qInfo = sObjectMgr->GetQuestTemplate(m_spellInfo->EffectMiscValue[effIndex])) { if (player->CanTakeQuest(qInfo, false) && player->CanAddQuest(qInfo, false)) { player->AddQuest(qInfo, NULL); } } } void Spell::EffectActivateRune(SpellEffIndex effIndex) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player *plr = (Player*)m_caster; if (plr->getClass() != CLASS_DEATH_KNIGHT) return; // needed later m_runesState = m_caster->ToPlayer()->GetRunesState(); uint32 count = damage; if (count == 0) count = 1; for (uint32 j = 0; j < MAX_RUNES && count > 0; ++j) { if (plr->GetRuneCooldown(j) && plr->GetCurrentRune(j) == RuneType(m_spellInfo->EffectMiscValue[effIndex])) { plr->SetRuneCooldown(j, 0); --count; } } // Empower rune weapon if (m_spellInfo->Id == 47568) { // Need to do this just once if (effIndex != 0) return; for (uint32 i = 0; i < MAX_RUNES; ++i) { if (plr->GetRuneCooldown(i) && (plr->GetCurrentRune(i) == RUNE_FROST || plr->GetCurrentRune(i) == RUNE_DEATH)) plr->SetRuneCooldown(i, 0); } } } void Spell::EffectCreateTamedPet(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER || unitTarget->GetPetGUID() || unitTarget->getClass() != CLASS_HUNTER) return; uint32 creatureEntry = m_spellInfo->EffectMiscValue[effIndex]; Pet * pet = unitTarget->CreateTamedPetFrom(creatureEntry, m_spellInfo->Id); if (!pet) return; // add to world pet->GetMap()->Add(pet->ToCreature()); // unitTarget has pet now unitTarget->SetMinion(pet, true); pet->InitTalentForLevel(); if (unitTarget->GetTypeId() == TYPEID_PLAYER) { pet->SavePetToDB(PET_SAVE_AS_CURRENT); unitTarget->ToPlayer()->PetSpellInitialize(); } } void Spell::EffectDiscoverTaxi(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; uint32 nodeid = m_spellInfo->EffectMiscValue[effIndex]; if (sTaxiNodesStore.LookupEntry(nodeid)) unitTarget->ToPlayer()->GetSession()->SendDiscoverNewTaxiNode(nodeid); } void Spell::EffectTitanGrip(SpellEffIndex /*effIndex*/) { if (unitTarget && unitTarget->GetTypeId() == TYPEID_PLAYER) unitTarget->ToPlayer()->SetCanTitanGrip(true); } void Spell::EffectRedirectThreat(SpellEffIndex /*effIndex*/) { if (unitTarget) m_caster->SetReducedThreatPercent((uint32)damage, unitTarget->GetGUID()); } void Spell::EffectWMODamage(SpellEffIndex /*effIndex*/) { if (gameObjTarget && gameObjTarget->GetGoType() == GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING) { Unit *caster = m_originalCaster; if (!caster) return; // Do not allow damage if hp is 0 if (gameObjTarget->GetGOValue()->building.health == 0) return; FactionTemplateEntry const *casterft, *goft; casterft = caster->getFactionTemplateEntry(); goft = sFactionTemplateStore.LookupEntry(gameObjTarget->GetUInt32Value(GAMEOBJECT_FACTION)); // Do not allow to damage GO's of friendly factions (ie: Wintergrasp Walls/Ulduar Storm Beacons) if ((casterft && goft && !casterft->IsFriendlyTo(*goft)) || !goft) { gameObjTarget->TakenDamage(uint32(damage), caster); WorldPacket data(SMSG_DESTRUCTIBLE_BUILDING_DAMAGE, 8+8+8+4+4); data.append(gameObjTarget->GetPackGUID()); data.append(caster->GetPackGUID()); if (Unit *who = caster->GetCharmerOrOwner()) data.append(who->GetPackGUID()); else data << uint8(0); data << uint32(damage); data << uint32(m_spellInfo->Id); gameObjTarget->SendMessageToSet(&data, false); } } } void Spell::EffectWMORepair(SpellEffIndex /*effIndex*/) { if (gameObjTarget && gameObjTarget->GetGoType() == GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING) gameObjTarget->Rebuild(); } void Spell::EffectWMOChange(SpellEffIndex effIndex) { if (gameObjTarget && gameObjTarget->GetGoType() == GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING) { Unit* caster = m_originalCaster; if (!caster) return; int ChangeType = m_spellInfo->EffectMiscValue[effIndex]; switch (ChangeType) { case 0: // intact if (gameObjTarget->HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED)) gameObjTarget->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED); if (gameObjTarget->HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED)) gameObjTarget->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED); break; case 1: // damaged gameObjTarget->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_DAMAGED); break; case 2: // destroyed gameObjTarget->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED); break; case 3: // rebuild gameObjTarget->Rebuild(); break; } } } void Spell::SummonGuardian(uint32 i, uint32 entry, SummonPropertiesEntry const *properties) { Unit *caster = m_originalCaster; if (!caster) return; if (caster->isTotem()) caster = caster->ToTotem()->GetOwner(); // in another case summon new uint8 level = caster->getLevel(); // level of pet summoned using engineering item based at engineering skill level if (m_CastItem && caster->GetTypeId() == TYPEID_PLAYER) if (ItemPrototype const *proto = m_CastItem->GetProto()) if (proto->RequiredSkill == SKILL_ENGINERING) if (uint16 skill202 = caster->ToPlayer()->GetSkillValue(SKILL_ENGINERING)) level = skill202/5; //float radius = GetSpellRadiusForFriend(sSpellRadiusStore.LookupEntry(m_spellInfo->EffectRadiusIndex[i])); float radius = 5.0f; uint32 amount = damage > 0 ? damage : 1; int32 duration = GetSpellDuration(m_spellInfo); switch (m_spellInfo->Id) { case 1122: // Inferno amount = 1; break; case 49028: // Dancing Rune Weapon if (AuraEffect *aurEff = m_originalCaster->GetAuraEffect(63330, 0)) // glyph of Dancing Rune Weapon duration += aurEff->GetAmount(); break; } if (Player* modOwner = m_originalCaster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration); //TempSummonType summonType = (duration == 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN; Map *map = caster->GetMap(); for (uint32 count = 0; count < amount; ++count) { Position pos; GetSummonPosition(i, pos, radius, count); TempSummon *summon = map->SummonCreature(entry, pos, properties, duration, caster); if (!summon) return; if (summon->HasUnitTypeMask(UNIT_MASK_GUARDIAN)) ((Guardian*)summon)->InitStatsForLevel(level); summon->SetUInt32Value(UNIT_CREATED_BY_SPELL, m_spellInfo->Id); if (summon->HasUnitTypeMask(UNIT_MASK_MINION) && m_targets.HasDst()) ((Minion*)summon)->SetFollowAngle(m_caster->GetAngle(summon)); if (summon->GetEntry() == 27893) { if (uint32 weapon = m_caster->GetUInt32Value(PLAYER_VISIBLE_ITEM_16_ENTRYID)) { summon->SetDisplayId(11686); summon->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID, weapon); } else summon->SetDisplayId(1126); } summon->AI()->EnterEvadeMode(); ExecuteLogEffectSummonObject(i, summon); } } void Spell::GetSummonPosition(uint32 i, Position &pos, float radius, uint32 count) { pos.SetOrientation(m_caster->GetOrientation()); if (m_targets.HasDst()) { // Summon 1 unit in dest location if (count == 0) pos.Relocate(m_targets.m_dstPos); // Summon in random point all other units if location present else { //This is a workaround. Do not have time to write much about it switch (m_spellInfo->EffectImplicitTargetA[i]) { case TARGET_MINION: case TARGET_DEST_CASTER_RANDOM: m_caster->GetNearPosition(pos, radius * (float)rand_norm(), (float)rand_norm()*static_cast<float>(2*M_PI)); break; case TARGET_DEST_DEST_RANDOM: case TARGET_DEST_TARGET_RANDOM: m_caster->GetRandomPoint(m_targets.m_dstPos, radius, pos); break; default: pos.Relocate(m_targets.m_dstPos); break; } } } // Summon if dest location not present near caster else { float x, y, z; m_caster->GetClosePoint(x,y,z,3.0f); pos.Relocate(x, y, z); } } void Spell::EffectRenamePet(SpellEffIndex /*effIndex*/) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT || !unitTarget->ToCreature()->isPet() || ((Pet*)unitTarget)->getPetType() != HUNTER_PET) return; unitTarget->SetByteFlag(UNIT_FIELD_BYTES_2, 2, UNIT_CAN_BE_RENAMED); } void Spell::EffectPlayMusic(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; uint32 soundid = m_spellInfo->EffectMiscValue[effIndex]; if (!sSoundEntriesStore.LookupEntry(soundid)) { sLog->outError("EffectPlayMusic: Sound (Id: %u) not exist in spell %u.",soundid,m_spellInfo->Id); return; } WorldPacket data(SMSG_PLAY_MUSIC, 4); data << uint32(soundid); unitTarget->ToPlayer()->GetSession()->SendPacket(&data); } void Spell::EffectSpecCount(SpellEffIndex /*effIndex*/) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; unitTarget->ToPlayer()->UpdateSpecCount(damage); } void Spell::EffectActivateSpec(SpellEffIndex /*effIndex*/) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; unitTarget->ToPlayer()->ActivateSpec(damage-1); // damage is 1 or 2, spec is 0 or 1 } void Spell::EffectPlayerNotification(SpellEffIndex /*effIndex*/) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; switch(m_spellInfo->Id) { case 58730: // Restricted Flight Area case 58600: // Restricted Flight Area unitTarget->ToPlayer()->GetSession()->SendNotification(LANG_ZONE_NOFLYZONE); break; } } void Spell::EffectRemoveAura(SpellEffIndex effIndex) { if (!unitTarget) return; // there may be need of specifying casterguid of removed auras unitTarget->RemoveAurasDueToSpell(m_spellInfo->EffectTriggerSpell[effIndex]); } void Spell::EffectCastButtons(SpellEffIndex effIndex) { if (!unitTarget || m_caster->GetTypeId() != TYPEID_PLAYER) return; Player *p_caster = (Player*)m_caster; uint32 button_id = m_spellInfo->EffectMiscValue[effIndex] + 132; uint32 n_buttons = m_spellInfo->EffectMiscValueB[effIndex]; for (; n_buttons; n_buttons--, button_id++) { ActionButton const* ab = p_caster->GetActionButton(button_id); if (!ab || ab->GetType() != ACTION_BUTTON_SPELL) continue; uint32 spell_id = ab->GetAction(); if (!spell_id) continue; if (p_caster->HasSpellCooldown(spell_id)) continue; SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id); uint32 cost = CalculatePowerCost(spellInfo, m_caster, GetSpellSchoolMask(spellInfo)); if (m_caster->GetPower(POWER_MANA) < cost) break; m_caster->CastSpell(unitTarget, spell_id, true); m_caster->ModifyPower(POWER_MANA, -(int32)cost); p_caster->AddSpellAndCategoryCooldowns(spellInfo, 0); } } void Spell::EffectRechargeManaGem(SpellEffIndex /*effIndex*/) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player *player = m_caster->ToPlayer(); if (!player) return; uint32 item_id = m_spellInfo->EffectItemType[0]; ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item_id); if (!pProto) { player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); return; } if (Item* pItem = player->GetItemByEntry(item_id)) { for (int x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x) pItem->SetSpellCharges(x,pProto->Spells[x].SpellCharges); pItem->SetState(ITEM_CHANGED,player); } } void Spell::EffectBind(SpellEffIndex effIndex) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* player = unitTarget->ToPlayer(); uint32 area_id; WorldLocation loc; if (m_spellInfo->EffectImplicitTargetA[effIndex] == TARGET_DST_DB || m_spellInfo->EffectImplicitTargetB[effIndex] == TARGET_DST_DB) { SpellTargetPosition const* st = sSpellMgr->GetSpellTargetPosition(m_spellInfo->Id); if (!st) { sLog->outError("Spell::EffectBind - unknown teleport coordinates for spell ID %u", m_spellInfo->Id); return; } loc.m_mapId = st->target_mapId; loc.m_positionX = st->target_X; loc.m_positionY = st->target_Y; loc.m_positionZ = st->target_Z; loc.m_orientation = st->target_Orientation; area_id = player->GetAreaId(); } else { player->GetPosition(&loc); area_id = player->GetAreaId(); } player->SetHomebind(loc, area_id); // binding WorldPacket data(SMSG_BINDPOINTUPDATE, (4+4+4+4+4)); data << float(loc.m_positionX); data << float(loc.m_positionY); data << float(loc.m_positionZ); data << uint32(loc.m_mapId); data << uint32(area_id); player->SendDirectMessage(&data); sLog->outStaticDebug("New homebind X : %f", loc.m_positionX); sLog->outStaticDebug("New homebind Y : %f", loc.m_positionY); sLog->outStaticDebug("New homebind Z : %f", loc.m_positionZ); sLog->outStaticDebug("New homebind MapId : %u", loc.m_mapId); sLog->outStaticDebug("New homebind AreaId : %u", area_id); // zone update data.Initialize(SMSG_PLAYERBOUND, 8+4); data << uint64(player->GetGUID()); data << uint32(area_id); player->SendDirectMessage( &data ); }
sureandrew/trinitycore
src/server/game/Spells/SpellEffects.cpp
C++
gpl-2.0
291,013
<?php return [ 'author' => null, // Author is still available (Khalil Hymore), just not from LD+JSON. 'categories' => [ 'Food', 'Cooking', 'Recipes', ], 'cookingMethod' => null, 'cookTime' => null, 'cuisines' => null, 'description' => 'You know what would be a really good occasion to make this creamy, dreamy dessert? Tuesday. Also: any other day. It turns an ordinary afternoon into a party, so you really ought to try all the flavor combos. You can also save a step and just use store-bought whipped topping instead of making your own. Whatever makes you happy - because that\'s the whole point.', 'image' => 'https://hips.hearstapps.com/rbk.h-cdn.co/assets/16/30/1469475350-rbk080116icecreampies-001.jpg', 'ingredients' => [ '14 oz. store-bought cookies (for this recipe we used an 11.3-oz package of pecan shortbread cookies)', '1 tbsp. sugar', '1/2 tsp. kosher salt', '4 tbsp. unsalted butter, melted', '4 pt. ice cream or sorbet (we used 2 pints each ice cream and raspberry sorbet)', '2 c. filling toppings: candy, fruit, sauces, or additional cookies (we used a 6-oz container of fresh raspberries and 2 small fresh peaches, cored and sliced', '1 c. heavy cream', '1 tbsp. sugar', '1 tsp. vanilla', ], 'instructions' => [ 'Make the crust. Heat oven to 350°F. In a food processor, combine the cookies, sugar, and salt and process until fine crumbs form. Drizzle in the melted butter and pulse together until the mixture has the consistency of wet sand. Press into a 9-in. springform pan and bake until golden and set, 8 to 10 minutes. Set aside to cool.', 'Add the first layer. Soften 2 pints of the ice cream and spread into the pan in an even layer. Then scatter half of your chosen fillings over it. Lightly press them into the ice cream and return pan to freezer to set until firm, at least 2 hours.', 'Add the second layer. Soften the remaining 2 pints of ice cream or sorbet. Remove pan from the freezer and spread the ice cream in an even layer over the filling. Return pan to freezer to set until firm, at least 2 hours.', 'Top it off. Whip the heavy cream, sugar, and vanilla to soft peaks. Remove pie from freezer and spread it with the whipped cream. Scatter the remaining fillings over the top. Return to the freezer to set at least 1 hour (wrapped in plastic wrap, it will keep up to 3 months). Remove pie from freezer. Run a small sharp knife or offset spatula around the edge of the pan and remove ring. Warm the blade of a sharp knife in hot water and slice the pie. Serve immediately.', ], 'name' => 'Anyone Can Make This Deliciously Decadent Ice Cream Pie', 'notes' => null, 'prepTime' => 'PT25M', 'publisher' => 'Redbook', 'totalTime' => 'PT35M', 'url' => 'https://www.redbookmag.com/food-recipes/recipes/a45244/ice-cream-pie-recipe/', 'yield' => '1', ];
ssnepenthe/recipe-scraper
tests/data/results/www.redbookmag.com/food-recipes-recipes-a45244-ice-cream-pie-recipe.php
PHP
gpl-2.0
2,988
/**************************************************************************** * * ViSP, open source Visual Servoing Platform software. * Copyright (C) 2005 - 2019 by Inria. All rights reserved. * * This software 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. * See the file LICENSE.txt at the root directory of this source * distribution for additional information about the GNU GPL. * * For using ViSP with software that can not be combined with the GNU * GPL, please contact Inria about acquiring a ViSP Professional * Edition License. * * See http://visp.inria.fr for more information. * * This software was developed at: * Inria Rennes - Bretagne Atlantique * Campus Universitaire de Beaulieu * 35042 Rennes Cedex * France * * If you have questions regarding the use of this file, please contact * Inria at visp@inria.fr * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * Description: * Benchmark Gaussian filter. * *****************************************************************************/ #include <visp3/core/vpConfig.h> #ifdef VISP_HAVE_CATCH2 #define CATCH_CONFIG_ENABLE_BENCHMARKING #define CATCH_CONFIG_RUNNER #include <catch.hpp> #include <visp3/io/vpImageIo.h> #include <visp3/core/vpIoTools.h> #include <visp3/core/vpImageFilter.h> #include <visp3/core/vpGaussianFilter.h> static const std::string ipath = vpIoTools::getViSPImagesDataPath(); static std::string imagePath = vpIoTools::createFilePath(ipath, "faces/1280px-Solvay_conference_1927.png"); TEST_CASE("vpGaussianFilter", "[benchmark]") { SECTION("unsigned char") { vpImage<unsigned char> I, I_blur; vpImageIo::read(I, imagePath); const float sigma = 5.0f; vpGaussianFilter gaussianFilter(I.getWidth(), I.getHeight(), sigma); BENCHMARK("Benchmark vpGaussianFilter uchar") { gaussianFilter.apply(I, I_blur); return I_blur; }; } SECTION("vpRGBa") { vpImage<vpRGBa> I, I_blur; vpImageIo::read(I, imagePath); const float sigma = 5.0f; vpGaussianFilter gaussianFilter(I.getWidth(), I.getHeight(), sigma); BENCHMARK("Benchmark vpGaussianFilter vpRGBa") { gaussianFilter.apply(I, I_blur); return I_blur; }; } SECTION("vpRGBa + deinterleave") { vpImage<vpRGBa> I, I_blur; vpImageIo::read(I, imagePath); const float sigma = 5.0f; const bool deinterleave = true; vpGaussianFilter gaussianFilter(I.getWidth(), I.getHeight(), sigma, deinterleave); BENCHMARK("Benchmark vpGaussianFilter vpRGBa") { gaussianFilter.apply(I, I_blur); return I_blur; }; } } TEST_CASE("vpImageFilter::gaussianBlur", "[benchmark]") { SECTION("unsigned char") { vpImage<unsigned char> I; vpImageIo::read(I, imagePath); vpImage<double> I_blur; const unsigned int kernelSize = 7; const double sigma = 5.0; BENCHMARK("Benchmark vpImageFilter::gaussianBlur uchar") { vpImageFilter::gaussianBlur(I, I_blur, kernelSize, sigma); return I_blur; }; } SECTION("vpRGBa") { vpImage<vpRGBa> I, I_blur; vpImageIo::read(I, imagePath); const unsigned int kernelSize = 7; const double sigma = 5.0; BENCHMARK("Benchmark vpImageFilter::gaussianBlur vpRGBa") { vpImageFilter::gaussianBlur(I, I_blur, kernelSize, sigma); return I_blur; }; } } #if (VISP_HAVE_OPENCV_VERSION >= 0x020101) TEST_CASE("Gaussian filter (OpenCV)", "[benchmark]") { SECTION("unsigned char") { cv::Mat img, img_blur; img = cv::imread(imagePath, cv::IMREAD_GRAYSCALE); const double sigma = 5.0; BENCHMARK("Benchmark Gaussian filter uchar (OpenCV)") { cv::GaussianBlur(img, img_blur, cv::Size(), sigma); return img_blur; }; } SECTION("BGR") { cv::Mat img, img_blur; img = cv::imread(imagePath, cv::IMREAD_COLOR); const double sigma = 5.0; BENCHMARK("Benchmark Gaussian filter BGR (OpenCV)") { cv::GaussianBlur(img, img_blur, cv::Size(), sigma); return img_blur; }; } } #endif int main(int argc, char *argv[]) { Catch::Session session; // There must be exactly one instance bool runBenchmark = false; // Build a new parser on top of Catch's using namespace Catch::clara; auto cli = session.cli() // Get Catch's composite command line parser | Opt(runBenchmark) // bind variable to a new option, with a hint string ["--benchmark"] // the option names it will respond to ("run benchmark?") // description string for the help output ; // Now pass the new composite back to Catch so it uses that session.cli(cli); // Let Catch (using Clara) parse the command line session.applyCommandLine(argc, argv); if (runBenchmark) { int numFailed = session.run(); // numFailed is clamped to 255 as some unices only use the lower 8 bits. // This clamping has already been applied, so just return it here // You can also do any post run clean-up here return numFailed; } return EXIT_SUCCESS; } #else #include <iostream> int main() { return 0; } #endif
lagadic/visp
modules/core/test/image-with-dataset/perfGaussianFilter.cpp
C++
gpl-2.0
5,342
#if defined(_WIN64) || defined(WIN64) || defined(_WIN32) || defined(WIN32) # if defined(_MSC_VER) # if defined(DEBUG) || defined(_DEBUG) #pragma comment(lib, "adisusbzd.lib") # else #pragma comment(lib, "adisusbz.lib") # endif # else #error [SWL] not supported compiler # endif #elif defined(__MINGW32__) # if defined(__GUNC__) # if defined(DEBUG) || defined(_DEBUG) # else # endif # else #error [SWL] not supported compiler # endif #elif defined(__CYGWIN__) # if defined(__GUNC__) # if defined(DEBUG) || defined(_DEBUG) # else # endif # else #error [SWL] not supported compiler # endif #elif defined(__unix__) || defined(__unix) || defined(unix) || defined(__linux__) || defined(__linux) || defined(linux) # if defined(__GUNC__) # if defined(DEBUG) || defined(_DEBUG) # else # endif # else #error [SWL] not supported compiler # endif #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__ ) || defined(__DragonFly__) # if defined(__GUNC__) # if defined(DEBUG) || defined(_DEBUG) # else # endif # else #error [SWL] not supported compiler # endif #elif defined(__APPLE__) # if defined(__GUNC__) # if defined(DEBUG) || defined(_DEBUG) # else # endif # else #error [SWL] not supported compiler # endif #else #error [SWL] not supported operating sytem #endif
sangwook236/general-development-and-testing
hw_dev/ext/test/imu/library_autolinking.cpp
C++
gpl-2.0
1,428
#!/usr/bin/env python # encoding: utf-8 # # rbootstrap - Install RPM based Linux into chroot jails # Copyright (C) 2014 Lars Michelsen <lm@larsmichelsen.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # 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. class RBError(Exception): pass class BailOut(RBError): """ Is used to terminate the program with an error message """ pass
LaMi-/rbootstrap
rbootstrap/exceptions.py
Python
gpl-2.0
1,001
<?php namespace Drupal\simpletest\Tests; use Drupal\Core\Url; use Drupal\simpletest\WebTestBase; /** * Tests the Simpletest UI internal browser. * * @group simpletest */ class SimpleTestBrowserTest extends WebTestBase { /** * Modules to enable. * * @var array */ public static $modules = array('simpletest', 'test_page_test'); protected function setUp() { parent::setUp(); // Create and log in an admin user. $this->drupalLogin($this->drupalCreateUser(array('administer unit tests'))); } /** * Test the internal browsers functionality. */ public function testInternalBrowser() { // Retrieve the test page and check its title and headers. $this->drupalGet('test-page'); $this->assertTrue($this->drupalGetHeader('Date'), 'An HTTP header was received.'); $this->assertTitle(t('Test page | @site-name', array( '@site-name' => $this->config('system.site')->get('name'), ))); $this->assertNoTitle('Foo'); $old_user_id = $this->container->get('current_user')->id(); $user = $this->drupalCreateUser(); $this->drupalLogin($user); // Check that current user service updated. $this->assertNotEqual($old_user_id, $this->container->get('current_user')->id(), 'Current user service updated.'); $headers = $this->drupalGetHeaders(TRUE); $this->assertEqual(count($headers), 2, 'There was one intermediate request.'); $this->assertTrue(strpos($headers[0][':status'], '303') !== FALSE, 'Intermediate response code was 303.'); $this->assertFalse(empty($headers[0]['location']), 'Intermediate request contained a Location header.'); $this->assertEqual($this->getUrl(), $headers[0]['location'], 'HTTP redirect was followed'); $this->assertFalse($this->drupalGetHeader('Location'), 'Headers from intermediate request were reset.'); $this->assertResponse(200, 'Response code from intermediate request was reset.'); $this->drupalLogout(); // Check that current user service updated to anonymous user. $this->assertEqual(0, $this->container->get('current_user')->id(), 'Current user service updated.'); // Test the maximum redirection option. $this->maximumRedirects = 1; $edit = array( 'name' => $user->getUsername(), 'pass' => $user->pass_raw ); $this->drupalPostForm('user/login', $edit, t('Log in'), array( 'query' => array('destination' => 'user/logout'), )); $headers = $this->drupalGetHeaders(TRUE); $this->assertEqual(count($headers), 2, 'Simpletest stopped following redirects after the first one.'); // Remove the Simpletest private key file so we can test the protection // against requests that forge a valid testing user agent to gain access // to the installer. // @see drupal_valid_test_ua() // Not using File API; a potential error must trigger a PHP warning. unlink($this->siteDirectory . '/.htkey'); $this->drupalGet(Url::fromUri('base:core/install.php', array('external' => TRUE, 'absolute' => TRUE))->toString()); $this->assertResponse(403, 'Cannot access install.php.'); } /** * Test validation of the User-Agent header we use to perform test requests. */ public function testUserAgentValidation() { global $base_url; // Logout the user which was logged in during test-setup. $this->drupalLogout(); $system_path = $base_url . '/' . drupal_get_path('module', 'system'); $HTTP_path = $system_path . '/tests/http.php/user/login'; $https_path = $system_path . '/tests/https.php/user/login'; // Generate a valid simpletest User-Agent to pass validation. $this->assertTrue(preg_match('/simpletest\d+/', $this->databasePrefix, $matches), 'Database prefix contains simpletest prefix.'); $test_ua = drupal_generate_test_ua($matches[0]); $this->additionalCurlOptions = array(CURLOPT_USERAGENT => $test_ua); // Test pages only available for testing. $this->drupalGet($HTTP_path); $this->assertResponse(200, 'Requesting http.php with a legitimate simpletest User-Agent returns OK.'); $this->drupalGet($https_path); $this->assertResponse(200, 'Requesting https.php with a legitimate simpletest User-Agent returns OK.'); // Now slightly modify the HMAC on the header, which should not validate. $this->additionalCurlOptions = array(CURLOPT_USERAGENT => $test_ua . 'X'); $this->drupalGet($HTTP_path); $this->assertResponse(403, 'Requesting http.php with a bad simpletest User-Agent fails.'); $this->drupalGet($https_path); $this->assertResponse(403, 'Requesting https.php with a bad simpletest User-Agent fails.'); // Use a real User-Agent and verify that the special files http.php and // https.php can't be accessed. $this->additionalCurlOptions = array(CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12'); $this->drupalGet($HTTP_path); $this->assertResponse(403, 'Requesting http.php with a normal User-Agent fails.'); $this->drupalGet($https_path); $this->assertResponse(403, 'Requesting https.php with a normal User-Agent fails.'); } /** * Tests that PHPUnit and KernelTestBase tests work through the UI. */ public function testTestingThroughUI() { $this->drupalGet('admin/config/development/testing'); $this->assertTrue(strpos($this->drupalSettings['simpleTest']['images'][0], 'core/misc/menu-collapsed.png') > 0, 'drupalSettings contains a link to core/misc/menu-collapsed.png.'); // We can not test WebTestBase tests here since they require a valid .htkey // to be created. However this scenario is covered by the testception of // \Drupal\simpletest\Tests\SimpleTestTest. $tests = array( // A KernelTestBase test. 'Drupal\KernelTests\KernelTestBaseTest', // A PHPUnit unit test. 'Drupal\Tests\action\Unit\Menu\ActionLocalTasksTest', // A PHPUnit functional test. 'Drupal\FunctionalTests\BrowserTestBaseTest', ); foreach ($tests as $test) { $this->drupalGet('admin/config/development/testing'); $edit = array( "tests[$test]" => TRUE, ); $this->drupalPostForm(NULL, $edit, t('Run tests')); $this->assertText('0 fails, 0 exceptions'); } } }
jackbravo/drupal8-basic-rest
core/modules/simpletest/src/Tests/SimpleTestBrowserTest.php
PHP
gpl-2.0
6,284
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('common', '0004_category'), ('seller', '0014_auto_20150607_0943'), ] operations = [ migrations.AddField( model_name='asset', name='newcategories', field=models.ManyToManyField(to='common.Category'), ), ]
tomcounsell/Cobra
apps/seller/migrations/0015_asset_newcategories.py
Python
gpl-2.0
455
// https://www.hackerrank.com/challenges/the-love-letter-mystery // by.0263 package main import "fmt" func main() { var jumSoal, changes, diff int var inputan string fmt.Scan(&jumSoal) for soal := 1; soal <= jumSoal; soal++ { fmt.Scan(&inputan) changes = 0 for i := 0; i < len(inputan)/2; i++ { diff = int(inputan[i]) - int(inputan[len(inputan)-i-1]) if (diff < 0) { changes -= diff } else { changes += diff } } fmt.Println(changes) } }
leo0263/hackergo
01 Warming Up/01 08 Angry Children .go
GO
gpl-2.0
490
// Compiler options: -warnaserror using System; using System.Reflection; using System.ComponentModel; [assembly: CLSCompliant(true)] [assembly: AssemblyTitle("")] public class CLSCLass_6 { private object disposedEvent = new object (); public EventHandlerList event_handlers; public event Delegate Disposed { add { event_handlers.AddHandler (disposedEvent, value); } remove { event_handlers.RemoveHandler (disposedEvent, value); } } } public delegate CLSDelegate Delegate (); [Serializable] public class CLSDelegate { } #pragma warning disable 3019 internal class CLSClass_5 { [CLSCompliant (true)] public uint Test () { return 1; } } #pragma warning restore 3019 [CLSCompliant (true)] public class CLSClass_4 { [CLSCompliant (false)] public uint Test () { return 1; } } public class CLSClass_3 { [CLSCompliant (false)] public uint Test_3 () { return 6; } } [CLSCompliant(false)] public class CLSClass_2 { public sbyte XX { get { return -1; } } } class CLSClass_1 { public UInt32 Valid() { return 5; } } [CLSCompliant(true)] public class CLSClass { private class C1 { #pragma warning disable 3019 [CLSCompliant(true)] public class C11 { protected ulong Foo3() { return 1; } } #pragma warning restore 3019 protected long Foo2() { return 1; } } [CLSCompliant(false)] protected internal class CLSClass_2 { public sbyte XX { get { return -1; } } } #pragma warning disable 3019, 169 [CLSCompliant(true)] private ulong Valid() { return 1; } #pragma warning restore 3019, 169 [CLSCompliant(true)] public byte XX { get { return 5; } } // protected internal sbyte FooProtectedInternal() { // return -4; // } internal UInt32 FooInternal() { return 1; } #pragma warning disable 169 private ulong Foo() { return 1; } #pragma warning restore 169 public static void Main() {} }
xen2/mcs
tests/test-cls-00.cs
C#
gpl-2.0
2,405
/* $Id: RTPathHasPath.cpp $ */ /** @file * IPRT - RTPathHasPath */ /* * Copyright (C) 2006-2015 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ /******************************************************************************* * Header Files * *******************************************************************************/ #include "internal/iprt.h" #include <iprt/path.h> #include <iprt/string.h> /** * Checks if a path includes more than a filename. * * @returns true if path present. * @returns false if no path. * @param pszPath Path to check. */ RTDECL(bool) RTPathHasPath(const char *pszPath) { #if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2) return strpbrk(pszPath, "/\\:") != NULL; #else return strpbrk(pszPath, "/") != NULL; #endif }
sobomax/virtualbox_64bit_edd
src/VBox/Runtime/common/path/RTPathHasPath.cpp
C++
gpl-2.0
1,755
// -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- // vi: set et ts=4 sw=2 sts=2: #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <iostream> #include <dune/common/exceptions.hh> // We use exceptions #include <dune/common/parallel/mpihelper.hh> // An initializer of MPI #include <dune/common/parallel/indexset.hh> #include <dune/common/parallel/remoteindices.hh> #include <dune/common/parallel/communicator.hh> #include <dune/common/parallel/plocalindex.hh> #include <dune/common/parallel/interface.hh> #include <dune/common/enumset.hh> enum Flags { owner, ghost }; template<typename T> struct AddData { typedef typename T::value_type IndexedType; static const IndexedType& gather(const T& v, int i){ return v[i]; } static void scatter(T& v, const IndexedType& item, int i){ v[i]+=item; } }; template<typename T> struct CopyData { typedef typename T::value_type IndexedType; static const IndexedType& gather(const T& v, int i){ return v[i]; } static void scatter(T& v, const IndexedType& item, int i){ v[i]=item; } }; template<class T> void doCalculations(T&){} #if HAVE_MPI void test() { int rank; MPI_Comm comm=(MPI_COMM_WORLD); MPI_Comm_rank(MPI_COMM_WORLD, &rank); using namespace Dune; // shortcut for index set type typedef ParallelLocalIndex<Flags> LocalIndex; typedef ParallelIndexSet<int, LocalIndex > PIndexSet; PIndexSet sis; sis.beginResize(); if(rank==0) { sis.add(11, LocalIndex(0, ghost)); for(int i=1; i<=6; i++) sis.add(i-1, LocalIndex(i, owner, i<=1||i>5)); sis.add(6, LocalIndex(7, ghost)); }else{ sis.add(5, LocalIndex(0, ghost)); for(int i=1; i<=6; i++) sis.add(5+i, LocalIndex(i, owner, i<=1||i>5)); sis.add(0,LocalIndex(7, ghost)); } sis.endResize(); PIndexSet tis; tis.beginResize(); int l=0; for(int i=0; i<2; ++i) for(int j=0; j<5; ++j) { int g=rank*3-1+i*6+j; if(g<0||g>11) continue; Flags flag=(j>0&&j<4) ? owner : ghost; tis.add(g, LocalIndex(l++, flag)); } tis.endResize(); std::cout<<rank<<" isxset: "<<sis<<std::endl; RemoteIndices<PIndexSet> riRedist(sis, tis, comm); riRedist.rebuild<true>(); std::vector<int> v; RemoteIndices<PIndexSet> riS(sis,sis, comm, v, true); riS.rebuild<false>(); std::cout<<std::endl<<"begin"<<rank<<" riS="<<riS<<" end"<<rank<<std::endl<<std::endl; Combine<EnumItem<Flags,ghost>,EnumItem<Flags,owner>,Flags> ghostFlags; EnumItem<Flags,owner> ownerFlags; Combine<EnumItem<Flags,ghost>, EnumItem<Flags,owner> > allFlags; Interface infRedist; Interface infS; infRedist.build(riRedist, ownerFlags, allFlags); infS.build(riS, ownerFlags, ghostFlags); std::cout<<"inf "<<rank<<": "<<infS<<std::endl; typedef std::vector<double> Container; Container s(sis.size(),3), t(tis.size()); s[sis.size()-1]=-1; BufferedCommunicator bComm; BufferedCommunicator bCommRedist; bComm.build(s, s, infS); //bCommRedist.build(s, t, infRedist); for(std::size_t i=0; i<sis.size(); i++) std::cout<<s[i]<<" "; std::cout<<std::endl; bComm.forward<CopyData<Container> >(s,s); for(std::size_t i=0; i<sis.size(); i++) std::cout<<s[i]<<" "; std::cout<<std::endl; //bCommRedist.forward<CopyData<Container> >(s,t); // calculate on the redistributed array doCalculations(t); bCommRedist.backward<AddData<Container> >(s,t); } #endif // HAVE_MPI int main(int argc, char** argv) { try{ using namespace Dune; #if HAVE_MPI //Maybe initialize Mpi MPIHelper& helper = MPIHelper::instance(argc, argv); std::cout << "Hello World! This is poosc08. rank=" <<helper.rank()<< std::endl; test(); return 0; #else std::cout<< "Test poosc08_test disabled because MPI is not available." << std::endl; return 77; #endif // HAVE_MPI } catch (Dune::Exception &e) { std::cerr << "Dune reported error: " << e << std::endl; } catch (...) { std::cerr << "Unknown exception thrown!" << std::endl; } }
magnese/dune-common
doc/comm/poosc08_test.cc
C++
gpl-2.0
4,019
#region License /* * Copyright (C) 1999-2015 John Källén. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ #endregion using Reko.Core; using Reko.Core.Expressions; using Reko.Core.Machine; using Reko.Core.Types; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Reko.Arch.Pdp11 { public class Pdp11Disassembler : DisassemblerBase<Pdp11Instruction> { private Pdp11Architecture arch; private ImageReader rdr; private Pdp11Instruction instrCur; private PrimitiveType dataWidth; public Pdp11Disassembler(ImageReader rdr, Pdp11Architecture arch) { this.rdr = rdr; this.arch = arch; } public override Pdp11Instruction DisassembleInstruction() { if (!rdr.IsValid) return null; var addr = rdr.Address; instrCur = Disassemble(); instrCur.Address = addr; instrCur.Length = (int)(rdr.Address - addr); return instrCur; } private Pdp11Instruction DecodeOperands(ushort wOpcode, Opcodes opcode, string fmt) { List<MachineOperand> ops = new List<MachineOperand>(2); int i = 0; dataWidth = PrimitiveType.Word16; switch (fmt[i]) { case 'b': dataWidth = PrimitiveType.Byte; i += 2; break; case 'w': dataWidth = PrimitiveType.Word16; i += 2; break; } while (i != fmt.Length) { if (fmt[i] == ',') ++i; switch (fmt[i++]) { case 'E': ops.Add(DecodeOperand(wOpcode)); break; case 'e': ops.Add(DecodeOperand(wOpcode >> 6)); break; default: throw new NotImplementedException(); } } var instr = new Pdp11Instruction { Opcode = opcode, DataWidth = dataWidth, op1 = ops.Count > 0 ? ops[0] : null, op2 = ops.Count > 1 ? ops[1] : null, }; return instr; } abstract class OpRec { public abstract Pdp11Instruction Decode(ushort opcode, Pdp11Disassembler dasm); } class FormatOpRec : OpRec { private string fmt; private Opcodes opcode; public FormatOpRec(string fmt, Opcodes op) { this.fmt = fmt; this.opcode = op; } public override Pdp11Instruction Decode(ushort opcode, Pdp11Disassembler dasm) { return dasm.DecodeOperands(opcode, this.opcode, fmt); } } class FnOpRec : OpRec { private Func<ushort, Pdp11Disassembler, Pdp11Instruction> fn; public FnOpRec(Func<ushort, Pdp11Disassembler, Pdp11Instruction> fn) { this.fn = fn; } public override Pdp11Instruction Decode(ushort opcode, Pdp11Disassembler dasm) { return fn(opcode, dasm); } } private static OpRec[] decoders; static Pdp11Disassembler() { decoders = new OpRec[] { null, new FormatOpRec("w:e,E", Opcodes.mov), new FormatOpRec("E,e", Opcodes.cmp), new FormatOpRec("E,e", Opcodes.bit), new FormatOpRec("E,e", Opcodes.bic), new FormatOpRec("E,e", Opcodes.bis), new FormatOpRec("w:E,e", Opcodes.add), null, null, new FormatOpRec("b:e,E", Opcodes.movb), new FormatOpRec("E,e", Opcodes.cmp), new FormatOpRec("E,e", Opcodes.bit), new FormatOpRec("E,e", Opcodes.bic), new FormatOpRec("E,e", Opcodes.bis), new FormatOpRec("w:E,e", Opcodes.sub), null, }; } private Pdp11Instruction Disassemble() { ushort opcode = rdr.ReadLeUInt16(); dataWidth = DataWidthFromSizeBit(opcode & 0x8000u); var decoder = decoders[(opcode >> 0x0C) & 0x00F]; if (decoder != null) return decoder.Decode(opcode, this); switch ((opcode >> 0x0C) & 0x007) { case 0: return NonDoubleOperandInstruction(opcode); case 7: switch ((opcode >> 0x09) & 7) { case 0: dataWidth = PrimitiveType.Word16; return new Pdp11Instruction { Opcode = Opcodes.mul, DataWidth = dataWidth, op1 = DecodeOperand(opcode), op2 = new RegisterOperand(arch.GetRegister((opcode >> 6) & 7)), }; case 1: dataWidth = PrimitiveType.Word16; return new Pdp11Instruction { Opcode = Opcodes.div, DataWidth = dataWidth, op1 = DecodeOperand(opcode), op2 = new RegisterOperand(arch.GetRegister((opcode >> 6) & 7)), }; case 2: dataWidth = PrimitiveType.Word16; return new Pdp11Instruction { Opcode = Opcodes.ash, DataWidth = dataWidth, op1 = DecodeOperand(opcode), op2 = new RegisterOperand(arch.GetRegister((opcode >> 6) & 7)), }; case 3: dataWidth = PrimitiveType.Word16; return new Pdp11Instruction { Opcode = Opcodes.ashc, DataWidth = dataWidth, op1 = DecodeOperand(opcode), op2 = new RegisterOperand(arch.GetRegister((opcode >> 6) & 7)), }; case 4: dataWidth = PrimitiveType.Word16; return new Pdp11Instruction { Opcode = Opcodes.xor, DataWidth = dataWidth, op1 = DecodeOperand(opcode), op2 = new RegisterOperand(arch.GetRegister((opcode >> 6) & 7)), }; case 5: return FpuArithmetic(opcode); case 7: dataWidth = PrimitiveType.Word16; return new Pdp11Instruction { Opcode = Opcodes.sob, DataWidth = dataWidth, op1 = Imm6(opcode), op2 = new RegisterOperand(arch.GetRegister((opcode >> 6) & 7)), }; } throw new NotSupportedException(); default: throw new NotSupportedException(); } throw new NotImplementedException(); } private MachineOperand Imm6(ushort opcode) { throw new NotImplementedException(); } private Pdp11Instruction FpuArithmetic(ushort opcode) { throw new NotImplementedException(); } private PrimitiveType DataWidthFromSizeBit(uint p) { return p != 0 ? PrimitiveType.Byte : PrimitiveType.Word16; } private Pdp11Instruction NonDoubleOperandInstruction(ushort opcode) { switch ((opcode >> 8)) { case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: return BranchInstruction(opcode); } var dataWidth = DataWidthFromSizeBit(opcode & 0x8000u); var op = DecodeOperand(opcode); Opcodes oc = Opcodes.illegal; switch ((opcode >> 6) & 0x3FF) { case 0x000: switch (opcode & 0x3F) { case 0x00: op= null;oc = Opcodes.halt; break; case 0x01: op= null;oc = Opcodes.wait; break; case 0x02: op= null;oc = Opcodes.rti; break; case 0x03: op= null;oc = Opcodes.bpt; break; case 0x04: op= null;oc = Opcodes.iot; break; case 0x05: op= null;oc = Opcodes.reset; break; case 0x06: op = null; oc = Opcodes.rtt; break; case 0x07: op = null; oc = Opcodes.illegal; break; } break; case 0x001: oc = Opcodes.jmp; break; case 0x002: switch (opcode & 0x38) { case 0: op = DecodeOperand(opcode & 7); oc = Opcodes.rts; break; case 3: op = Imm3(opcode); oc = Opcodes.spl; break; case 4: case 5: case 6: case 7: throw new NotImplementedException("Cond codes"); } break; case 0x003: oc = Opcodes.swab; dataWidth = PrimitiveType.Byte; break; case 0x020: case 0x021: case 0x022: case 0x023: case 0x024: case 0x025: case 0x026: case 0x027: return new Pdp11Instruction { Opcode = Opcodes.jsr, op1= Reg(opcode >> 6), op2 = op }; case 0x220: case 0x221: case 0x222: case 0x223: oc = Opcodes.emt; op = null; break; case 0x224: case 0x225: case 0x226: case 0x227: oc = Opcodes.trap; op = null; break; case 0x028: case 0x228: oc = dataWidth.Size == 1 ? Opcodes.clrb : Opcodes.clr; break; case 0x029: case 0x229: oc = Opcodes.com; break; case 0x02A: case 0x22A: oc = Opcodes.inc; break; case 0x02B: case 0x22B: oc = Opcodes.dec; break; case 0x02C: case 0x22C: oc = Opcodes.neg; break; case 0x02D: case 0x22D: oc = Opcodes.adc; break; case 0x02E: case 0x22E: oc = Opcodes.sbc; break; case 0x02F: case 0x22F: oc = Opcodes.tst; break; case 0x030: case 0x230: oc = Opcodes.ror; break; case 0x031: case 0x231: oc = Opcodes.rol; break; case 0x032: case 0x232: oc = Opcodes.asr; break; case 0x033: case 0x233: oc = Opcodes.asl; break; case 0x034: oc = Opcodes.mark; break; case 0x234: oc = Opcodes.mtps; break; case 0x035: oc = Opcodes.mfpi; break; case 0x235: oc = Opcodes.mfpd; break; case 0x036: oc = Opcodes.mtpi; break; case 0x236: oc = Opcodes.mtpd; break; case 0x037: oc = Opcodes.sxt; break; case 0x237: oc = Opcodes.mfps; break; } return new Pdp11Instruction { Opcode = oc, DataWidth = dataWidth, op1 = op, }; } private MachineOperand Reg(int bits) { return new RegisterOperand(arch.GetRegister(bits & 7)); } private MachineOperand Imm3(ushort opcode) { throw new NotImplementedException(); } private Pdp11Instruction BranchInstruction(ushort opcode) { var oc = Opcodes.illegal; switch ((opcode >> 8) | (opcode >> 15)) { case 1: oc = Opcodes.br; break; case 2: oc = Opcodes.bne; break; case 3: oc = Opcodes.beq; break; case 4: oc = Opcodes.bge; break; case 5: oc = Opcodes.blt; break; case 6: oc = Opcodes.bgt; break; case 7: oc = Opcodes.ble; break; case 8: oc = Opcodes.bpl; break; case 9: oc = Opcodes.bmi; break; case 0xA: oc = Opcodes.bhi; break; case 0xB: oc = Opcodes.blos; break; case 0xC: oc = Opcodes.bvc; break; case 0xD: oc = Opcodes.bvs; break; case 0xE: oc = Opcodes.bcc; break; case 0xF: oc = Opcodes.bcs; break; } return new Pdp11Instruction { Opcode = oc, DataWidth = PrimitiveType.Word16, op1 = new AddressOperand(rdr.Address + (sbyte)(opcode & 0xFF)), }; } private MachineOperand DecodeOperand(int operandBits) { var reg = arch.GetRegister(operandBits & 7); Debug.Print("operandBits {0:X} {1:X} ", (operandBits >> 3) & 7, operandBits & 7); if (reg == Registers.pc) { switch ((operandBits >> 3) & 7) { case 0: return new RegisterOperand(reg); case 1: return new MemoryOperand(AddressMode.RegDef, dataWidth, reg); case 2: return new ImmediateOperand(Constant.Word16(rdr.ReadLeUInt16())); case 3: return new MemoryOperand(rdr.ReadLeUInt16(), dataWidth); // PC relative } throw new NotImplementedException(); } else { switch ((operandBits >> 3) & 7) { case 0: return new RegisterOperand(reg); // Reg Direct addressing of the register case 1: return new MemoryOperand(AddressMode.RegDef, dataWidth, reg); // Reg Def Contents of Reg is the address case 2: return new MemoryOperand(AddressMode.AutoIncr, dataWidth, reg); // AutoIncr Contents of Reg is the address, then Reg incremented case 4: return new MemoryOperand(AddressMode.AutoDecr, dataWidth, reg); // AutoDecr Reg incremented, then contents of Reg is the address //case 3: // AutoIncrDef Content of Reg is addr of addr, then Reg Incremented //case 4: // AutoDecr Reg is decremented then contents is address //case 5: // AutoDecrDef Reg is decremented then contents is addr of addr case 6: return new MemoryOperand(AddressMode.Indexed, dataWidth, reg) { EffectiveAddress = rdr.ReadLeUInt16() }; //case 6: return new MemoryOperand(reg, rdr.ReadLeUInt16()); // Index Contents of Reg + Following word is address //case 7: // IndexDef Contents of Reg + Following word is addr of addr default: throw new NotSupportedException(string.Format("Address mode {0} not supported.", (operandBits >> 3) & 7)); } } } } }
MavenRain/reko
src/Arch/Pdp11/Pdp11Disassembler.cs
C#
gpl-2.0
16,871
<?php /** * Jetpack Compatibility File * See: http://jetpack.me/ * * @package Bose */ /** * Add theme support for Infinite Scroll. * See: http://jetpack.me/support/infinite-scroll/ */ function bose_jetpack_setup() { add_theme_support( 'infinite-scroll', array( 'container' => 'main', 'footer' => 'page', ) ); } add_action( 'after_setup_theme', 'bose_jetpack_setup' );
radision/cms_template
wp-content/themes/bose/inc/jetpack.php
PHP
gpl-2.0
386
# # Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/] # # This file is part of Outer Space. # # Outer Space 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. # # Outer Space 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 Outer Space; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # import gdata from dialog import ProgressDlg from dialog import PlayerSelectDlg import pygame from ige import log # module globals progressDlg = None def onInitConnection(): pass def onConnInitialized(): pass def onCmdBegin(): if gdata.mainGameDlg: gdata.mainGameDlg.onCmdInProgress(1) else: gdata.cmdInProgress = 1 gdata.app.update() def onCmdEnd(): if gdata.mainGameDlg: gdata.mainGameDlg.onCmdInProgress(0) else: gdata.cmdInProgress = 0 gdata.app.update() def onUpdateStarting(): global progressDlg log.debug("onUpdateStarting") if not progressDlg: progressDlg = ProgressDlg(gdata.app) progressDlg.display(_('Updating OSCI database...'), 0, 1) def onUpdateProgress(curr, max, text = None): global progressDlg log.debug("onUpdateProgress") progressDlg.setProgress(text, curr, max) def onUpdateFinished(): global progressDlg log.debug("onUpdateFinished") try: progressDlg.hide() except: log.warning("Cannot delete progressDlg window") for dialog in gdata.updateDlgs: dialog.update() def onNewMessages(number): gdata.mainGameDlg.messagesDlg.update() def onWaitingForResponse(): #pygame.event.pump() while pygame.event.poll().type != pygame.NOEVENT: pass
dahaic/outerspace
client/osci/handler.py
Python
gpl-2.0
2,143
using System; using System.Drawing; using System.Windows.Data; namespace PowerPointLabs.Converters.ColorPane { class SelectedColorToMonochromaticTwo : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var selectedColor = (HSLColor)value; Color convertedColor = new HSLColor(selectedColor.Hue, selectedColor.Saturation, 0.70f * 240); return Color.FromArgb(255, convertedColor.R, convertedColor.G, convertedColor.B); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
initialshl/PowerPointLabs
PowerPointLabs/PowerPointLabs/Converters/ColorPane/SelectedColorToMonochromaticTwo.cs
C#
gpl-2.0
823
<?php /* Author: Eddie Machado URL: htp://themble.com/bones/ This is where you can drop your custom functions or just edit things like thumbnail sizes, header images, sidebars, comments, ect. */ /************* INCLUDE NEEDED FILES ***************/ /* 1. library/bones.php - head cleanup (remove rsd, uri links, junk css, ect) - enqueueing scripts & styles - theme support functions - custom menu output & fallbacks - related post function - page-navi function - removing <p> from around images - customizing the post excerpt - custom google+ integration - adding custom fields to user profiles */ require_once( 'library/bones.php' ); // if you remove this, bones will break /* 2. library/custom-post-type.php - an example custom post type - example custom taxonomy (like categories) - example custom taxonomy (like tags) */ require_once( 'library/price-post-type.php' ); // you can disable this if you like require_once( 'library/social-post-type.php' ); require_once( 'library/sponsors-post-type.php' ); require_once( 'library/speakers-post-type.php' ); require_once( 'library/locations-post-type.php' ); require_once( 'library/workshops-post-type.php' ); require_once( 'library/sponsors-link-post-type.php' ); /* 3. library/admin.php - removing some default WordPress dashboard widgets - an example custom dashboard widget - adding custom login css - changing text in footer of admin */ // require_once( 'library/admin.php' ); // this comes turned off by default /* 4. library/translation/translation.php - adding support for other languages */ // require_once( 'library/translation/translation.php' ); // this comes turned off by default /************* THUMBNAIL SIZE OPTIONS *************/ // Thumbnail sizes add_image_size( 'bones-thumb-600', 600, 150, true ); add_image_size( 'bones-thumb-300', 300, 100, true ); /* to add more sizes, simply copy a line from above and change the dimensions & name. As long as you upload a "featured image" as large as the biggest set width or height, all the other sizes will be auto-cropped. To call a different size, simply change the text inside the thumbnail function. For example, to call the 300 x 300 sized image, we would use the function: <?php the_post_thumbnail( 'bones-thumb-300' ); ?> for the 600 x 100 image: <?php the_post_thumbnail( 'bones-thumb-600' ); ?> You can change the names and dimensions to whatever you like. Enjoy! */ add_filter( 'image_size_names_choose', 'bones_custom_image_sizes' ); function bones_custom_image_sizes( $sizes ) { return array_merge( $sizes, array( 'bones-thumb-600' => __('600px by 150px'), 'bones-thumb-300' => __('300px by 100px'), ) ); } /* The function above adds the ability to use the dropdown menu to select the new images sizes you have just created from within the media manager when you add media to your content blocks. If you add more image sizes, duplicate one of the lines in the array and name it according to your new image size. */ /************* ACTIVE SIDEBARS ********************/ // Sidebars & Widgetizes Areas function bones_register_sidebars() { register_sidebar(array( 'id' => 'sidebar1', 'name' => __( 'Sidebar 1', 'bonestheme' ), 'description' => __( 'The first (primary) sidebar.', 'bonestheme' ), 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h4 class="widgettitle">', 'after_title' => '</h4>', )); /* to add more sidebars or widgetized areas, just copy and edit the above sidebar code. In order to call your new sidebar just use the following code: Just change the name to whatever your new sidebar's id is, for example: register_sidebar(array( 'id' => 'sidebar2', 'name' => __( 'Sidebar 2', 'bonestheme' ), 'description' => __( 'The second (secondary) sidebar.', 'bonestheme' ), 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h4 class="widgettitle">', 'after_title' => '</h4>', )); To call the sidebar in your template, you can just copy the sidebar.php file and rename it to your sidebar's name. So using the above example, it would be: sidebar-sidebar2.php */ } // don't remove this bracket! /************* COMMENT LAYOUT *********************/ // Comment Layout function bones_comments( $comment, $args, $depth ) { $GLOBALS['comment'] = $comment; ?> <li <?php comment_class(); ?>> <article id="comment-<?php comment_ID(); ?>" class="clearfix"> <header class="comment-author vcard"> <?php /* this is the new responsive optimized comment image. It used the new HTML5 data-attribute to display comment gravatars on larger screens only. What this means is that on larger posts, mobile sites don't have a ton of requests for comment images. This makes load time incredibly fast! If you'd like to change it back, just replace it with the regular wordpress gravatar call: echo get_avatar($comment,$size='32',$default='<path_to_url>' ); */ ?> <?php // custom gravatar call ?> <?php // create variable $bgauthemail = get_comment_author_email(); ?> <img data-gravatar="http://www.gravatar.com/avatar/<?php echo md5( $bgauthemail ); ?>?s=32" class="load-gravatar avatar avatar-48 photo" height="32" width="32" src="<?php echo get_template_directory_uri(); ?>/library/images/nothing.gif" /> <?php // end custom gravatar call ?> <?php printf(__( '<cite class="fn">%s</cite>', 'bonestheme' ), get_comment_author_link()) ?> <time datetime="<?php echo comment_time('Y-m-j'); ?>"><a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ) ?>"><?php comment_time(__( 'F jS, Y', 'bonestheme' )); ?> </a></time> <?php edit_comment_link(__( '(Edit)', 'bonestheme' ),' ','') ?> </header> <?php if ($comment->comment_approved == '0') : ?> <div class="alert alert-info"> <p><?php _e( 'Your comment is awaiting moderation.', 'bonestheme' ) ?></p> </div> <?php endif; ?> <section class="comment_content clearfix"> <?php comment_text() ?> </section> <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?> </article> <?php // </li> is added by WordPress automatically ?> <?php } // don't remove this bracket! /************* SEARCH FORM LAYOUT *****************/ // Search Form function bones_wpsearch($form) { $form = '<form role="search" method="get" id="searchform" action="' . home_url( '/' ) . '" > <label class="screen-reader-text" for="s">' . __( 'Search for:', 'bonestheme' ) . '</label> <input type="text" value="' . get_search_query() . '" name="s" id="s" placeholder="' . esc_attr__( 'Search the Site...', 'bonestheme' ) . '" /> <input type="submit" id="searchsubmit" value="' . esc_attr__( 'Search' ) .'" /> </form>'; return $form; } // don't remove this bracket! function custom_excerpt_length( $length ) { return 20; } function themeslug_theme_customizer( $wp_customize ) { $wp_customize->add_section( 'themeslug_logo_section' , array( 'title' => __( 'Logo', 'themeslug' ), 'priority' => 30, 'description' => 'Upload a logo to replace the default site name and description in the header', )); $wp_customize->add_setting( 'themeslug_logo' ); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'themeslug_logo', array( 'label' => __( 'Logo', 'themeslug' ), 'section' => 'themeslug_logo_section', 'settings' => 'themeslug_logo', ))); } add_action('customize_register', 'themeslug_theme_customizer'); add_theme_support('custom-background'); ?>
mindtheproduct/2014
wp-content/themes/mtp2014/functions.php
PHP
gpl-2.0
7,646
<?php /******************************************************************************* Copyright 2009 Whole Foods Co-op This file is part of CORE-POS. CORE-POS 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. CORE-POS 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 IT CORE; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *********************************************************************************/ /* HELP nightly.seniordiscount.php Update custdata.discount on senior discount days. Customize this script with your store's discount day. This script must be run after midnight. This script does not update the lanes, therefore it should be run before lane syncing. */ // ************************************ // *** SETTINGS *** // ************************************ // Discount value is the percent * 100, e.g. 10 = 10% $discount_value = 10; // NOTE: Simply uncomment your desired senior discount day. // $discount_day = "Sunday"; // $discount_day = "Monday"; // $discount_day = "Tuesday"; $discount_day = "Wednesday"; // $discount_day = "Thursday"; // $discount_day = "Friday"; // $discount_day = "Saturday"; // ************************************ include(dirname(__FILE__) . '/../config.php'); if (!class_exists('FannieAPI')) { include(__DIR__ . '/../classlib2.0/FannieAPI.php'); } if (!function_exists('cron_msg')) { include(__DIR__ . '/../src/cron_msg.php'); } set_time_limit(0); $today = date('l'); $dday = date_create($discount_day); date_add($dday, date_interval_create_from_date_string('1 days')); $discount_day_after = date_format($dday, 'l'); $sql = new SQLManager($FANNIE_SERVER,$FANNIE_SERVER_DBMS,$FANNIE_OP_DB, $FANNIE_SERVER_USER,$FANNIE_SERVER_PW); $toggle = ($today == $discount_day) ? "+" : "-"; if (($today == $discount_day) || ($today == $discount_day_after)) { $sql->query("UPDATE custdata SET discount = (discount $toggle $discount_value) WHERE SSI = 1"); } else { echo cron_msg("nightly.seniordiscount.php: Discount active on " . $discount_day . ".<br /> No discounts to apply"); }
CORE-POS/IS4C
fannie/cron/nightly.seniordiscount.php
PHP
gpl-2.0
2,670
import fauxfactory import pytest from cfme import test_requirements from cfme.control.explorer.policies import VMControlPolicy from cfme.infrastructure.provider.virtualcenter import VMwareProvider from cfme.markers.env_markers.provider import ONE_PER_TYPE from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.blockers import BZ from cfme.utils.conf import credentials from cfme.utils.update import update from cfme.utils.wait import wait_for pytestmark = [ pytest.mark.ignore_stream("upstream"), pytest.mark.long_running, pytest.mark.provider([VMwareProvider], selector=ONE_PER_TYPE, scope="module"), test_requirements.ansible, ] @pytest.fixture(scope="function") def ansible_action(appliance, ansible_catalog_item): action_collection = appliance.collections.actions action = action_collection.create( fauxfactory.gen_alphanumeric(15, start="action_"), action_type="Run Ansible Playbook", action_values={ "run_ansible_playbook": {"playbook_catalog_item": ansible_catalog_item.name} }, ) yield action action.delete_if_exists() @pytest.fixture(scope="function") def policy_for_testing(appliance, create_vm, provider, ansible_action): policy = appliance.collections.policies.create( VMControlPolicy, fauxfactory.gen_alpha(15, start="policy_"), scope=f"fill_field(VM and Instance : Name, INCLUDES, {create_vm.name})", ) policy.assign_actions_to_event("Tag Complete", [ansible_action.description]) policy_profile = appliance.collections.policy_profiles.create( fauxfactory.gen_alpha(15, start="profile_"), policies=[policy] ) provider.assign_policy_profiles(policy_profile.description) yield if policy.exists: policy.unassign_events("Tag Complete") provider.unassign_policy_profiles(policy_profile.description) policy_profile.delete() policy.delete() @pytest.fixture(scope="module") def ansible_credential(wait_for_ansible, appliance, full_template_modscope): credential = appliance.collections.ansible_credentials.create( fauxfactory.gen_alpha(start="cred_"), "Machine", username=credentials[full_template_modscope.creds]["username"], password=credentials[full_template_modscope.creds]["password"], ) yield credential credential.delete_if_exists() @pytest.mark.tier(3) @pytest.mark.parametrize("create_vm", ["full_template"], indirect=True) def test_action_run_ansible_playbook_localhost( request, ansible_catalog_item, ansible_action, policy_for_testing, create_vm, ansible_credential, ansible_service_request, ansible_service, appliance, ): """Tests a policy with ansible playbook action against localhost. Polarion: assignee: gtalreja initialEstimate: 1/6h casecomponent: Ansible """ with update(ansible_action): ansible_action.run_ansible_playbook = {"inventory": {"localhost": True}} create_vm.add_tag() wait_for(ansible_service_request.exists, num_sec=600) ansible_service_request.wait_for_request() view = navigate_to(ansible_service, "Details") assert view.provisioning.details.get_text_of("Hosts") == "localhost" assert view.provisioning.results.get_text_of("Status") == "Finished" @pytest.mark.meta(blockers=[BZ(1822533, forced_streams=["5.11", "5.10"])]) @pytest.mark.tier(3) @pytest.mark.parametrize("create_vm", ["full_template"], indirect=True) def test_action_run_ansible_playbook_manual_address( request, ansible_catalog_item, ansible_action, policy_for_testing, create_vm, ansible_credential, ansible_service_request, ansible_service, appliance, ): """Tests a policy with ansible playbook action against manual address. Polarion: assignee: gtalreja initialEstimate: 1/6h casecomponent: Ansible """ with update(ansible_catalog_item): ansible_catalog_item.provisioning = {"machine_credential": ansible_credential.name} with update(ansible_action): ansible_action.run_ansible_playbook = { "inventory": {"specific_hosts": True, "hosts": create_vm.ip_address} } create_vm.add_tag() wait_for(ansible_service_request.exists, num_sec=600) ansible_service_request.wait_for_request() view = navigate_to(ansible_service, "Details") assert view.provisioning.details.get_text_of("Hosts") == create_vm.ip_address assert view.provisioning.results.get_text_of("Status") == "Finished" @pytest.mark.meta(blockers=[BZ(1822533, forced_streams=["5.11", "5.10"])]) @pytest.mark.tier(3) @pytest.mark.parametrize("create_vm", ["full_template"], indirect=True) def test_action_run_ansible_playbook_target_machine( request, ansible_catalog_item, ansible_action, policy_for_testing, create_vm, ansible_credential, ansible_service_request, ansible_service, appliance, ): """Tests a policy with ansible playbook action against target machine. Polarion: assignee: gtalreja initialEstimate: 1/6h casecomponent: Ansible """ with update(ansible_action): ansible_action.run_ansible_playbook = {"inventory": {"target_machine": True}} create_vm.add_tag() wait_for(ansible_service_request.exists, num_sec=600) ansible_service_request.wait_for_request() view = navigate_to(ansible_service, "Details") assert view.provisioning.details.get_text_of("Hosts") == create_vm.ip_address assert view.provisioning.results.get_text_of("Status") == "Finished" @pytest.mark.tier(3) @pytest.mark.parametrize("create_vm", ["full_template"], indirect=True) def test_action_run_ansible_playbook_unavailable_address( request, ansible_catalog_item, create_vm, ansible_action, policy_for_testing, ansible_credential, ansible_service_request, ansible_service, appliance, ): """Tests a policy with ansible playbook action against unavailable address. Polarion: assignee: gtalreja initialEstimate: 1/6h casecomponent: Ansible """ with update(ansible_catalog_item): ansible_catalog_item.provisioning = {"machine_credential": ansible_credential.name} with update(ansible_action): ansible_action.run_ansible_playbook = { "inventory": {"specific_hosts": True, "hosts": "unavailable_address"} } create_vm.add_tag() wait_for(ansible_service_request.exists, num_sec=600) ansible_service_request.wait_for_request() view = navigate_to(ansible_service, "Details") assert view.provisioning.details.get_text_of("Hosts") == "unavailable_address" assert view.provisioning.results.get_text_of("Status") == "Finished"
nachandr/cfme_tests
cfme/tests/ansible/test_embedded_ansible_actions.py
Python
gpl-2.0
6,825