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
/**************************************************************************** * MeshLab o o * * An extendible mesh processor o o * * _ O _ * * Copyright(C) 2005, 2009 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ /* A class implementing Meshlab's Edit interface that is for picking points in 3D * * * @author Oscar Barney */ #include <QtGui> #include <GL/glew.h> #include "editpickpoints.h" #include <meshlab/mainwindow.h> #include <wrap/gl/picking.h> #include <wrap/gl/pick.h> #include <wrap/qt/gl_label.h> #include <math.h> using namespace vcg; #define PI 3.14159265 EditPickPointsPlugin::EditPickPointsPlugin() { //initialize to false so we dont end up collection some weird point in the beginning registerPoint = false; moveSelectPoint = false; pickPointsDialog = 0; currentModel = 0; overrideCursorShape = 0; } //Constants const QString EditPickPointsPlugin::Info() { return tr("Pick and save 3D points on the mesh"); } //called void EditPickPointsPlugin::Decorate(MeshModel &mm, GLArea *gla, QPainter *painter) { //qDebug() << "Decorate " << mm.fileName.c_str() << " ..." << mm.cm.fn; if(gla != glArea || mm.cm.fn < 1) { //qDebug() << "GLarea is different or no faces!!! "; return; } //make sure we picking points on the right meshes! if(&mm != currentModel){ //now that were are ending tell the dialog to save any points it has to metadata pickPointsDialog->savePointsToMetaData(); //set the new mesh model pickPointsDialog->setCurrentMeshModel(&mm, gla); currentModel = &mm; } //We have to calculate the position here because it doesnt work in the mouseEvent functions for some reason Point3f pickedPoint; if (moveSelectPoint && Pick<Point3f>(currentMousePosition.x(),gla->height()-currentMousePosition.y(),pickedPoint)){ /* qDebug("Found point for move %i %i -> %f %f %f", currentMousePosition.x(), currentMousePosition.y(), pickedPoint[0], pickedPoint[1], pickedPoint[2]); */ //let the dialog know that this was the pointed picked incase it wants the information pickPointsDialog->selectOrMoveThisPoint(pickedPoint); moveSelectPoint = false; } else if(registerPoint && Pick<Point3f>(currentMousePosition.x(),gla->height()-currentMousePosition.y(),pickedPoint)) { /* qDebug("Found point for add %i %i -> %f %f %f", currentMousePosition.x(), currentMousePosition.y(), pickedPoint[0], pickedPoint[1], pickedPoint[2]); */ //find the normal of the face we just clicked CFaceO *face; bool result = GLPickTri<CMeshO>::PickNearestFace(currentMousePosition.x(),gla->height()-currentMousePosition.y(), mm.cm, face); if(!result){ qDebug() << "find nearest face failed!"; } else { CFaceO::NormalType faceNormal = face->N(); //qDebug() << "found face normal: " << faceNormal[0] << faceNormal[1] << faceNormal[2]; //if we didnt find a face then dont add the point because the user was probably //clicking on another mesh opened inside the glarea pickPointsDialog->addMoveSelectPoint(pickedPoint, faceNormal); } registerPoint = false; } drawPickedPoints(pickPointsDialog->getPickedPointTreeWidgetItemVector(), mm.cm.bbox, painter); } bool EditPickPointsPlugin::StartEdit(MeshModel &mm, GLArea *gla ) { //qDebug() << "StartEdit Pick Points: " << mm.fileName.c_str() << " ..." << mm.cm.fn; //if there are no faces then we cant do anything with this plugin if(mm.cm.fn < 1) { if(NULL != pickPointsDialog) { pickPointsDialog->hide(); } //show message QMessageBox::warning(gla->window(), "Edit Pick Points", "Sorry, this mesh has no faces on which picked points can sit.", QMessageBox::Ok, QMessageBox::Ok); return false; } //get the cursor QCursor *cursor = QApplication::overrideCursor(); if(cursor) overrideCursorShape = cursor->shape(); else overrideCursorShape = Qt::ArrowCursor; //set this so redraw can use it glArea = gla; //Create GUI window if we dont already have one if(pickPointsDialog == 0) { pickPointsDialog = new PickPointsDialog(this, gla->window()); } currentModel = &mm; //set the current mesh pickPointsDialog->setCurrentMeshModel(&mm, gla); //show the dialog pickPointsDialog->show(); return true; } void EditPickPointsPlugin::EndEdit(MeshModel &mm, GLArea *gla) { //qDebug() << "EndEdit Pick Points: " << mm.fileName.c_str() << " ..." << mm.cm.fn; // some cleaning at the end. if(mm.cm.fn > 0) { assert(pickPointsDialog); //now that were are ending tell the dialog to save any points it has to metadata pickPointsDialog->savePointsToMetaData(); //remove the dialog from the screen pickPointsDialog->hide(); QApplication::setOverrideCursor( QCursor((Qt::CursorShape)overrideCursorShape) ); this->glArea = 0; } } void EditPickPointsPlugin::mousePressEvent(QMouseEvent *event, MeshModel &mm, GLArea *gla ) { //qDebug() << "mouse press Pick Points: " << mm.fileName.c_str() << " ..."; //if there are no faces then we cant do anything with this plugin if(mm.cm.fn < 1) return; if(Qt::LeftButton | event->buttons()) { gla->suspendedEditor = true; QCoreApplication::sendEvent(gla, event); gla->suspendedEditor = false; } if(Qt::RightButton == event->button() && pickPointsDialog->getMode() != PickPointsDialog::ADD_POINT){ currentMousePosition = event->pos(); pickPointsDialog->recordNextPointForUndo(); //set flag that we need to add a new point moveSelectPoint = true; } } void EditPickPointsPlugin::mouseMoveEvent(QMouseEvent *event, MeshModel &mm, GLArea *gla ) { //qDebug() << "mousemove pick Points: " << mm.fileName.c_str() << " ..."; //if there are no faces then we cant do anything with this plugin if(mm.cm.fn < 1) return; if(Qt::LeftButton | event->buttons()) { gla->suspendedEditor = true; QCoreApplication::sendEvent(gla, event); gla->suspendedEditor = false; } if(Qt::RightButton & event->buttons() && pickPointsDialog->getMode() != PickPointsDialog::ADD_POINT){ //qDebug() << "mouse move left button and move mode: "; currentMousePosition = event->pos(); //set flag that we need to add a new point registerPoint = true; } } void EditPickPointsPlugin::mouseReleaseEvent(QMouseEvent *event, MeshModel &mm, GLArea * gla) { //qDebug() << "mouseRelease Pick Points: " << mm.fileName.c_str() << " ..."; //if there are no faces then we cant do anything with this plugin if(mm.cm.fn < 1) return; if(Qt::LeftButton | event->buttons()) { gla->suspendedEditor = true; QCoreApplication::sendEvent(gla, event); gla->suspendedEditor = false; } //only add points for the left button if(Qt::RightButton == event->button()){ currentMousePosition = event->pos(); //set flag that we need to add a new point registerPoint = true; } } void EditPickPointsPlugin::drawPickedPoints( std::vector<PickedPointTreeWidgetItem*> &pointVector, vcg::Box3f &boundingBox, QPainter *painter) { assert(glArea); vcg::Point3f size = boundingBox.Dim(); //how we scale the object indicating the normal at each selected point float scaleFactor = (size[0]+size[1]+size[2])/90.0; //qDebug() << "scaleFactor: " << scaleFactor; glPushAttrib(GL_ALL_ATTRIB_BITS); // enable color tracking glEnable(GL_COLOR_MATERIAL); //draw the things that we always want to show, like the names glDepthFunc(GL_ALWAYS); glDisable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); //set point attributes glPointSize(4.5); bool showNormal = pickPointsDialog->showNormal(); bool showPin = pickPointsDialog->drawNormalAsPin(); for(int i = 0; i < pointVector.size(); ++i) { PickedPointTreeWidgetItem * item = pointVector[i]; //if the point has been set (it may not be if a template has been loaded) if(item->isActive()){ Point3f point = item->getPoint(); glColor(Color4b::Blue); glLabel::render(painter,point, QString(item->getName())); //draw the dot if we arnt showing the normal or showing the normal as a line if(!showNormal || !showPin) { if(item->isSelected() ) glColor(Color4b::Green); glBegin(GL_POINTS); glVertex(point); glEnd(); } } } //now draw the things that we want drawn if they are not ocluded //we can see in bright red glDepthFunc(GL_LESS); glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glMatrixMode(GL_MODELVIEW); Point3f yaxis; yaxis[0] = 0; yaxis[1] = 1; yaxis[2] = 0; for(int i = 0; i < pointVector.size(); ++i) { PickedPointTreeWidgetItem * item = pointVector[i]; //if the point has been set (it may not be if a template has been loaded) if(item->isActive()){ Point3f point = item->getPoint(); if(showNormal) { Point3f normal = item->getNormal(); if(showPin) { //dot product float angle = (Angle(normal,yaxis) * 180.0 / PI); //cross product Point3f axis = yaxis^normal; //qDebug() << "angle: " << angle << " x" << axis[0] << " y" << axis[1] << " z" << axis[2]; //bluegreen and a little clear glColor4f(0.0f, 1.0f, 0.0f, 0.7f); //glColor(Color4b::Green); glPushMatrix(); //move the pin to where it needs to be glTranslatef(point[0], point[1], point[2]); glRotatef(angle, axis[0], axis[1], axis[2]); glScalef(0.2*scaleFactor, 1.5*scaleFactor, 0.2*scaleFactor); glBegin(GL_TRIANGLES); //front glNormal3f(0, -1, 1); glVertex3f(0,0,0); glVertex3f(1,1,1); glVertex3f(-1,1,1); //right glNormal3f(1, -1, 0); glVertex3f(0,0,0); glVertex3f(1,1,-1); glVertex3f(1,1,1); //left glNormal3f(-1, -1, 0); glVertex3f(0,0,0); glVertex3f(-1,1,1); glVertex3f(-1,1,-1); //back glNormal3f(0, -1, -1); glVertex3f(0,0,0); glVertex3f(-1,1,-1); glVertex3f(1,1,-1); //top //if it is selected color it green if(item->isSelected() ) glColor4f(0.0f, 0.0f, 1.0f, 0.7f); glNormal3f(0, 1, 0); glVertex3f(1,1,1); glVertex3f(1,1,-1); glVertex3f(-1,1,-1); glNormal3f(0, 1, 0); glVertex3f(1,1,1); glVertex3f(-1,1,-1); glVertex3f(-1,1,1); //change back if(item->isSelected() ) glColor4f(0.0f, 1.0f, 0.0f, 0.7f); glEnd(); glPopMatrix(); } else { glColor(Color4b::Green); glBegin(GL_LINES); glVertex(point); glVertex(point+(normal*scaleFactor)); glEnd(); } } glColor(Color4b::Red); glArea->renderText(point[0], point[1], point[2], QString(item->getName()) ); } } glDisable(GL_BLEND); glDisable(GL_COLOR_MATERIAL); glDisable(GL_DEPTH_TEST); glPopAttrib(); }
guerrerocarlos/meshlab
src/plugins/edit_pickpoints/editpickpoints.cpp
C++
gpl-2.0
12,813
""" AUTHOR: Dr. Andrew David Burbanks, 2005. This software is Copyright (C) 2004-2008 Bristol University and is released under the GNU General Public License version 2. MODULE: SystemBath PURPOSE: Used to generate System Bath Hamiltonian, given number of bath modes. NOTES: The system defined by the Hamiltonian is (2n+2)-dimensional, and is ordered (s, p_s, x, p_x, y, p_y, ...). There is no need for Taylor expansion, as we have the Hamiltonian in explicit polynomial form. """ from math import * from random import * from Polynomial import * from LieAlgebra import LieAlgebra class SystemBath: """ The original (_not_ mass-weighted) system bath. The system-bath model represents a 'system' part: a symmetric quartic double-well potential, coupled to a number of 'bath modes': harmonic oscillators. The coupling is achieved via a bilinear coupling between the configuration space coordinate of the system and the conjugate momenta of each of the bath modes. The resulting Hamiltonian is a polynomial of degree 4 in the phase space coordinates. With this version, the client must specify all of the following:- @param n_bath_modes: (non-negative int). @param system_mass: (positive real). @param imag_harmonic_frequency_at_barrier: (real; imag part of pure imag). @param reciprocal_barrier_height_above_well_bottom: (positive real). @param bath_masses: (seq of n_bath_modes positive reals). @param bath_frequencies: (seq of n_bath_modes reals). @param bath_coupling_constants: (seq of n_bath_modes reals). """ def __init__(self, n_bath_modes, system_mass, imag_harmonic_frequency_at_barrier, reciprocal_barrier_height_above_well_bottom, bath_masses, bath_frequencies, bath_coupling_constants): assert n_bath_modes>=0 assert system_mass >= 0.0 assert abs(imag_harmonic_frequency_at_barrier) > 0.0 assert reciprocal_barrier_height_above_well_bottom >= 0.0 assert len(bath_masses) == n_bath_modes assert len(bath_frequencies) == n_bath_modes assert len(bath_coupling_constants) == n_bath_modes for f, g in zip(bath_frequencies[:-1], bath_frequencies[1:]): assert f < g self._m_s = system_mass #system mass self._omega_b = imag_harmonic_frequency_at_barrier self._v_0_sh = reciprocal_barrier_height_above_well_bottom self._n = n_bath_modes self._c = bath_coupling_constants #to the system s coordinate. self._w = bath_frequencies self._m = bath_masses self._lie = LieAlgebra(n_bath_modes+1) #$a = (-1/2)m_s\omega_b^2.$ self._a = -0.5*self._m_s*(self._omega_b**2) #$b = \frac{m_s^2\omega_b^4}{16V_0}.$ self._b = ((self._m_s**2) * (self._omega_b**4))/(16.0*self._v_0_sh) def lie_algebra(self): """ Return the Lie algebra on which the polynomials will be constructed. For N bath modes, this has (N+1)-dof. """ return self._lie def hamiltonian_real(self): """ Calculate the real Hamiltonian for the system-bath model. """ #Establish some convenient notation: n = self._n a = self._a b = self._b m_s = self._m_s c = self._c w = self._w m = self._m q_s = self._lie.q(0) p_s = self._lie.p(0) #Compute some constants: coeff_q_s = a for i in xrange(0, len(c)): coeff_q_s += (c[i]**2.0)/(2.0 * m[i] * (w[i]**2.0)) coeff_p_s = 1.0/(2.0 * m_s) coeff_q_bath = [] coeff_p_bath = [] for i in xrange(0, len(c)): coeff_q_bath.append(0.5 * m[i] * (w[i]**2.0)) coeff_p_bath.append(1.0/(2.0 * m[i])) #Sanity checks: assert n >= 0, 'Need zero or more bath modes.' assert len(c) == n, 'Need a coupling constant for each bath mode.' assert len(coeff_q_bath) == n, 'Need constant for each bath config.' assert len(coeff_p_bath) == n, 'Need constant for each bath momentum.' #System part: h_system = coeff_p_s * (p_s**2) h_system += coeff_q_s * (q_s**2) h_system += b * (q_s**4) #Bath part: h_bath = self._lie.zero() for i in xrange(len(c)): bath_dof = i+1 h_bath += coeff_q_bath[i] * (self._lie.q(bath_dof)**2) h_bath += coeff_p_bath[i] * (self._lie.p(bath_dof)**2) #Coupling part: h_coupling = self._lie.zero() for i, c_i in enumerate(c): bath_dof = i+1 h_coupling += -c_i * (self._lie.q(bath_dof) * q_s) #Complete Hamiltonian: h = h_system + h_bath + h_coupling #Sanity checks: assert h.degree() == 4 assert h.n_vars() == 2*n+2 assert len(h) == (3) + (2*n) + (n) #system+bath+coupling return h class MassWeightedSystemBath: """ The system-bath model represents a 'system' part (a symmetric quartic double-well potential) coupled to a number of 'bath modes' (harmonic oscillators). The coupling is achieved via a bilinear coupling between the configuration space coordinate of the system and the conjugate momenta of each of the bath modes. The resulting Hamiltonian is a polynomial of degree 4 in the phase space coordinates. """ def __init__(self, n_bath_modes, imag_harmonic_frequency_at_barrier, reciprocal_barrier_height_above_well_bottom, damping_strength, bath_cutoff_frequency, bath_masses, bath_frequencies, bath_compound_coupling_constants): """ Construct a mass-weighted system bath given the values of the parameters and the compound coupling constants. @param n_bath_modes: (non-negative int). @param imag_harmonic_frequency_at_barrier: (real; im part of pure im). @param reciprocal_barrier_height_above_well_bottom: (positive real). @param damping_strength: (real). @param bath_cutoff_frequency: (real, <<bath_frequencies[-1]). @param bath_masses: (seq of n_bath_modes positive reals). @param bath_frequencies: (increasing seq of n_bath_modes reals). @param bath_compound_coupling_constants: (seq of n_bath_modes reals). """ #check inputs assert n_bath_modes>=0 assert abs(imag_harmonic_frequency_at_barrier) > 0.0 assert reciprocal_barrier_height_above_well_bottom >= 0.0 assert len(bath_masses) == n_bath_modes assert len(bath_frequencies) == n_bath_modes assert len(bath_compound_coupling_constants) == n_bath_modes #ensure that the bath frequencies are increasing for f, g in zip(bath_frequencies[:-1], bath_frequencies[1:]): assert f < g #store member variables self._n = n_bath_modes self._omega_b = imag_harmonic_frequency_at_barrier self._v_0_sh = reciprocal_barrier_height_above_well_bottom self._eta = damping_strength self._omega_c = bath_cutoff_frequency self._c_star = bath_compound_coupling_constants #to system coord self._w = bath_omegas self._lie = LieAlgebra(n_bath_modes+1) def compute_compound_constants(n_bath_modes, damping_strength, bath_cutoff_frequency, bath_frequencies): """ Compute the compound coupling constants. @param n_bath_modes: (non-negative int). @param damping_strength: (real). @param bath_cutoff_frequency: (real, <<bath_frequencies[-1]). @param bath_frequencies: (seq of n_bath_modes reals increasing). @return: bath_compound_coupling_constants (seq of n_bath_modes reals). """ #check inputs assert n_bath_modes>=0 assert len(bath_frequencies) == n_bath_modes for f, g in zip(bath_frequencies[:-1], bath_frequencies[1:]): assert f < g assert bath_frequencies[-1] > bath_cutoff_frequency #accumulate compound frequencies c_star = [] omega_c = bath_cutoff_frequency eta = damping_strength for jm1, omega_j in enumerate(bath_frequencies): c = (-2.0/(pi*(jm1+1.0)))*eta*omega_c d = ((omega_j+omega_c)*exp(-omega_j/omega_c) - omega_c) c_star.append(c*d) return c_star compute_compound_constants = staticmethod(compute_compound_constants) def bath_spectral_density_function(self, omega): """ The bath is defined in terms of a continuous spectral density function, which has the Ohmic form with an exponential cutoff. For infinite bath cutoff frequency, $\omega_c$, the bath is strictly Ohmic, i.e., the friction kernel becomes a delta function in the time domain, and the classical dynamics of the system coordinate are described by the ordinary Langevin equation. In that case, $eta$ (the damping strength) is the classically measurable friction coefficient. However, for finite values of the bath cutoff frequency, the friction kernel is nonlocal, which introduces memory effects into the Generalized Langevin Equation (GLE). """ return self.eta * omega * exp(-omega/self._omega_c) def hamiltonian_real(self): """ Calculate the real Hamiltonian for the system-bath model. """ #establish some convenient notation: n = self._n w = self._w c_star = self._c_star #sanity checks: assert n >= 0, 'Need zero or more bath modes.' assert len(c_star) == n, 'Need a coupling constant for each bath mode.' #system coefficients: a = -0.5*(self._omega_b**2) b = (self._omega_b**4)/(16.0*self._v_0_sh) coeff_q_s = a for i in xrange(0, len(c_star)): coeff_q_s += c_star[i]/(2.0 * (w[i])) coeff_p_s = 1.0/2.0 #system part: q_s = self._lie.q(0) p_s = self._lie.p(0) h_system = coeff_p_s * (p_s**2) h_system += coeff_q_s * (q_s**2) h_system += b * (q_s**4) #bath coefficients: coeff_q_bath = [] coeff_p_bath = [] for i in xrange(0, len(c_star)): coeff_q_bath.append(0.5 * (w[i]**2.0)) coeff_p_bath.append(1.0/2.0) #sanity checks: assert len(coeff_q_bath) == n, 'Need constant for each bath config.' assert len(coeff_p_bath) == n, 'Need constant for each bath momentum.' #bath part: h_bath = self._lie.zero() for i in xrange(len(c_star)): bath_dof = i+1 h_bath += coeff_q_bath[i] * (self._lie.q(bath_dof)**2) h_bath += coeff_p_bath[i] * (self._lie.p(bath_dof)**2) #coupling part: h_coupling = self._lie.zero() for i, c_i in enumerate(c_star): bath_dof = i+1 h_coupling += -sqrt(c_i*w[i]) * (self._lie.q(bath_dof)*q_s) #complete Hamiltonian: h = h_system + h_bath + h_coupling #sanity checks: assert h.degree() == 4 assert h.n_vars() == 2*n+2 assert len(h) == (3) + (2*n) + (n) #system+bath+coupling return h def new_random_system_bath(n_bath_modes, system_mass, imag_harmonic_frequency_at_barrier, reciprocal_barrier_height_above_well_bottom, random_seed): #check inputs assert n_bath_modes >= 0 assert system_mass >= 0.0 #unitialize random number generator seed(random_seed) #generate parameters bath_masses = [] bath_omegas = [] bath_coupling_constants = [] for i in xrange(0, n_bath_modes): bath_coupling_constants.append(uniform(0.001, 0.5)) bath_masses.append(uniform(0.5, 3.6)) bath_omegas.append(gauss(0.0, 2.0)) #sort frequencies into increasing order bath_omegas.sort() #instantiate the system bath sb = SystemBath(n_bath_modes, system_mass, imag_harmonic_frequency_at_barrier, reciprocal_barrier_height_above_well_bottom, bath_masses, bath_omegas, bath_coupling_constants) return sb
Peter-Collins/NormalForm
src/py/SystemBath.py
Python
gpl-2.0
12,748
package by.falc0n.util; /** * Contains a set of extension methods and constants to operate with arrays * (primitive and object). * * @author falc0n * @version 1.0 * */ public final class ArrayExt { /** * An empty {@code byte} array. * * @since 1.0 */ public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /** * An empty {@code short} array. * * @since 1.0 */ public static final short[] EMPTY_SHORT_ARRAY = new short[0]; /** * An empty {@code int} array. * * @since 1.0 */ public static final int[] EMPTY_INT_ARRAY = new int[0]; /** * An empty {@code long} array. * * @since 1.0 */ public static final long[] EMPTY_LONG_ARRAY = new long[0]; /** * An empty {@code float} array. * * @since 1.0 */ public static final float[] EMPTY_FLOAT_ARRAY = new float[0]; /** * An empty {@code double} array. * * @since 1.0 */ public static final double[] EMPTY_DOUBLE_ARRAY = new double[0]; /** * An empty {@code char} array. * * @since 1.0 */ public static final char[] EMPTY_CHAR_ARRAY = new char[0]; /** * An empty {@code boolean} array. * * @since 1.0 */ public static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0]; /** * An empty {@link Byte} array. * * @since 1.0 */ public static final Byte[] EMPTY_BYTE_OBJECT_ARRAY = new Byte[0]; /** * An empty {@link Short} array. * * @since 1.0 */ public static final Short[] EMPTY_SHORT_OBJECT_ARRAY = new Short[0]; /** * An empty {@link Integer} array. * * @since 1.0 */ public static final Integer[] EMPTY_INT_OBJECT_ARRAY = new Integer[0]; /** * An empty {@link Long} array. * * @since 1.0 */ public static final Long[] EMPTY_LONG_OBJECT_ARRAY = new Long[0]; /** * An empty {@link Float} array. * * @since 1.0 */ public static final Float[] EMPTY_FLOAT_OBJECT_ARRAY = new Float[0]; /** * An empty {@link Double} array. * * @since 1.0 */ public static final Double[] EMPTY_DOUBLE_OBJECT_ARRAY = new Double[0]; /** * An empty {@link Character} array. * * @since 1.0 */ public static final Character[] EMPTY_CHAR_OBJECT_ARRAY = new Character[0]; /** * An empty {@link Boolean} array. * * @since 1.0 */ public static final Boolean[] EMPTY_BOOLEAN_OBJECT_ARRAY = new Boolean[0]; /** * An empty object array. * * @since 1.0 */ public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0]; /** * Checks whether the {@code byte} array contains the specified value. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(byte[] array, byte value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the {@code short} array contains the specified value. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(short[] array, short value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the {@code int} array contains the specified value. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(int[] array, int value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the {@code long} array contains the specified value. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(long[] array, long value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the {@code float} array contains the specified value. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(float[] array, float value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the {@code double} array contains the specified value. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(double[] array, double value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the {@code char} array contains the specified value. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(char[] array, char value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the {@code boolean} array contains the specified value. * The array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(boolean[] array, boolean value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (value == array[i]) { result = true; break; } } return result; } /** * Checks whether the object array contains the specified value. "Contains" * means that the array has an element which equals (see * {@link #equals(Object)} ) to the value or they're both {@code null}. The * array shouldn't be {@code null}. * * @param array * - an array to check * @param value * - a value to search for * @return {@code true} - if the array contains the value; {@code false} - * otherwise * * @since 1.0 */ public static final boolean contains(Object[] array, Object value) { boolean result = false; for (int i = 0; i < array.length; i++) { if (ObjectExt.equalOrNull(array[i], value)) { result = true; break; } } return result; } /** * Converts the {@code byte} array to an array of corresponding objects. If * the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Byte[] toObjectArray(byte[] array) { Byte[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Byte[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_BYTE_OBJECT_ARRAY; } } return objArray; } /** * Converts the {@code short} array to an array of corresponding objects. If * the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Short[] toObjectArray(short[] array) { Short[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Short[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_SHORT_OBJECT_ARRAY; } } return objArray; } /** * Converts the {@code int} array to an array of corresponding objects. If * the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Integer[] toObjectArray(int[] array) { Integer[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Integer[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_INT_OBJECT_ARRAY; } } return objArray; } /** * Converts the {@code long} array to an array of corresponding objects. If * the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Long[] toObjectArray(long[] array) { Long[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Long[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_LONG_OBJECT_ARRAY; } } return objArray; } /** * Converts the {@code float} array to an array of corresponding objects. If * the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Float[] toObjectArray(float[] array) { Float[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Float[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_FLOAT_OBJECT_ARRAY; } } return objArray; } /** * Converts the {@code double} array to an array of corresponding objects. * If the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Double[] toObjectArray(double[] array) { Double[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Double[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_DOUBLE_OBJECT_ARRAY; } } return objArray; } /** * Converts the {@code char} array to an array of corresponding objects. If * the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Character[] toObjectArray(char[] array) { Character[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Character[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_CHAR_OBJECT_ARRAY; } } return objArray; } /** * Converts the {@code boolean} array to an array of corresponding objects. * If the input array is {@code null}, then {@code null} will be returned. * * @param array * - an array to convert * @return an array of objects or {@code null} * * @since 1.0 */ public static final Boolean[] toObjectArray(boolean[] array) { Boolean[] objArray = null; if (array != null) { if (array.length > 0) { objArray = new Boolean[array.length]; for (int i = 0; i < array.length; i++) { objArray[i] = array[i]; } } else { objArray = EMPTY_BOOLEAN_OBJECT_ARRAY; } } return objArray; } public static final byte[] toPrimitiveArray(Byte[] array) { byte[] primArray = null; if (array != null) { if (array.length > 0) { primArray = new byte[array.length]; for (int i = 0; i < array.length; i++) { primArray[i] = array[i]; } } else { primArray = EMPTY_BYTE_ARRAY; } } return primArray; } public static final byte[] toPrimitiveArray(Byte[] array, byte nullValue) { byte[] primArray = null; if (array != null) { if (array.length > 0) { primArray = new byte[array.length]; for (int i = 0; i < array.length; i++) { primArray[i] = (array[i] != null) ? array[i] : nullValue; } } else { primArray = EMPTY_BYTE_ARRAY; } } return primArray; } private ArrayExt() { super(); } }
fa1con/falc0n-utils
src/main/java/by/falc0n/util/ArrayExt.java
Java
gpl-2.0
13,659
<?php /** * @package CrowdfundingPartners * @subpackage Files * @author Todor Iliev * @copyright Copyright (C) 2015 Todor Iliev <todor@itprism.com>. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL */ namespace CrowdfundingPartners; use Prism\Database\ArrayObject; use Joomla\Utilities\ArrayHelper; defined('JPATH_PLATFORM') or die; /** * This class provides functionality that manage partners. * * @package CrowdfundingPartners * @subpackage Parnters */ class Partners extends ArrayObject { /** * Load partners data by ID from database. * * <code> * $ids = array(1,2,3,4,5); * * $partners = new CrowdfundingPartners\Partners(JFactory::getDbo()); * $partners->load($ids); * * foreach($partners as $partner) { * echo $partners["name"]; * echo $partners["partner_id"]; * } * </code> * * @param int $projectId * @param array $ids */ public function load($projectId = 0, $ids = array()) { // Load project data $query = $this->db->getQuery(true); $query ->select("a.id, a.name, a.project_id, a.partner_id") ->from($this->db->quoteName("#__cfpartners_partners", "a")); if (!empty($ids)) { ArrayHelper::toInteger($ids); $query->where("a.id IN ( " . implode(",", $ids) . " )"); } if (!empty($projectId)) { $query->where("a.project_id = " . (int)$projectId); } $this->db->setQuery($query); $results = $this->db->loadAssocList(); if (!$results) { $results = array(); } $this->items = $results; } /** * Add a new value to the array. * * <code> * $partner = array( * "name" => "John Dow", * "project_id" => 1, * "partner_id" => 2 * ); * * $partners = new CrowdfundingPartners\Partners(); * $partners->add($partner); * </code> * * @param array $value * @param null|int $index * * @return $this */ public function add($value, $index = null) { if (!is_null($index)) { $this->items[$index] = $value; } else { $this->items[] = $value; } return $this; } }
Creativetech-Solutions/joomla-easysocial-network
libraries/CrowdfundingPartners/Partners.php
PHP
gpl-2.0
2,368
<?php get_header(); ?> <div id="content" class="clearfix row"> <div class="row centered"> <div class="brandhead"> <h1 class="">News and Articles</h1> <p class="lead">A partnership to deliver high quality, efficient patient care for South Yorkshire, Mid Yorkshire and North Derbyshire</p> </div> </div> <div id="main" class="col-sm-8 clearfix" role="main"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class('clearfix'); ?> role="article"> <header> <a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail( 'wpbs-featured' ); ?></a> <div class="article-header"><h1 class="h2"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h1></div> <p class="meta"><?php _e("Posted", "wpbootstrap"); ?> <time datetime="<?php echo the_time('Y-m-j'); ?>" pubdate><?php the_time(); ?></time> <?php _e("by", "wpbootstrap"); ?> <?php the_author_posts_link(); ?> <span class="amp">&</span> <?php _e("filed under", "wpbootstrap"); ?> <?php the_category(', '); ?>.</p> </header> <!-- end article header --> <section class="post_content clearfix"> <?php the_content( __("Read more &raquo;","wpbootstrap") ); ?> </section> <!-- end article section --> <footer> <p class="tags"><?php the_tags('<span class="tags-title">' . __("Tags","wpbootstrap") . ':</span> ', ' ', ''); ?></p> </footer> <!-- end article footer --> </article> <!-- end article --> <?php endwhile; ?> <?php if (function_exists('page_navi')) { // if expirimental feature is active ?> <?php page_navi(); // use the page navi function ?> <?php } else { // if it is disabled, display regular wp prev & next links ?> <nav class="wp-prev-next"> <ul class="pager"> <li class="previous"><?php next_posts_link(_e('&laquo; Older Entries', "wpbootstrap")) ?></li> <li class="next"><?php previous_posts_link(_e('Newer Entries &raquo;', "wpbootstrap")) ?></li> </ul> </nav> <?php } ?> <?php else : ?> <article id="post-not-found"> <header> <h1><?php _e("Not Found", "wpbootstrap"); ?></h1> </header> <section class="post_content"> <p><?php _e("Sorry, but the requested resource was not found on this site.", "wpbootstrap"); ?></p> </section> <footer> </footer> </article> <?php endif; ?> </div> <!-- end #main --> <?php get_sidebar(); // sidebar 1 ?> </div> <!-- end #content --> <?php get_footer(); ?>
gitpress/together
wp-content/themes/wordpress-bootstrap-master/index.php
PHP
gpl-2.0
2,891
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\IFD0; use PHPExiftool\Driver\AbstractTag; class Copyright extends AbstractTag { protected $Id = 33432; protected $Name = 'Copyright'; protected $FullName = 'Exif::Main'; protected $GroupName = 'IFD0'; protected $g0 = 'EXIF'; protected $g1 = 'IFD0'; protected $g2 = 'Image'; protected $Type = 'string'; protected $Writable = true; protected $Description = 'Copyright'; protected $local_g2 = 'Author'; }
Droces/casabio
vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/IFD0/Copyright.php
PHP
gpl-2.0
724
<?php /** * The template for displaying search results pages. * * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result * * @package Brushy Hill Cottage */ get_header(); ?> <section id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php if ( have_posts() ) : ?> <header class="page-header"> <h1 class="page-title"><?php printf( esc_html__( 'Search Results for: %s', 'brushy-hill-cottage' ), '<span>' . get_search_query() . '</span>' ); ?></h1> </header><!-- .page-header --> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php /** * Run the loop for the search to output the results. * If you want to overload this in a child theme then include a file * called content-search.php and that will be used instead. */ get_template_part( 'template-parts/content', 'search' ); ?> <?php endwhile; ?> <?php the_posts_navigation(); ?> <?php else : ?> <?php get_template_part( 'template-parts/content', 'none' ); ?> <?php endif; ?> </main><!-- #main --> </section><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
bpriddy/brushyhillcottage
wp-content/themes/brushy-hill-cottage/search.php
PHP
gpl-2.0
1,206
package com.badday.ss.blocks; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.world.World; import com.badday.ss.SS; import com.badday.ss.SSConfig; import com.badday.ss.api.IGasNetwork; import com.badday.ss.api.IGasNetworkElement; import com.badday.ss.api.IGasNetworkVent; import com.badday.ss.core.atmos.GasUtils; import com.badday.ss.core.utils.BlockVec3; import com.badday.ss.events.RebuildNetworkPoint; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; /** * * @author KolesnikovAK * * Seal gases on bay * */ public class SSBlockAirVent extends BlockContainer implements IGasNetworkElement { private IIcon[] iconBuffer; //private int ICON_INACTIVE_SIDE = 0, ICON_BOTTOM = 1, ICON_SIDE_ACTIVATED = 2; private int ICON_SIDE = 0, ICON_SIDE_FRONT = 1, ICON_SIDE_BACK = 2, ICON_SIDE_FRONTON=3; public SSBlockAirVent(String assetName) { super(Material.rock); this.setResistance(1000.0F); this.setHardness(330.0F); this.setBlockTextureName(SS.ASSET_PREFIX + assetName); this.setBlockName(assetName); this.setBlockUnbreakable(); this.setStepSound(soundTypeMetal); this.setCreativeTab(SS.ssTab); disableStats(); } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister par1IconRegister) { iconBuffer = new IIcon[4]; //iconBuffer[ICON_INACTIVE_SIDE] = par1IconRegister.registerIcon("ss:airgenSideInactive"); //iconBuffer[ICON_BOTTOM] = par1IconRegister.registerIcon("ss:contBottom"); //iconBuffer[ICON_SIDE_ACTIVATED] = par1IconRegister.registerIcon("ss:airgenSideActive"); iconBuffer[ICON_SIDE] = par1IconRegister.registerIcon("ss:blockGasVentSide"); iconBuffer[ICON_SIDE_FRONT] = par1IconRegister.registerIcon("ss:blockGasVentFront"); iconBuffer[ICON_SIDE_BACK] = par1IconRegister.registerIcon("ss:blockGasVentBack"); iconBuffer[ICON_SIDE_FRONTON] = par1IconRegister.registerIcon("ss:blockGasVentFrontOn"); } @SideOnly(Side.CLIENT) @Override public IIcon getIcon(int side, int metadata) { if (side == 1) { if (metadata == 0) { return iconBuffer[ICON_SIDE_BACK]; } else if (metadata == 1) { return iconBuffer[ICON_SIDE_FRONT]; } else if (metadata == 2) { return iconBuffer[ICON_SIDE_BACK]; } else if (metadata == 3) { return iconBuffer[ICON_SIDE_FRONTON]; } } if (side == 0) { if (metadata == 0) { return iconBuffer[ICON_SIDE_FRONT]; } else if (metadata == 1) { return iconBuffer[ICON_SIDE_BACK]; } else if (metadata == 2) { return iconBuffer[ICON_SIDE_FRONTON]; } else if (metadata == 3) { return iconBuffer[ICON_SIDE_BACK]; } } return iconBuffer[ICON_SIDE]; } /** * Overridden by {@link #createTileEntity(World, int)} */ @Override public TileEntity createNewTileEntity(World w, int i) { return null; } @Override public TileEntity createTileEntity(World world, int meta) { return new SSTileEntityAirVent(); } /** * Returns the quantity of items to drop on block destruction. */ @Override public int quantityDropped(Random par1Random) { return 0; } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityplayer, int side, float a, float b, float c) { if (world.isRemote) return true; if (entityplayer.getCurrentEquippedItem() != null) { String itemName = entityplayer.getCurrentEquippedItem().getUnlocalizedName(); if (itemName.equals("item.ss.multitool")) { TileEntity tileEntity = world.getTileEntity(x, y, z); if (tileEntity instanceof SSTileEntityAirVent) { IGasNetwork net = ((SSTileEntityAirVent) tileEntity).getGasNetwork(); if (SS.Debug) { ((SSTileEntityAirVent) tileEntity).printDebugInfo(); } } } else if (itemName.equals("ic2.itemToolWrenchElectric") || itemName.equals("item.thermalexpansion.tool.wrench")) { // Rotate AirVent int oldMeta = world.getBlockMetadata(x, y, z); int oldSide = oldMeta & 1; if (side != oldSide && side >= 0 && side < 2) { if (side == 0 && side != oldSide) { world.setBlockMetadataWithNotify(x, y, z, oldMeta & 2, 3); // old meta 1 or 3 -> 0 or 2 entityplayer.getCurrentEquippedItem().damageItem(1, entityplayer); TileEntity tileEntity = world.getTileEntity(x, y, z); ((IGasNetworkVent) tileEntity).getGasNetwork().removeVent((IGasNetworkVent) tileEntity); // Rebuild new network on UP from Vent if (SS.Debug) System.out.println("Try to rebild on UP"); if (world.getBlock(x, y+1, z) == SSConfig.ssBlockGasPipe || world.getBlock(x, y+1, z) == SSConfig.ssBlockGasPipeCasing) { GasUtils.registeredEventRebuildGasNetwork(new RebuildNetworkPoint(world,new BlockVec3(x,y+1,z))); } } else if (side == 1 && side != oldSide) { world.setBlockMetadataWithNotify(x, y, z, oldMeta | 1, 3); // old meta 0 or 2 -> 1 or 3 entityplayer.getCurrentEquippedItem().damageItem(1, entityplayer); TileEntity tileEntity = world.getTileEntity(x, y, z); ((IGasNetworkVent) tileEntity).getGasNetwork().removeVent((IGasNetworkVent) tileEntity); // Rebuild new network on DOWN from Vent if (SS.Debug) System.out.println("Try to rebild on DOWN"); if (world.getBlock(x, y-1, z) == SSConfig.ssBlockGasPipe || world.getBlock(x, y-1, z) == SSConfig.ssBlockGasPipeCasing) { GasUtils.registeredEventRebuildGasNetwork(new RebuildNetworkPoint(world,new BlockVec3(x,y-1,z))); } } } } } return true; } @Override public void breakBlock(World par1World, int par2, int par3, int par4, Block par5, int par6) { TileEntity te = par1World.getTileEntity(par2, par3, par4); if (te != null) { te.invalidate(); } super.breakBlock(par1World, par2, par3, par4, par5, par6); } }
Tankistodor/SSAraminta
src/main/java/com/badday/ss/blocks/SSBlockAirVent.java
Java
gpl-2.0
6,252
Almadeladanza::Application.routes.draw do devise_for :users, ActiveAdmin::Devise.config ActiveAdmin.routes(self) mount ActiveAdmin::Tinymce::Engine => '/', as: 'admin_editor' root to: "news#index" resources :dance_styles, only: [:index, :show] resources :lessons, only: [:index, :show] resources :interior_images, only: [:index] resources :news, only: [:index, :show] resources :gallery_events, only: [:index] resources :about, only: [:index] resources :contacts, only: [:index] resources :feedback, only: [:index] resources :coaches, only: [:index, :show] resources :posts, only: [:index, :show] resources :clients, only: [:create] # The priority is based upon order of creation: # first created -> highest priority. # Sample of regular route: # match 'products/:id' => 'catalog#view' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase # This route can be invoked with purchase_url(:id => product.id) # Sample resource route (maps HTTP verbs to controller actions automatically): # resources :products # Sample resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Sample resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Sample resource route with more complex sub-resources # resources :products do # resources :comments # resources :sales do # get 'recent', :on => :collection # end # end # Sample resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end # You can have the root of your site routed with "root" # just remember to delete public/index.html. # root :to => 'welcome#index' # See how all your routes lay out with "rake routes" # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. # match ':controller(/:action(/:id))(.:format)' end
KernelCorp/almadeladanza
config/routes.rb
Ruby
gpl-2.0
2,432
using System; using System.Collections.Generic; using System.Linq; using Server.Engines.PartySystem; using Server.Items; using Server.Spells.Fourth; using Server.Spells.Necromancy; using Server.Targeting; namespace Server.Spells.Mysticism { public class CleansingWindsSpell : MysticSpell { public override SpellCircle Circle { get { return SpellCircle.Sixth; } } private static SpellInfo m_Info = new SpellInfo( "Cleansing Winds", "In Vas Mani Hur", 230, 9022, Reagent.Garlic, Reagent.Ginseng, Reagent.MandrakeRoot, Reagent.DragonBlood ); public CleansingWindsSpell(Mobile caster, Item scroll) : base(caster, scroll, m_Info) { } public override void OnCast() { Caster.Target = new MysticSpellTarget(this, TargetFlags.Beneficial); } public override void OnTarget(object o) { var targeted = o as Mobile; if (targeted == null) return; if (CheckBSequence(targeted)) { /* Soothing winds attempt to neutralize poisons, lift curses, and heal a valid * Target. The Caster's Mysticism and either Focus or Imbuing (whichever is * greater) skills determine the effectiveness of the Cleansing Winds. */ Caster.PlaySound(0x64C); var targets = new List<Mobile> {targeted}; targets.AddRange(FindAdditionalTargets(targeted).Take(3)); // This effect can hit up to 3 additional players beyond the primary target. double primarySkill = Caster.Skills[CastSkill].Value; double secondarySkill = Caster.Skills[DamageSkill].Value; var toHeal = (int)((primarySkill + secondarySkill) / 4.0) + Utility.RandomMinMax(-3, 3); toHeal /= targets.Count; // The effectiveness of the spell is reduced by the number of targets affected. foreach (var target in targets) { // WARNING: This spell will flag the caster as a criminal if a criminal or murderer party member is close enough // to the target to receive the benefits from the area of effect. Caster.DoBeneficial(target); PlayEffect(target); int toHealMod = toHeal; if (target.Poisoned) { int poisonLevel = target.Poison.RealLevel + 1; int chanceToCure = (10000 + (int)((primarySkill + secondarySkill) / 2 * 75) - (poisonLevel * 1750)) / 100; if (chanceToCure > Utility.Random(100) && target.CurePoison(Caster)) { // Poison reduces healing factor by 15% per level of poison. toHealMod -= (int)(toHeal * poisonLevel * 0.15); } else { // If the cure fails, the target will not be healed. toHealMod = 0; } } // Cleansing Winds will not heal the target after removing mortal wound. if (MortalStrike.IsWounded(target)) { MortalStrike.EndWound(target); toHealMod = 0; } var curseLevel = RemoveCurses(target); if (toHealMod > 0 && curseLevel > 0) { // Each Curse reduces healing by 3 points + 1% per curse level. int toHealMod1 = toHealMod - (curseLevel * 3); int toHealMod2 = toHealMod - (int)(toHealMod * (curseLevel / 100.0)); toHealMod -= toHealMod1 + toHealMod2; } if (toHealMod > 0) SpellHelper.Heal(toHealMod, target, Caster); } } FinishSequence(); } private static void PlayEffect(Mobile m) { m.FixedParticles(0x3709, 1, 30, 9963, 13, 3, EffectLayer.Head); var from = new Entity(Serial.Zero, new Point3D(m.X, m.Y, m.Z - 10), m.Map); var to = new Entity(Serial.Zero, new Point3D(m.X, m.Y, m.Z + 50), m.Map); Effects.SendMovingParticles(from, to, 0x2255, 1, 0, false, false, 13, 3, 9501, 1, 0, EffectLayer.Head, 0x100); } private IEnumerable<Mobile> FindAdditionalTargets(Mobile targeted) { var casterParty = Party.Get(Caster); if (casterParty == null) yield break; foreach (var m in Caster.Map.GetMobilesInRange(new Point3D(targeted), 2)) { if (m == null || m == targeted) continue; // Players in the area must be in the casters party in order to receive the beneficial effects of the spell. if (Caster.CanBeBeneficial(m, false) && casterParty.Contains(m)) yield return m; } } private static int RemoveCurses(Mobile m) { int curseLevel = 0; if (SleepSpell.IsUnderSleepEffects(m)) { SleepSpell.EndSleep(m); curseLevel += 2; } if (EvilOmenSpell.TryEndEffect(m)) { curseLevel += 1; } if (StrangleSpell.RemoveCurse(m)) { curseLevel += 2; } if (CorpseSkinSpell.RemoveCurse(m)) { curseLevel += 3; } if (CurseSpell.UnderEffect(m)) { CurseSpell.RemoveEffect(m); curseLevel += 4; } if (BloodOathSpell.RemoveCurse(m)) { curseLevel += 3; } if (MindRotSpell.HasMindRotScalar(m)) { MindRotSpell.ClearMindRotScalar(m); curseLevel += 2; } if (SpellPlagueSpell.HasSpellPlague(m)) { SpellPlagueSpell.RemoveFromList(m); curseLevel += 4; } if (m.GetStatMod("[Magic] Str Curse") != null) { m.RemoveStatMod("[Magic] Str Curse"); curseLevel += 1; } if (m.GetStatMod("[Magic] Dex Curse") != null) { m.RemoveStatMod("[Magic] Dex Curse"); curseLevel += 1; } if (m.GetStatMod("[Magic] Int Curse") != null) { m.RemoveStatMod("[Magic] Int Curse"); curseLevel += 1; } BuffInfo.RemoveBuff(m, BuffIcon.Clumsy); BuffInfo.RemoveBuff(m, BuffIcon.FeebleMind); BuffInfo.RemoveBuff(m, BuffIcon.Weaken); BuffInfo.RemoveBuff(m, BuffIcon.Curse); BuffInfo.RemoveBuff(m, BuffIcon.MassCurse); BuffInfo.RemoveBuff(m, BuffIcon.MortalStrike); BuffInfo.RemoveBuff(m, BuffIcon.Mindrot); BuffInfo.RemoveBuff(m, BuffIcon.CorpseSkin); BuffInfo.RemoveBuff(m, BuffIcon.Strangle); BuffInfo.RemoveBuff(m, BuffIcon.EvilOmen); return curseLevel; } } }
SirGrizzlyBear/ServUOGrizzly
Scripts/Spells/Mysticism/SpellDefinitions/CleansingWindsSpell.cs
C#
gpl-2.0
7,614
/* * Copyright (c) 2011, Intel Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include "kernelAPI.h" #include "globals.h" #define FILENAME_FLAGS (O_RDWR | O_TRUNC | O_CREAT) #define FILENAME_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH) KernelAPI::KernelAPI() { } KernelAPI::~KernelAPI() { } uint8_t * KernelAPI::mmap(size_t bufLength, uint16_t bufID, MmapRegion region) { int prot = PROT_READ; if (region >= MMAPREGION_FENCE) throw FrmwkEx(HERE, "Detected illegal region = %d", region); if (region == MMR_META) prot |= PROT_WRITE; off_t encodeOffset = bufID; encodeOffset |= ((off_t)region << METADATA_UNIQUE_ID_BITS); encodeOffset *= sysconf(_SC_PAGESIZE); return (uint8_t *)::mmap(0, bufLength, prot, MAP_SHARED, gDutFd, encodeOffset); } void KernelAPI::munmap(uint8_t *memPtr, size_t bufLength) { ::munmap(memPtr, bufLength); } void KernelAPI::DumpKernelMetrics(DumpFilename filename) { int rc; struct nvme_file dumpMe = { (short unsigned int)filename.length(), filename.c_str() }; LOG_NRM("Dump dnvme metrics to filename: %s", filename.c_str()); if ((rc = ioctl(gDutFd, NVME_IOCTL_DUMP_METRICS, &dumpMe)) < 0) throw FrmwkEx(HERE, "Unable to dump dnvme metrics, err code = %d", rc); } void KernelAPI::DumpCtrlrSpaceRegs(DumpFilename filename, bool verbose) { int fd; string work; uint64_t value = 0; string outFile; const CtlSpcType *ctlMetrics = gRegisters->GetCtlMetrics(); LOG_NRM("Dump ctrlr regs to filename: %s", filename.c_str()); if ((fd = open(filename.c_str(), FILENAME_FLAGS, FILENAME_MODE)) == -1) throw FrmwkEx(HERE, "file=%s: %s", filename.c_str(), strerror(errno)); // Read all registers in ctrlr space for (int i = 0; i < CTLSPC_FENCE; i++) { if (!gRegisters->ValidSpecRev(ctlMetrics[i].specRev)) continue; if (ctlMetrics[i].size > MAX_SUPPORTED_REG_SIZE) { uint8_t *buffer; buffer = new uint8_t[ctlMetrics[i].size]; if (gRegisters->Read(NVMEIO_BAR01, ctlMetrics[i].size, ctlMetrics[i].offset, buffer, verbose) == false) { goto ERROR_OUT; } else { string work = " "; work += gRegisters->FormatRegister(NVMEIO_BAR01, ctlMetrics[i].size, ctlMetrics[i].offset, buffer); work += "\n"; write(fd, work.c_str(), work.size()); } delete [] buffer; } else if (gRegisters->Read((CtlSpc)i, value, verbose) == false) { break; } else { work = " "; // indent reg values within each capability work += gRegisters->FormatRegister(ctlMetrics[i].size, ctlMetrics[i].desc, value); work += "\n"; write(fd, work.c_str(), work.size()); } } close(fd); return; ERROR_OUT: close(fd); throw FrmwkEx(HERE); } void KernelAPI::DumpPciSpaceRegs(DumpFilename filename, bool verbose) { int fd; string work; uint64_t value; const PciSpcType *pciMetrics = gRegisters->GetPciMetrics(); const vector<PciCapabilities> *pciCap = gRegisters->GetPciCapabilities(); LOG_NRM("Dump PCI regs to filename: %s", filename.c_str()); if ((fd = open(filename.c_str(), FILENAME_FLAGS, FILENAME_MODE)) == -1) throw FrmwkEx(HERE, "file=%s: %s", filename.c_str(), strerror(errno)); // Traverse the PCI header registers work = "PCI header registers\n"; write(fd, work.c_str(), work.size()); for (int j = 0; j < PCISPC_FENCE; j++) { if (!gRegisters->ValidSpecRev(pciMetrics[j].specRev)) continue; // All PCI hdr regs don't have an associated capability if (pciMetrics[j].cap == PCICAP_FENCE) { if (gRegisters->Read((PciSpc)j, value, verbose) == false) goto ERROR_OUT; RegToFile(fd, pciMetrics[j], value); } } // Traverse all discovered capabilities for (size_t i = 0; i < pciCap->size(); i++) { switch (pciCap->at(i)) { case PCICAP_PMCAP: work = "Capabilities: PMCAP: PCI power management\n"; break; case PCICAP_MSICAP: work = "Capabilities: MSICAP: Message signaled interrupt\n"; break; case PCICAP_MSIXCAP: work = "Capabilities: MSIXCAP: Message signaled interrupt ext'd\n"; break; case PCICAP_PXCAP: work = "Capabilities: PXCAP: Message signaled interrupt\n"; break; case PCICAP_AERCAP: work = "Capabilities: AERCAP: Advanced Error Reporting\n"; break; default: LOG_ERR("PCI space reporting an unknown capability: %d\n", pciCap->at(i)); goto ERROR_OUT; } write(fd, work.c_str(), work.size()); // Read all registers assoc with the discovered capability for (int j = 0; j < PCISPC_FENCE; j++) { if (!gRegisters->ValidSpecRev(pciMetrics[j].specRev)) continue; if (pciCap->at(i) == pciMetrics[j].cap) { if (pciMetrics[j].size > MAX_SUPPORTED_REG_SIZE) { bool err = false; uint8_t *buffer; buffer = new uint8_t[pciMetrics[j].size]; if (gRegisters->Read(NVMEIO_PCI_HDR, pciMetrics[j].size, pciMetrics[j].offset, buffer, verbose) == false) { err = true; } else { string work = " "; work += gRegisters->FormatRegister(NVMEIO_PCI_HDR, pciMetrics[j].size, pciMetrics[j].offset, buffer); work += "\n"; write(fd, work.c_str(), work.size()); } delete [] buffer; if (err) goto ERROR_OUT; } else if (gRegisters->Read((PciSpc)j, value, verbose) == false) { goto ERROR_OUT; } else { RegToFile(fd, pciMetrics[j], value); } } } } close(fd); return; ERROR_OUT: close(fd); throw FrmwkEx(HERE); } void KernelAPI::RegToFile(int fd, const PciSpcType regMetrics, uint64_t value) { string work = " "; // indent reg values within each capability work += gRegisters->FormatRegister(regMetrics.size, regMetrics.desc, value); work += "\n"; write(fd, work.c_str(), work.size()); } void KernelAPI::LogCQMetrics(struct nvme_gen_cq &cqMetrics) { LOG_NRM("CQMetrics.q_id = 0x%04X", cqMetrics.q_id); LOG_NRM("CQMetrics.tail_ptr = 0x%04X", cqMetrics.tail_ptr); LOG_NRM("CQMetrics.head_ptr = 0x%04X", cqMetrics.head_ptr); LOG_NRM("CQMetrics.elements = 0x%04X", cqMetrics.elements); LOG_NRM("CQMetrics.irq_enabled = %s", cqMetrics.irq_enabled ? "T" : "F"); LOG_NRM("CQMetrics.irq_no = %d", cqMetrics.irq_no); LOG_NRM("CQMetrics.pbit_new_entry = %d", cqMetrics.pbit_new_entry); } void KernelAPI::LogSQMetrics(struct nvme_gen_sq &sqMetrics) { LOG_NRM("SQMetrics.sq_id = 0x%04X", sqMetrics.sq_id); LOG_NRM("SQMetrics.cq_id = 0x%04X", sqMetrics.cq_id); LOG_NRM("SQMetrics.tail_ptr = 0x%04X", sqMetrics.tail_ptr); LOG_NRM("SQMetrics.tail_ptr_virt = 0x%04X", sqMetrics.tail_ptr_virt); LOG_NRM("SQMetrics.head_ptr = 0x%04X", sqMetrics.head_ptr); LOG_NRM("SQMetrics.elements = 0x%04X", sqMetrics.elements); } void KernelAPI::WriteToDnvmeLog(string log) { int rc; struct nvme_logstr logMe = { (short unsigned int)log.length(), log.c_str() }; LOG_NRM("Write custom string to dnvme's log output: \"%s\"", log.c_str()); if ((rc = ioctl(gDutFd, NVME_IOCTL_MARK_SYSLOG, &logMe)) < 0) { throw FrmwkEx(HERE, "Unable to log custom string to dnvme, err = %d", rc); } }
junqiang521/Test
dnvme/tnvme-master/Utils/kernelAPI.cpp
C++
gpl-2.0
8,831
import csv import logging from fa.miner import yahoo from fa.piping import csv_string_to_records from fa.util import partition from fa.database.query import get_outdated_symbols, update_fundamentals import initialize from settings import * """ Download data from internet to database """ initialize.init() logger = logging.getLogger(__name__) logger.info("Will update historical prices of all symbols not up to date on {0}.".format(end_date)) all_symbols = [s.symbol for s in get_outdated_symbols("price", end_date)] # do the download in chunks of size 8 to prevent overloading servers for symbols in partition(all_symbols, 8): data = yahoo.get_historical_data(symbols, start_date, end_date) for symbol, csv_string in data.items(): if csv_string: try: records = csv_string_to_records(symbol, csv_string, strict=True) update_fundamentals("price", symbol, records, end_date, delete_old=True) except csv.Error as e: logger.exception(e) logger.error("csv of {0} is malformed.".format(symbol)) else: logger.warning("Could not find updated historical prices of {0}. Skip.".format(symbol)) logger.info("Finished updating historical prices.")
kakarukeys/algo-fa
examples/update_price_data.py
Python
gpl-2.0
1,268
<?php /** * @version $Id: frontpage.class.php,v 1.1 2005/07/22 01:54:45 eddieajau Exp $ * @package Mambo * @subpackage Content * @copyright (C) 2000 - 2005 Miro International Pty Ltd * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * Mambo is Free Software */ /** ensure this file is being included by a parent file */ defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' ); /** * @package Mambo * @subpackage Content */ class mosFrontPage extends mosDBTable { /** @var int Primary key */ var $content_id=null; /** @var int */ var $ordering=null; /** * @param database A database connector object */ function mosFrontPage( &$db ) { $this->mosDBTable( '#__content_frontpage', 'content_id', $db ); } } ?>
wuts/earthquake
components/com_frontpage/frontpage.class.php
PHP
gpl-2.0
752
/* * Copyright (c) 2014, 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. */ /** * JDK-8050964: OptimisticTypesPersistence.java should use java.util.Date instead of java.sql.Date * * Make sure that nashorn.jar has only 'compact1' dependency. * * @test * @option -scripting * @run */ // assume that this script is run with "nashorn.jar" System // property set to relative path of nashorn.jar from the current // directory of test execution. if (typeof fail != 'function') { fail = print; } var System = java.lang.System; var File = java.io.File; var nashornJar = new File(System.getProperty("nashorn.jar")); if (! nashornJar.isAbsolute()) { nashornJar = new File(".", nashornJar); } var javahome = System.getProperty("java.home"); var jdepsPath = javahome + "/../bin/jdeps".replaceAll(/\//g, File.separater); // run jdep on nashorn.jar - only summary but print profile info `${jdepsPath} -s -P ${nashornJar.absolutePath}` // check for "(compact1)" in output from jdep tool if (! /(compact1)/.test($OUT)) { fail("non-compact1 dependency: " + $OUT); }
koutheir/incinerator-hotspot
nashorn/test/script/nosecurity/JDK-8050964.js
JavaScript
gpl-2.0
2,050
from infoshopkeeper_config import configuration cfg = configuration() dbtype = cfg.get("dbtype") dbname = cfg.get("dbname") dbhost = cfg.get("dbhost") dbuser = cfg.get("dbuser") dbpass = cfg.get("dbpass") from sqlobject import * if dbtype in ('mysql', 'postgres'): if dbtype is 'mysql': import MySQLdb as dbmodule elif dbtype is 'postgres': import psycopg as dbmodule #deprecate def connect(): return dbmodule.connect (host=dbhost,db=dbname,user=dbuser,passwd=dbpass) def conn(): return '%s://%s:%s@%s/%s?charset=utf8&sqlobject_encoding=utf8' % (dbtype,dbuser,dbpass,dbhost,dbname) elif dbtype is 'sqlite': import os, time, re from pysqlite2 import dbapi2 as sqlite db_file_ext = '.' + dbtype if not dbname.endswith(db_file_ext): dbname+=db_file_ext dbpath = os.path.join(dbhost, dbname) def now(): return time.strftime('%Y-%m-%d %H:%M:%S') def regexp(regex, val): print regex, val, bool(re.search(regex, val, re.I)) return bool(re.search(regex, val, re.I)) class SQLiteCustomConnection(sqlite.Connection): def __init__(self, *args, **kwargs): print '@@@ SQLiteCustomConnection: registering functions' sqlite.Connection.__init__(self, *args, **kwargs) SQLiteCustomConnection.registerFunctions(self) def registerFunctions(self): self.create_function("NOW", 0, now) self.create_function("REGEXP", 2, regexp) self.create_function("regexp", 2, regexp) #~ self.execute("SELECT * FROM title WHERE title.booktitle REGEXP 'mar'") registerFunctions=staticmethod(registerFunctions) #deprecate _conn=None def connect(): import sqlobject #~ return sqlite.connect (database=dbpath) global _conn if not _conn: #~ _conn = sqlite.connect (database=dbpath) from objects.title import Title # can't use factory in URI because sqliteconnection doesn't share globals with us Title._connection._connOptions['factory'] = SQLiteCustomConnection # get the connection instance that sqlobject is going to use, so we only have one _conn = Title._connection.getConnection() # since a connection is made before we can set the factory, we have to register # the functions here also SQLiteCustomConnection.registerFunctions(_conn) return _conn def conn(): return '%s://%s?debug=t' % (dbtype,dbpath) #~ return '%s://%s?debug=t&factory=SQLiteCustomConnection' % (dbtype,dbpath)
johm/infoshopkeeper
components/db.py
Python
gpl-2.0
2,693
package co.deepthought; import co.deepthought.imagine.image.Fingerprinter; import co.deepthought.imagine.store.Size; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashSet; public class Tester { public static void main(String[] args) throws IOException { final String[] imageFiles = { "fireboat-300x200-100.jpg", "fireboat-1200x800-60.jpg", "liberty+autocolor-900x600-60.jpg", "liberty-600x400-40.jpg", "liberty-1200x800-80.jpg", "pathological-cropped-1.jpeg", "pathological-cropped-2.jpeg", "pathological-skyline-1.jpeg", "pathological-skyline-2.jpeg", "hat-small.jpeg", "hat-large.jpeg" }; final String[] fingerprints = new String[imageFiles.length]; for(int i = 0; i < imageFiles.length; i++) { final BufferedImage image = ImageIO.read( new File("/Users/kevindolan/rentenna/imagine/resources/test/"+imageFiles[i])); final Fingerprinter fingerprinter = new Fingerprinter(image); fingerprints[i] = fingerprinter.getFingerprint(new Size(36, 24)); } final HashSet<String> seen = new HashSet<>(); for(int i = 0; i < imageFiles.length; i++) { if(!seen.contains(imageFiles[i])) { seen.add(imageFiles[i]); System.out.println(imageFiles[i]); for(int j = 0; j < imageFiles.length; j++) { if(!seen.contains(imageFiles[j])) { final int difference = Fingerprinter.difference(fingerprints[i], fingerprints[j]); System.out.println(difference); if(difference < 256) { System.out.println("\t" + imageFiles[j]); seen.add(imageFiles[j]); } } } } } } }
metric-collective/imagine
src/main/java/co/deepthought/Tester.java
Java
gpl-2.0
2,065
package net.demilich.metastone.game.spells; import net.demilich.metastone.game.Attribute; import net.demilich.metastone.game.GameContext; import net.demilich.metastone.game.Player; import net.demilich.metastone.game.cards.Card; import net.demilich.metastone.game.cards.CardCatalogue; import net.demilich.metastone.game.cards.CardList; import net.demilich.metastone.game.entities.Entity; import net.demilich.metastone.game.spells.desc.SpellArg; import net.demilich.metastone.game.spells.desc.SpellDesc; import net.demilich.metastone.game.spells.desc.filter.EntityFilter; import net.demilich.metastone.game.targeting.CardLocation; public class ReceiveCardAndDoSomethingSpell extends Spell { private void castSomethingSpell(GameContext context, Player player, SpellDesc spell, Entity source, Card card) { context.getLogic().receiveCard(player.getId(), card); // card may be null (i.e. try to draw from deck, but already in // fatigue) if (card == null || card.getLocation() == CardLocation.GRAVEYARD) { return; } context.setEventCard(card); SpellUtils.castChildSpell(context, player, spell, source, card); context.setEventCard(null); } @Override protected void onCast(GameContext context, Player player, SpellDesc desc, Entity source, Entity target) { EntityFilter cardFilter = (EntityFilter) desc.get(SpellArg.CARD_FILTER); SpellDesc cardEffectSpell = (SpellDesc) desc.get(SpellArg.SPELL); int count = desc.getValue(SpellArg.VALUE, context, player, target, source, 1); if (cardFilter != null) { CardList cards = CardCatalogue.query(context.getDeckFormat()); CardList result = new CardList(); String replacementCard = (String) desc.get(SpellArg.CARD); for (Card card : cards) { if (cardFilter.matches(context, player, card)) { result.add(card); } } for (int i = 0; i < count; i++) { Card card = null; if (!result.isEmpty()) { card = result.getRandom(); } else if (replacementCard != null) { card = CardCatalogue.getCardById(replacementCard); } if (card != null) { Card clone = card.clone(); castSomethingSpell(context, player, cardEffectSpell, source, clone); } } } else { for (Card card : SpellUtils.getCards(context, desc, player)) { for (int i = 0; i < count; i++) { castSomethingSpell(context, player, cardEffectSpell, source, card); } } } } }
doombubbles/metastonething
game/src/main/java/net/demilich/metastone/game/spells/ReceiveCardAndDoSomethingSpell.java
Java
gpl-2.0
2,386
<?php /** * --------------------------------------------------------------------- * GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2015-2017 Teclib' and contributors. * * http://glpi-project.org * * based on GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2003-2014 by the INDEPNET Development Team. * * --------------------------------------------------------------------- * * LICENSE * * This file is part of GLPI. * * GLPI 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. * * GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>. * --------------------------------------------------------------------- */ /** @file * @brief */ if (!defined('GLPI_ROOT')) { die("Sorry. You can't access this file directly"); } /** * Relation between item and devices **/ class Item_DevicePowerSupply extends Item_Devices { static public $itemtype_2 = 'DevicePowerSupply'; static public $items_id_2 = 'devicepowersupplies_id'; static protected $notable = false; /** * @since version 0.85 **/ static function getSpecificities($specif='') { return array('serial' => parent::getSpecificities('serial'), 'otherserial' => parent::getSpecificities('otherserial'), 'locations_id' => parent::getSpecificities('locations_id'), 'states_id' => parent::getSpecificities('states_id') ); } }
eltharin/glpi
inc/item_devicepowersupply.class.php
PHP
gpl-2.0
1,935
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source 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. * * Resin Open Source 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * Free SoftwareFoundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson * * $Id: DocumentEcmaWrap.java,v 1.2 2004/09/29 00:13:10 cvs Exp $ */ package com.caucho.eswrap.org.w3c.dom; import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Document; public class DocumentEcmaWrap { public static Attr createAttribute(Document doc, String name, String value) throws DOMException { Attr attr = doc.createAttribute(name); attr.setValue(value); return attr; } }
christianchristensen/resin
modules/ecmascript/src/com/caucho/eswrap/org/w3c/dom/DocumentEcmaWrap.java
Java
gpl-2.0
1,457
#include <QImage> #include <QFile> #include "SpriteBundle.h" SpriteBundle::SpriteBundle() { m_index = 0; } void SpriteBundle::update(const int delta) { Sprite &image = m_sprites[m_index]; image.update(delta); } void SpriteBundle::setImageIndex(const int index) { m_index = index; } QSGTexture *SpriteBundle::currentImage(Scene *scene, bool flipped) { Sprite &image = m_sprites[m_index]; QSGTexture *frame = image.currentFrame(scene, flipped); return frame; } int SpriteBundle::spriteCount() const { return m_sprites.count(); } int SpriteBundle::imageIndex() const { return m_index; } QDataStream &operator >>(QDataStream &stream, SpriteBundle &bundle) { stream >> bundle.m_sprites; return stream; }
MemoryLeek/ld27
SpriteBundle.cpp
C++
gpl-2.0
720
/************************************************************************* * Clus - Software for Predictive Clustering * * Copyright (C) 2007 * * Katholieke Universiteit Leuven, Leuven, Belgium * * Jozef Stefan Institute, Ljubljana, Slovenia * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * * Contact information: <http://www.cs.kuleuven.be/~dtai/clus/>. * *************************************************************************/ /* * Created on Jul 28, 2005 * */ package clus.ext.beamsearch; import clus.algo.tdidt.ClusNode; import clus.main.Settings; import clus.statistic.ClusStatistic; import clus.statistic.RegressionStat; public class ClusBeamHeuristicMorishita extends ClusBeamHeuristic { public ClusBeamHeuristicMorishita(ClusStatistic stat) { super(stat); } public double computeMorishitaStat(ClusStatistic stat, ClusStatistic tstat) { RegressionStat stat_set = (RegressionStat)stat; RegressionStat stat_all = (RegressionStat)tstat; // Compute half of formula from Definition 2 of Morishita paper double result = 0.0; for (int i = 0; i < stat_set.getNbAttributes(); i++) { double term_i = stat_set.getMean(i) - stat_all.getMean(i); result += term_i * term_i; } return result * stat_set.getTotalWeight(); } public double calcHeuristic(ClusStatistic c_tstat, ClusStatistic c_pstat, ClusStatistic missing) { double n_tot = c_tstat.m_SumWeight; double n_pos = c_pstat.m_SumWeight; double n_neg = n_tot - n_pos; // Acceptable? if (n_pos < Settings.MINIMAL_WEIGHT || n_neg < Settings.MINIMAL_WEIGHT) { return Double.NEGATIVE_INFINITY; } m_Neg.copy(c_tstat); m_Neg.subtractFromThis(c_pstat); // Does not take into account missing values! return computeMorishitaStat(c_pstat, c_tstat) + computeMorishitaStat(m_Neg, c_tstat); } public double estimateBeamMeasure(ClusNode tree, ClusNode parent) { if (tree.atBottomLevel()) { return computeMorishitaStat(tree.getClusteringStat(), parent.getClusteringStat()); } else { double result = 0.0; for (int i = 0; i < tree.getNbChildren(); i++) { ClusNode child = (ClusNode)tree.getChild(i); result += estimateBeamMeasure(child); } return result; } } public double estimateBeamMeasure(ClusNode tree) { if (tree.atBottomLevel()) { return 0; } else { double result = 0.0; for (int i = 0; i < tree.getNbChildren(); i++) { ClusNode child = (ClusNode)tree.getChild(i); result += estimateBeamMeasure(child, tree); } return result; } } public double computeLeafAdd(ClusNode leaf) { return 0.0; } public String getName() { return "Beam Heuristic (Morishita)"; } public void setRootStatistic(ClusStatistic stat) { super.setRootStatistic(stat); } }
active-learning/active-learning-scala
src/main/java/clus/ext/beamsearch/ClusBeamHeuristicMorishita.java
Java
gpl-2.0
3,865
// Implementing the functionality for system calls (keystrokes etc.) and // exercising different functions available from other classes/files // // Author: Archit Gupta, Nehal Bhandari // Date: December 24, 2015 #include "process.h" char valid_keystroke(DisplayHandler* display, char input) { if ((input <= 'z' && input >= 'a') || (input <= 'Z' && input >= 'A')) { return 0; } return input; } // Function definitions for PreviewManager class PreviewManager::PreviewManager() { win = NULL; m_mode = VISUAL; m_exit_signal = false; m_cursor_y = Y_OFFSET; m_cursor_x = X_OFFSET; } // Function definitions specific to ListPreviewManager ListPreviewManager::ListPreviewManager() { ListPreviewManager(NULL, NULL); } ListPreviewManager::ListPreviewManager(WINDOW *_win, ToDoList *td) { win = _win; td_list = td; if (td_list != NULL) { entry_under_cursor = td->get_list_top(); } m_mode = VISUAL; m_exit_signal = false; m_cursor_y = Y_OFFSET; m_cursor_x = X_OFFSET; } void ListPreviewManager::printToDoList(ToDoListEntry* first_entry_to_print) { int y_cursor = m_cursor_y; // TODO: Add functionality to print the todo-list title here (and have a // title for the todo list in the first place ToDoListEntry* entry_to_print = first_entry_to_print; while(entry_to_print != NULL) { printToDoEntry(entry_to_print, y_cursor); y_cursor += entry_to_print->get_message_block_length(); entry_to_print = entry_to_print->get_next_todo_entry(); } box(win, 0, 0); wrefresh(win); } void ListPreviewManager::printToDoEntry(ToDoListEntry* entry_to_print, int y_cursor) { entry_to_print->print(win, y_cursor, entry_to_print == entry_under_cursor); #ifdef __DEBUG__ //getch(); //box(win, 0, 0); wrefresh(win); #endif } void ListPreviewManager::insert_text(char input) { entry_under_cursor->insert_text(win, m_cursor_y, m_cursor_x, input); if ((input >= (char) FIRST_WRITABLE_ASCII_CHAR) && (input <= (char) LAST_WRITEABLE_ASCII_CHAR)) { move_cursor_right(); } else if (input == (char) M_KEY_BACKSPACE) { move_cursor_left(); } wrefresh(win); } void ListPreviewManager::process(char input) { switch (input) { #define F_DEF(INPUT, FUNCTION, NON_FUNC_MODE)\ case INPUT:\ if (m_mode == NON_FUNC_MODE)\ {\ insert_text(INPUT);\ } else {\ FUNCTION(); \ } break; #include "keystrokes.def" #undef F_DEF default: if (m_mode == INSERT) { insert_text(input); } else { return; } break; } } // Key stroke related functions have been described here void ListPreviewManager::move_cursor_left(){ if (m_mode == EDIT || m_mode == INSERT) { if (m_cursor_x > X_OFFSET) { wmove(win, m_cursor_y, --m_cursor_x); wrefresh(win); } else{ int old_cursor_y = m_cursor_y; move_cursor_up(); if (old_cursor_y != m_cursor_y) { // Change the x cursor value only if the y cursor has changed // (i.e. the line under cursor has been switched) m_cursor_x = WRITABLE_X; wmove(win, m_cursor_y, m_cursor_x); wrefresh(win); } } } } void ListPreviewManager::move_cursor_right(){ if (m_mode == EDIT || m_mode == INSERT) { if (m_cursor_x < entry_under_cursor->x_limit()) { wmove(win, m_cursor_y, ++m_cursor_x); wrefresh(win); } else{ int old_cursor_y = m_cursor_y; move_cursor_down(); if (old_cursor_y != m_cursor_y) { // Change the x cursor value only if the y cursor has changed // (i.e. the line under cursor has been switched) m_cursor_x = X_OFFSET; wmove(win, m_cursor_y, m_cursor_x); wrefresh(win); } } } } void ListPreviewManager::move_cursor_up(){ if (m_mode == VISUAL) { if(entry_under_cursor->get_prev_todo_entry() != NULL) { entry_under_cursor->refresh(win, m_cursor_y, false); entry_under_cursor = entry_under_cursor->get_prev_todo_entry(); m_cursor_y -= entry_under_cursor->get_message_block_length(); entry_under_cursor->refresh(win, m_cursor_y, true); wrefresh(win); box(win, 0, 0); } } else { bool jump_todo_entry = entry_under_cursor->check_end_point(true); if (jump_todo_entry) { if(entry_under_cursor->get_prev_todo_entry() != NULL) { entry_under_cursor = entry_under_cursor->get_prev_todo_entry(); entry_under_cursor->set_cursor_bottom(); m_cursor_x = entry_under_cursor->x_limit(); wmove(win, --m_cursor_y, m_cursor_x); } } else { entry_under_cursor->update_cursor_position(win, m_cursor_y, m_cursor_x, true); } wrefresh(win); } } void ListPreviewManager::move_cursor_down(){ if (m_mode == VISUAL) { if(entry_under_cursor->get_next_todo_entry() != NULL) { entry_under_cursor->refresh(win, m_cursor_y, false); m_cursor_y += entry_under_cursor->get_message_block_length(); entry_under_cursor = entry_under_cursor->get_next_todo_entry(); entry_under_cursor->refresh(win, m_cursor_y, true); wrefresh(win); box(win, 0, 0); } } else { bool jump_todo_entry = entry_under_cursor->check_end_point(false); if (jump_todo_entry) { if(entry_under_cursor->get_prev_todo_entry() != NULL) { entry_under_cursor = entry_under_cursor->get_next_todo_entry(); entry_under_cursor->set_cursor_top(); m_cursor_x = X_OFFSET; wmove(win, ++m_cursor_y, m_cursor_x); } } else { entry_under_cursor->update_cursor_position(win, m_cursor_y, m_cursor_x, false); } wrefresh(win); } } // Switching between various modes void ListPreviewManager::switch_to_edit_mode(){ PreviewMode last_mode = m_mode; m_mode = EDIT; curs_set(m_mode); if (last_mode == VISUAL) { entry_under_cursor->refresh(win, m_cursor_y, false); wmove(win, m_cursor_y, X_OFFSET); wrefresh(win); } } void ListPreviewManager::switch_to_visual_mode(){ if (m_mode == EDIT) { m_mode = VISUAL; curs_set(m_mode); entry_under_cursor->refresh(win, m_cursor_y, true); wrefresh(win); } } void ListPreviewManager::switch_to_insert_mode(){ m_mode = INSERT; curs_set(EDIT); // Using curs_set(INSERT) makes the cursor invisible -___- entry_under_cursor->refresh(win, m_cursor_y, false); wmove(win, m_cursor_y, m_cursor_x); wrefresh(win); } void ListPreviewManager::step_modes_back(){ switch (m_mode) { case EDIT: switch_to_visual_mode(); break; case INSERT: switch_to_edit_mode(); break; default: switch_to_visual_mode(); break; } } // Adding and deleting ToDo Entries void ListPreviewManager::add_todo_entry(){ entry_under_cursor = td_list->new_todo_entry(entry_under_cursor); printToDoList(entry_under_cursor); } void ListPreviewManager::two_tap_delete(){ char repeat = getch(); if (repeat == 'd') { ToDoListEntry* next_todo_entry = entry_under_cursor->get_next_todo_entry(); td_list->remove_todo_entry(entry_under_cursor); entry_under_cursor = next_todo_entry; printToDoList(entry_under_cursor); } } void ListPreviewManager::two_tap_quit(){ char repeat = getch(); if (repeat == 'q') { m_exit_signal = true; } } void ListPreviewManager::toggle_mark_unmark(){ entry_under_cursor->toggle_mark_unmark(); entry_under_cursor->refresh(win, m_cursor_y, true); wrefresh(win); }
architgupta93/todo-app
2_Code/process.cpp
C++
gpl-2.0
8,567
function Drag(id,init) { var _this=this; this.disX=0; this.disY=0; this.oDiv=document.getElementById(id); if(init) { _this.fnDown(); } this.oDiv.onmousedown=function (ev) { _this.fnDown(ev); return false; }; } Drag.prototype.fnDown=function (ev) { var _this=this; var oEvent=ev||event; this.disX=oEvent.clientX-this.oDiv.offsetLeft; this.disY=oEvent.clientY-this.oDiv.offsetTop; document.onmousemove=function (ev) { _this.fnMove(ev); }; document.onmouseup=function () { _this.fnUp(); }; }; Drag.prototype.fnMove=function (ev) { var oEvent=ev||event; this.oDiv.style.left=oEvent.clientX-this.disX+'px'; this.oDiv.style.top=oEvent.clientY-this.disY+'px'; }; Drag.prototype.fnUp=function () { document.onmousemove=null; document.onmouseup=null; }; function LimitDrag(id) { Drag.call(this, id); } //LimitDrag.prototype=Drag.prototype; for(var i in Drag.prototype) { LimitDrag.prototype[i]=Drag.prototype[i]; } LimitDrag.prototype.fnMove=function (ev) { var oEvent=ev||event; var l=oEvent.clientX-this.disX; var t=oEvent.clientY-this.disY; if(l<0) { l=0; } else if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth) { l=document.documentElement.clientWidth-this.oDiv.offsetWidth; } if(t<0) { t=0; } else if(t>document.documentElement.clientHeight-this.oDiv.offsetHeight) { t=document.documentElement.clientHeight-this.oDiv.offsetHeight; } this.oDiv.style.left=l+'px'; this.oDiv.style.top=t+'px'; };
Jackmeng1985/drupal7
sites/all/modules/beauty_crm/js/drag.js
JavaScript
gpl-2.0
1,492
#!/usr/bin/env python background_image_filename = 'sushiplate.jpg' import pygame from pygame.locals import * from sys import exit SCREEN_SIZE = (640, 480) pygame.init() screen = pygame.display.set_mode(SCREEN_SIZE, NOFRAME, 32) background = pygame.image.load(background_image_filename).convert() while True: event = pygame.event.wait() if event.type == QUIT: exit() if event.type == VIDEORESIZE: SCREEN_SIZE = event.size screen = pygame.display.set_mode(SCREEN_SIZE, RESIZABLE, 32) pygame.display.set_caption('Window resized to ' + str(event.size)) # screen.fill((0, 0, 0)) screen.blit(background, (0, 0)) # screen_width, screen_height = SCREEN_SIZE # for y in range(0, screen_height, background.get_height()): # for x in range(0, screen_width, background.get_width()): # screen.blit(background, (x, y)) pygame.display.update()
opensvn/python
pygame/resize.py
Python
gpl-2.0
919
/* * _ __ _ * | |/ /__ __ __ _ _ __ | |_ _ _ _ __ ___ * | ' / \ \ / // _` || '_ \ | __|| | | || '_ ` _ \ * | . \ \ V /| (_| || | | || |_ | |_| || | | | | | * |_|\_\ \_/ \__,_||_| |_| \__| \__,_||_| |_| |_| * * Copyright (C) 2019 Alexander Söderberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package xyz.kvantum.server.api.util; public interface ApplicationStructureFactory<A extends ApplicationStructure> { A create(ApplicationContext applicationContext); }
IntellectualSites/IntellectualServer
ServerAPI/src/main/java/xyz/kvantum/server/api/util/ApplicationStructureFactory.java
Java
gpl-2.0
1,042
<? echo "<div class='information'>\n"; require("../updatePubliDocs.php"); $chemin="$_SERVER[DOCUMENT_ROOT]$public_path/$publi[year]/$publi[bibTex]/" ; intranetSqlConnect(); if (!empty($_POST["group"])) $group=$_POST["group"]; $res_upd = sqlQuery("SELECT * from docs WHERE id=$id_doc"); $docs = mysql_fetch_array($res_upd); switch ($group) { case "public": rename($chemin."$protected/$docs[source]", $chemin.$docs['source']); break; case "private": if (!is_dir($chemin."$protected/")) { mkdir($chemin."$protected/", 0755); } if (!is_file($chemin."$protected/.htaccess")) { // Creation of .htaccess file $file = $chemin."$protected/.htaccess"; echo "Creating .htaccess file in $chemin$protected/<br />\n"; copy("$_SERVER[DOCUMENT_ROOT]$intra_path/htaccess_private", $file); if (!is_file("$file")) error("File .htaccess could not be created"); } rename($chemin.$docs['source'], $chemin."$protected/$docs[source]"); break; } updatePubliDocs($id); echo "</div>\n"; ?>
truijllo/basilic
Sources/Intranet/Publications/mod_upd.php
PHP
gpl-2.0
1,036
<?php /** *------------------------------------------------------------------------------ * iCagenda v3 by Jooml!C - Events Management Extension for Joomla! 2.5 / 3.x *------------------------------------------------------------------------------ * @package com_icagenda * @copyright Copyright (c)2012-2014 Cyril RezŽ, Jooml!C - All rights reserved * * @license GNU General Public License version 3 or later; see LICENSE.txt * @author Cyril RezŽ (Lyr!C) * @link http://www.joomlic.com * * @version 3.3.3 2014-04-02 * @since 3.3.3 *------------------------------------------------------------------------------ */ // No direct access to this file defined('_JEXEC') or die(); /** * category Table class */ class iCagendaTableregistration extends JTable { /** * Constructor * * @param JDatabase A database connector object */ public function __construct(&$_db) { parent::__construct('#__icagenda_registration', 'id', $_db); } /** * Overloaded bind function to pre-process the params. * * @param array Named array * @return null|string null is operation was satisfactory, otherwise returns an error * @see JTable:bind * @since 1.5 */ public function bind($array, $ignore = '') { if (isset($array['params']) && is_array($array['params'])) { $registry = new JRegistry(); $registry->loadArray($array['params']); $array['params'] = (string)$registry; } if (isset($array['metadata']) && is_array($array['metadata'])) { $registry = new JRegistry(); $registry->loadArray($array['metadata']); $array['metadata'] = (string)$registry; } return parent::bind($array, $ignore); } /** * Overloaded check function */ public function check() { //If there is an ordering column and this is a new row then get the next ordering value if (property_exists($this, 'ordering') && $this->id == 0) { $this->ordering = self::getNextOrder(); } // URL jimport( 'joomla.filter.output' ); // if(empty($this->alias)) { // $this->alias = $this->title; // } // $this->alias = JFilterOutput::stringURLSafe($this->alias); return parent::check(); } /** * Method to set the publishing state for a row or list of rows in the database * table. The method respects checked out rows by other users and will attempt * to checkin rows that it can after adjustments are made. * * @param mixed An optional array of primary key values to update. If not * set the instance property value is used. * @param integer The publishing state. eg. [0 = unpublished, 1 = published] * @param integer The user id of the user performing the operation. * @return boolean True on success. * @since 1.0.4 */ public function publish($pks = null, $state = 1, $userId = 0) { // Initialise variables. $k = $this->_tbl_key; // Sanitize input. JArrayHelper::toInteger($pks); $userId = (int) $userId; $state = (int) $state; // If there are no primary keys set check to see if the instance key is set. if (empty($pks)) { if ($this->$k) { $pks = array($this->$k); } // Nothing to set publishing state on, return false. else { $this->setError(JText::_('JLIB_DATABASE_ERROR_NO_ROWS_SELECTED')); return false; } } // Build the WHERE clause for the primary keys. $where = $k.'='.implode(' OR '.$k.'=', $pks); // Determine if there is checkin support for the table. if (!property_exists($this, 'checked_out') || !property_exists($this, 'checked_out_time')) { $checkin = ''; } else { $checkin = ' AND (checked_out = 0 OR checked_out = '.(int) $userId.')'; } // Update the publishing state for rows with the given primary keys. $this->_db->setQuery( 'UPDATE `'.$this->_tbl.'`' . ' SET `state` = '.(int) $state . ' WHERE ('.$where.')' . $checkin ); $this->_db->query(); // Check for a database error. if ($this->_db->getErrorNum()) { $this->setError($this->_db->getErrorMsg()); return false; } // If checkin is supported and all rows were adjusted, check them in. if ($checkin && (count($pks) == $this->_db->getAffectedRows())) { // Checkin the rows. foreach($pks as $pk) { $this->checkin($pk); } } // If the JTable instance value is in the list of primary keys that were set, set the instance. if (in_array($this->$k, $pks)) { $this->state = $state; } $this->setError(''); return true; } }
C3Style/appuihec
administrator/components/com_icagenda/tables/registration.php
PHP
gpl-2.0
4,975
/** * stencil_maskType.java * * This file was generated by XMLSpy 2007sp2 Enterprise Edition. * * YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE * OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION. * * Refer to the XMLSpy Documentation for further details. * http://www.altova.com/xmlspy */ package com.jmex.model.collada.schema; import com.jmex.xml.types.SchemaNCName; public class stencil_maskType extends com.jmex.xml.xml.Node { public stencil_maskType(stencil_maskType node) { super(node); } public stencil_maskType(org.w3c.dom.Node node) { super(node); } public stencil_maskType(org.w3c.dom.Document doc) { super(doc); } public stencil_maskType(com.jmex.xml.xml.Document doc, String namespaceURI, String prefix, String name) { super(doc, namespaceURI, prefix, name); } public void adjustPrefix() { for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Attribute, null, "value" ); tmpNode != null; tmpNode = getDomNextChild( Attribute, null, "value", tmpNode ) ) { internalAdjustPrefix(tmpNode, false); } for ( org.w3c.dom.Node tmpNode = getDomFirstChild( Attribute, null, "param" ); tmpNode != null; tmpNode = getDomNextChild( Attribute, null, "param", tmpNode ) ) { internalAdjustPrefix(tmpNode, false); } } public void setXsiType() { org.w3c.dom.Element el = (org.w3c.dom.Element) domNode; el.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:type", "stencil_mask"); } public static int getvalue2MinCount() { return 0; } public static int getvalue2MaxCount() { return 1; } public int getvalue2Count() { return getDomChildCount(Attribute, null, "value"); } public boolean hasvalue2() { return hasDomChild(Attribute, null, "value"); } public int2 newvalue2() { return new int2(); } public int2 getvalue2At(int index) throws Exception { return new int2(getDomNodeValue(getDomChildAt(Attribute, null, "value", index))); } public org.w3c.dom.Node getStartingvalue2Cursor() throws Exception { return getDomFirstChild(Attribute, null, "value" ); } public org.w3c.dom.Node getAdvancedvalue2Cursor( org.w3c.dom.Node curNode ) throws Exception { return getDomNextChild( Attribute, null, "value", curNode ); } public int2 getvalue2ValueAtCursor( org.w3c.dom.Node curNode ) throws Exception { if( curNode == null ) throw new com.jmex.xml.xml.XmlException("Out of range"); else return new int2(getDomNodeValue(curNode)); } public int2 getvalue2() throws Exception { return getvalue2At(0); } public void removevalue2At(int index) { removeDomChildAt(Attribute, null, "value", index); } public void removevalue2() { removevalue2At(0); } public org.w3c.dom.Node addvalue2(int2 value) { if( value.isNull() ) return null; return appendDomChild(Attribute, null, "value", value.toString()); } public org.w3c.dom.Node addvalue2(String value) throws Exception { return addvalue2(new int2(value)); } public void insertvalue2At(int2 value, int index) { insertDomChildAt(Attribute, null, "value", index, value.toString()); } public void insertvalue2At(String value, int index) throws Exception { insertvalue2At(new int2(value), index); } public void replacevalue2At(int2 value, int index) { replaceDomChildAt(Attribute, null, "value", index, value.toString()); } public void replacevalue2At(String value, int index) throws Exception { replacevalue2At(new int2(value), index); } public static int getparamMinCount() { return 0; } public static int getparamMaxCount() { return 1; } public int getparamCount() { return getDomChildCount(Attribute, null, "param"); } public boolean hasparam() { return hasDomChild(Attribute, null, "param"); } public SchemaNCName newparam() { return new SchemaNCName(); } public SchemaNCName getparamAt(int index) throws Exception { return new SchemaNCName(getDomNodeValue(getDomChildAt(Attribute, null, "param", index))); } public org.w3c.dom.Node getStartingparamCursor() throws Exception { return getDomFirstChild(Attribute, null, "param" ); } public org.w3c.dom.Node getAdvancedparamCursor( org.w3c.dom.Node curNode ) throws Exception { return getDomNextChild( Attribute, null, "param", curNode ); } public SchemaNCName getparamValueAtCursor( org.w3c.dom.Node curNode ) throws Exception { if( curNode == null ) throw new com.jmex.xml.xml.XmlException("Out of range"); else return new SchemaNCName(getDomNodeValue(curNode)); } public SchemaNCName getparam() throws Exception { return getparamAt(0); } public void removeparamAt(int index) { removeDomChildAt(Attribute, null, "param", index); } public void removeparam() { removeparamAt(0); } public org.w3c.dom.Node addparam(SchemaNCName value) { if( value.isNull() ) return null; return appendDomChild(Attribute, null, "param", value.toString()); } public org.w3c.dom.Node addparam(String value) throws Exception { return addparam(new SchemaNCName(value)); } public void insertparamAt(SchemaNCName value, int index) { insertDomChildAt(Attribute, null, "param", index, value.toString()); } public void insertparamAt(String value, int index) throws Exception { insertparamAt(new SchemaNCName(value), index); } public void replaceparamAt(SchemaNCName value, int index) { replaceDomChildAt(Attribute, null, "param", index, value.toString()); } public void replaceparamAt(String value, int index) throws Exception { replaceparamAt(new SchemaNCName(value), index); } }
tectronics/xenogeddon
src/com/jmex/model/collada/schema/stencil_maskType.java
Java
gpl-2.0
5,745
#include "document.h" #include "effect.h" #include "newdialog.h" #include <QtCore/QFile> #include <QtCore/QTimer> #include <QtCore/QUrl> #include <QtGui/QMessageBox> #include <QtGui/QFileDialog> namespace { static QString strippedName(const QString & fileName) { return QFileInfo(fileName).fileName(); } static QString strippedName(const QFile & file) { return QFileInfo(file).fileName(); } } // static QString Document::lastEffect() { return s_lastEffect; } // static void Document::setLastEffect(const QString & effectPath) { s_lastEffect = effectPath; } // static QString Document::s_lastEffect; Document::Document(QGLWidget * glWidget, QWidget * parent/*= 0*/) : QObject(parent) { Q_ASSERT(glWidget != NULL); m_glWidget = glWidget; m_owner = parent; m_effectFactory = NULL; m_file = NULL; m_effect = NULL; m_modified = false; } Document::~Document() { closeEffect(); } bool Document::isModified() const { return m_modified; } void Document::setModified(bool m) { // If file not saved, modified is always true. //if (m_modified != m) // Sometimes want to force an update by invoking the signal. { m_modified = m; emit modifiedChanged(m_modified); } } /// Return the current document file name. QString Document::fileName() const { QString fileName; if (m_file != NULL) { fileName = strippedName(*m_file); } else { QString fileExtension = m_effectFactory->extension(); fileName = tr("untitled") + "." + fileExtension; } return fileName; } /// Return document's title. QString Document::title() const { QString title; if (m_file == NULL) { title = tr("Untitled"); } else { title = strippedName(*m_file); } if (m_modified) { title.append(" "); title.append(tr("[modified]")); } return title; } bool Document::canLoadFile(const QString & fileName) const { int idx = fileName.lastIndexOf('.'); QString fileExtension = fileName.mid(idx+1); const EffectFactory * effectFactory = EffectFactory::factoryForExtension(fileExtension); return (effectFactory != NULL) && m_effectFactory->isSupported(); } /*************************Peter Komar code, august 2009 ************************************/ void Document::slot_load_from_library_shader(const QString& name_lib) { if (!close()) { // User cancelled the operation. return; } QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); QFile *filelib = new QFile(name_lib); if (!filelib->open(QIODevice::ReadOnly)) { QMessageBox::critical(m_owner, tr("Error"), tr("Can't open library.")); return; } int idx = name_lib.lastIndexOf('.'); QString Ext = name_lib.mid(idx+1); m_effectFactory = EffectFactory::factoryForExtension(Ext); if (m_effectFactory != NULL) { Q_ASSERT(m_effectFactory->isSupported()); m_effect = m_effectFactory->createEffect(m_glWidget); Q_ASSERT(m_effect != NULL); connect(m_effect, SIGNAL(built(bool)), this, SIGNAL(effectBuilt(bool))); m_effect->load(filelib); emit effectCreated(); build(false); } emit titleChanged(name_lib.mid(name_lib.lastIndexOf("/")+1,idx)); filelib->close(); delete filelib; QApplication::restoreOverrideCursor(); } /**************************************************************************/ bool Document::loadFile(const QString & fileName) { if (!close()) { // User cancelled the operation. return false; } delete m_file; m_file = new QFile(fileName); if (!m_file->open(QIODevice::ReadOnly)) { delete m_file; m_file = NULL; return false; } QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); m_modified = false; int idx = fileName.lastIndexOf('.'); QString fileExtension = fileName.mid(idx+1); m_effectFactory = EffectFactory::factoryForExtension(fileExtension); if (m_effectFactory != NULL) { Q_ASSERT(m_effectFactory->isSupported()); m_effect = m_effectFactory->createEffect(m_glWidget); Q_ASSERT(m_effect != NULL); connect(m_effect, SIGNAL(built(bool)), this, SIGNAL(effectBuilt(bool))); m_effect->load(m_file); emit effectCreated(); build(false); } else { // @@ Can this happen? } m_file->close(); emit titleChanged(title()); s_lastEffect = fileName; // @@ Move this somewhere else! emit fileNameChanged(fileName); QApplication::restoreOverrideCursor(); return true; } void Document::reset(bool startup) { // Count effect file types. const QList<const EffectFactory *> & effectFactoryList = EffectFactory::factoryList(); int count = 0; foreach(const EffectFactory * ef, effectFactoryList) { if(ef->isSupported()) { ++count; } } const EffectFactory * effectFactory = NULL; if (count == 0) { // Display error. QMessageBox::critical(m_owner, tr("Error"), tr("No effect files supported"), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); } else if(count == 1) { // Use the first supported effect type. foreach(const EffectFactory * ef, effectFactoryList) { if(ef->isSupported()) { effectFactory = ef; break; } } } else { // Let the user choose the effect type. NewDialog newDialog(m_owner, startup); int result = newDialog.exec(); if (result == QDialog::Accepted) { QString selection = newDialog.shaderType(); foreach(const EffectFactory * ef, effectFactoryList) { if(ef->isSupported() && ef->name() == selection) { effectFactory = ef; break; } } } else if (result == NewDialog::OpenEffect) { open(); return; } } if (effectFactory != NULL) { newEffect(effectFactory); } } void Document::open() { // Find supported effect types. QStringList effectTypes; QStringList effectExtensions; foreach (const EffectFactory * factory, EffectFactory::factoryList()) { if (factory->isSupported()) { QString effectType = QString("%1 (*.%2)").arg(factory->namePlural()).arg(factory->extension()); effectTypes.append(effectType); QString effectExtension = factory->extension(); effectExtensions.append("*." + effectExtension); } } if (effectTypes.isEmpty()) { QMessageBox::critical(m_owner, tr("Error"), tr("No effect files supported"), QMessageBox::Ok, QMessageBox::NoButton, QMessageBox::NoButton); return; } //QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), tr("."), effectTypes.join(";")); QString fileName = QFileDialog::getOpenFileName(m_owner, tr("Open File"), s_lastEffect, QString(tr("Effect Files (%1)")).arg(effectExtensions.join(" "))); if (!fileName.isEmpty()) { loadFile(fileName); } } bool Document::save() { if (m_file == NULL) { // Choose file dialog. QString fileExtension = m_effectFactory->extension(); QString effectType = QString("%1 (*.%2)").arg(m_effectFactory->namePlural()).arg(fileExtension); QString fileName = QFileDialog::getSaveFileName(m_owner, tr("Save File"), tr("untitled") + "." + fileExtension, effectType); if( fileName.isEmpty() ) { return false; } m_file = new QFile(fileName); } // @@ Check for errors. return saveEffect(); } void Document::saveAs() { Q_ASSERT(m_effectFactory != NULL); QString fileExtension = m_effectFactory->extension(); QString effectType = QString("%1 (*.%2)").arg(m_effectFactory->namePlural()).arg(fileExtension); // Choose file dialog. QString fileName = QFileDialog::getSaveFileName(m_owner, tr("Save File"), this->fileName(), effectType); if( fileName.isEmpty() ) { return; } delete m_file; m_file = new QFile(fileName); // @@ Check for errors. saveEffect(); // @@ Emit only when file name actually changed. emit fileNameChanged(fileName); } bool Document::close() { if (m_effect == NULL) { Q_ASSERT(m_file == NULL); // No effect open. return true; } if (m_effectFactory != NULL && isModified()) { QString fileName; if (m_file != NULL) { fileName = strippedName(*m_file); } else { QString extension = m_effectFactory->extension(); fileName = tr("untitled") + "." + extension; } while (true) { int answer = QMessageBox::question(m_owner, tr("Save modified files"), tr("Do you want to save '%1' before closing?").arg(fileName), QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel); if (answer == QMessageBox::Yes) { if( save() ) { break; } } else if (answer == QMessageBox::Cancel) { return false; } else { break; } } } emit effectDeleted(); closeEffect(); return true; } void Document::build(bool threaded /*= true*/) { Q_ASSERT(m_effect != NULL); emit synchronizeEditors(); emit effectBuilding(); m_effect->build(threaded); } void Document::onParameterChanged() { Q_ASSERT(m_effectFactory != NULL); if (m_effectFactory->savesParameters() && !isModified()) { setModified(true); } } void Document::newEffect(const EffectFactory * effectFactory) { Q_ASSERT(effectFactory != NULL); if (!close()) { // User cancelled the operation. return; } QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); m_effectFactory = effectFactory; m_effect = m_effectFactory->createEffect(m_glWidget); Q_ASSERT(m_effect != NULL); connect(m_effect, SIGNAL(built(bool)), this, SIGNAL(effectBuilt(bool))); m_modified = false; emit effectCreated(); emit titleChanged(title()); build(false); QApplication::restoreOverrideCursor(); } bool Document::saveEffect() { m_file->open(QIODevice::WriteOnly); // Synchronize before save. emit synchronizeEditors(); m_effect->save(m_file); m_file->close(); setModified(false); emit titleChanged(title()); //updateActions(); // qshaderedit listens to modifiedChanged return true; } void Document::closeEffect() { // Delete effect. delete m_effect; m_effect = NULL; delete m_file; m_file = NULL; }
peterkomar/qshaderedit
src/document.cpp
C++
gpl-2.0
10,048
<?php /* Plugin Name: Email Subscribers Plugin URI: http://www.gopiplus.com/work/2014/05/02/email-subscribers-wordpress-plugin/ Description: Email subscribers plugin has options to send newsletters to subscribers. It has a separate page with HTML editor to create a HTML newsletter. Also have options to send notification email to subscribers when new posts are published to your blog. Separate page available to include and exclude categories to send notifications. Version: 2.7 Author: Gopi Ramasamy Donate link: http://www.gopiplus.com/work/2014/05/02/email-subscribers-wordpress-plugin/ Author URI: http://www.gopiplus.com/work/2014/05/02/email-subscribers-wordpress-plugin/ License: GPLv2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html */ /* Copyright 2014 Email subscribers (http://www.gopiplus.com) 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(preg_match('#' . basename(__FILE__) . '#', $_SERVER['PHP_SELF'])) { die('You are not allowed to call this page directly.'); } require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'base'.DIRECTORY_SEPARATOR.'es-defined.php'); require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.'es-stater.php'); add_action('admin_menu', array( 'es_cls_registerhook', 'es_adminmenu' )); register_activation_hook(ES_FILE, array( 'es_cls_registerhook', 'es_activation' )); register_deactivation_hook(ES_FILE, array( 'es_cls_registerhook', 'es_deactivation' )); add_action( 'widgets_init', array( 'es_cls_registerhook', 'es_widget_loading' )); add_shortcode( 'email-subscribers', 'es_shortcode' ); require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.'es-directly.php'); function es_textdomain() { load_plugin_textdomain( 'email-subscribers' , false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' ); } add_action('plugins_loaded', 'es_textdomain'); add_action( 'transition_post_status', array( 'es_cls_sendmail', 'es_prepare_notification' ), 10, 3 ); ?>
CosmicPi/cosmicpi.org
wp-content/plugins/email-subscribers/email-subscribers.php
PHP
gpl-2.0
2,553
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateProjectPackageTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('project_package', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('repository'); $table->string('deploy_branch'); $table->string('deploy_location'); $table->integer('order'); $table->integer('project_id')->unsigned(); }); Schema::table('project_package', function($table) { $table->foreign('project_id') ->references('id')->on('project') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('project_package'); } }
ImbalanceGaming/imbalance-gaming-laravel
database/migrations/2016_04_14_100207_create_project_package_table.php
PHP
gpl-2.0
1,001
package com.example.seventeen.blissappid; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.CountDownTimer; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; /** * Hofundur: Egill Orn Sigthorsson * Dagsetning: 1.10.2014 * Lysing: Vidmot fyrir nothafa, tar sem hann getur tjad ja og nei * a audskiljanlegan hatt og opnad fulla blisstaknatoflu */ public class nothafi1 extends Activity { /** * Gerum sitthvoran onclicklistner fyrir ja og nei * @param savedInstanceState save instance */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_nothafi1); makeOnclickListeners(); } /** * bua til on click listnera fyrir takka i netenda vidmoti */ public void makeOnclickListeners(){ ImageButton jabutt; jabutt = (ImageButton) findViewById(R.id.ja); jabutt.setOnClickListener(gotoClickListener); ImageButton neibutt; neibutt = (ImageButton) findViewById(R.id.nei); neibutt.setOnClickListener(gotoneiClickListener); ImageButton bio; bio = (ImageButton) findViewById(R.id.bio); bio.setOnClickListener(gotoBioClickListener); ImageButton ftafla; ftafla = (ImageButton) findViewById(R.id.ftafla); ftafla.setOnClickListener(gotoftaflaClickListener); } /** * Ef smellt er a ja takkan */ View.OnClickListener gotoClickListener = new View.OnClickListener() { /** * tegar smellt er a ja takkan gloir hann i 3 sekundur * * @param v er view */ @Override public void onClick(View v) { final ImageButton jabutt; jabutt = (ImageButton) findViewById(R.id.ja); new CountDownTimer(3000,1000){ /** * breytum bakgrunni a takkanum a medan vid teljum nidur * @param millisUntilFinished timi eftir */ @Override public void onTick(long millisUntilFinished){ jabutt.setBackgroundResource(R.drawable.jafoc); } /** * breytum bakgrunni a takkanum i upprunalegt astandi tegar 3 sekundur eru lidnar */ @Override public void onFinish(){ //set the new Content of your activity jabutt.setBackgroundResource(R.drawable.ja); } }.start(); } }; /** * Ef smellt er a nei takkan */ View.OnClickListener gotoneiClickListener = new View.OnClickListener() { /** * Þegar smellt er á nei takkan glóir hann i 3 sekundur * @param v er view */ @Override public void onClick(View v) { final ImageButton neibutt; neibutt = (ImageButton) findViewById(R.id.nei); new CountDownTimer(3000,1000){ /** * breytum bakgrunni á takkanum a medan við teljum nidur * @param millisUntilFinished timi eftir */ @Override public void onTick(long millisUntilFinished){ neibutt.setBackgroundResource(R.drawable.neifoc); } /** * breytum bakgrunni á takkanum í upprunalegt astandi tegar 3 sekundur eru lidnar */ @Override public void onFinish(){ //set the new Content of your activity neibutt.setBackgroundResource(R.drawable.nei); } }.start(); } }; /** * Ef smellt er a bio takkan */ View.OnClickListener gotoBioClickListener = new View.OnClickListener() { /** * ef smellt er a bio takkan er kallad a fallid bio() * @param v view */ @Override public void onClick(View v) { bio(); } }; /** * opnar nyja gluggan bio */ private void bio(){ startActivity(new Intent(this, bio.class)); } /** * Ef smellt er a bio takkan */ View.OnClickListener gotoftaflaClickListener = new View.OnClickListener() { /** * ef smellt er a bio takkan er kallad a fallid bio() * @param v view */ @Override public void onClick(View v) { ftafla(); } }; /** * opnar nyja gluggan ftafla */ private void ftafla(){ startActivity(new Intent(this, full_blisstafla.class)); } /** * Inflate the menu; this adds items to the action bar if it is present. * @param menu Menu * @return true */ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.nothafi1, menu); return true; } /** * Handle action bar item clicks here. The action bar will * automatically handle clicks on the Home/Up button, so long * as you specify a parent activity in AndroidManifest.xml. * @param item MenuItem * @return super.onOptionsItemSelected(item); */ @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
sbleika/Blissid
BlissAppid_git/BlissAppid/app/src/main/java/com/example/seventeen/blissappid/nothafi1.java
Java
gpl-2.0
5,549
/** * */ package com.ankamagames.dofus.harvey.engine.numeric.bytes.sets.classes; import java.util.List; import com.ankamagames.dofus.harvey.engine.common.sets.classes.AbstractIntervalBridge; import com.ankamagames.dofus.harvey.engine.common.sets.classes.SplitOnRangeBridge; import com.ankamagames.dofus.harvey.engine.numeric.bytes.sets.classes.toolboxes.ByteBoundComparisonToolbox; import com.ankamagames.dofus.harvey.engine.numeric.bytes.sets.classes.toolboxes.ByteEqualityToolbox; import com.ankamagames.dofus.harvey.engine.numeric.bytes.sets.classes.toolboxes.ByteIntervalCreationToolbox; import com.ankamagames.dofus.harvey.numeric.bytes.sets.classes.ByteInterval; import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.IByteBound; import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.IByteInterval; import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.IByteSet; import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.IElementaryByteSet; import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.IEmptyByteSet; import com.ankamagames.dofus.harvey.numeric.bytes.sets.interfaces.ISimpleByteSet; import org.eclipse.jdt.annotation.NonNullByDefault; /** * @author sgros * */ @NonNullByDefault public class ByteIntervalBridge<Bridged extends ByteInterval> extends AbstractIntervalBridge<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, IByteInterval, IEmptyByteSet, Bridged> { protected ByteBoundComparisonToolbox<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, Bridged> _boundToolbox; protected ByteIntervalCreationToolbox<Bridged> _creationToolbox; protected ByteEqualityToolbox<IByteSet, ISimpleByteSet, IElementaryByteSet, Bridged> _equalityToolbox; protected SplitOnRangeBridge<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, IByteInterval, IEmptyByteSet, Bridged> _splitBridge; public ByteIntervalBridge(final Bridged bridged) { super(bridged); _boundToolbox = new ByteBoundComparisonToolbox<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, Bridged>(_bridged); _creationToolbox = new ByteIntervalCreationToolbox<Bridged>(_bridged); _equalityToolbox = new ByteEqualityToolbox<IByteSet, ISimpleByteSet, IElementaryByteSet, Bridged>(_bridged); _splitBridge = new SplitOnRangeBridge<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, IByteInterval, IEmptyByteSet, Bridged>(_bridged, _creationToolbox); } @Override protected SplitOnRangeBridge<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, IByteInterval, IEmptyByteSet, Bridged> getSplitBridge() { return _splitBridge; } @Override protected ByteBoundComparisonToolbox<IByteBound, IByteSet, ISimpleByteSet, IElementaryByteSet, Bridged> getBoundComparisonToolbox() { return _boundToolbox; } @Override protected ByteIntervalCreationToolbox<Bridged> getSetCreationToolbox() { return _creationToolbox; } @Override protected ByteEqualityToolbox<IByteSet, ISimpleByteSet, IElementaryByteSet, Bridged> getEqualityToolbox() { return _equalityToolbox; } public List<? extends IByteSet> split(final byte[] values, final boolean[] isIntervalStart) { return getSetCreationToolbox().split(values, isIntervalStart); } @Override public boolean isEmpty() { final IByteBound lowerBound = _bridged.getLowerBound(); final IByteBound upperBound = _bridged.getUpperBound(); if(lowerBound == null || upperBound == null) return true; return (lowerBound.getValue() - upperBound.getValue())>0; } @Override public IByteSet unite(final IByteSet set) { return super.unite(set).getAsSet(); } @Override public IByteSet intersect(final IByteSet set) { return super.intersect(set).getAsSet(); } }
Ankama/harvey
src/com/ankamagames/dofus/harvey/engine/numeric/bytes/sets/classes/ByteIntervalBridge.java
Java
gpl-2.0
3,714
using System; using System.Collections; using Server; using Server.Mobiles; using Server.Items; using Server.Gumps; using MC = Server.MegaSpawnerSystem.MasterControl; namespace Server.MegaSpawnerSystem { public class RemoveEmptySpawnersGump : Gump { private ArrayList ArgsList = new ArrayList(); private string FileName; private ArrayList MSGCheckBoxesList = new ArrayList(); private ArrayList PersonalConfigList = new ArrayList(); private StyleType StyleTypeConfig; private BackgroundType BackgroundTypeConfig; private TextColor DefaultTextColor, TitleTextColor; private string MessagesTitle, Messages; private string defaultTextColor, titleTextColor; private Mobile gumpMobile; public static void Initialize() { string helpDesc = "That plug-in will remove all spawners that do not have any entries."; MC.RegisterPlugIn( new MC.OnCommand( RemoveEmptySpawners ), "RemoveEmptySpawners", "Remove All Empty Spawners", helpDesc ); } public static void RemoveEmptySpawners( Mobile mobile, ArrayList argsList ) { mobile.SendGump( new RemoveEmptySpawnersGump( mobile, argsList ) ); } public RemoveEmptySpawnersGump( Mobile mobile, ArrayList argsList ) : base( 0,0 ) { gumpMobile = mobile; ArgsList = argsList; GetArgsList(); GetTextColors(); AddPage(0); // Page 0 MC.DisplayStyle( this, StyleTypeConfig, 180, 180, 380, 110 ); MC.DisplayBackground( this, BackgroundTypeConfig, 200, 200, 340, 40 ); MC.DisplayBackground( this, BackgroundTypeConfig, 200, 250, 340, 20 ); AddHtml( 221, 181, 320, 20, MC.ColorText( titleTextColor, "Confirmation Of Deleting Empty Spawners" ), false, false ); AddHtml( 201, 201, 340, 40, MC.ColorText( defaultTextColor, "Are you sure you want to delete all empty spawners on the entire server?" ), false, false ); AddHtml( 491, 251, 60, 20, MC.ColorText( defaultTextColor, "Cancel" ), false, false ); AddButton( 450, 250, 4017, 4019, 0, GumpButtonType.Reply, 0 ); AddHtml( 241, 251, 60, 20, MC.ColorText( defaultTextColor, "Ok" ), false, false ); AddButton( 200, 250, 4023, 4025, 1, GumpButtonType.Reply, 0 ); } public override void OnResponse( Server.Network.NetState sender, RelayInfo info ) { switch ( info.ButtonID ) { case 0: // Close Gump { MessagesTitle = "Delete Empty Spawners"; Messages = "You have chosen not to delete all empty spawners on the entire server."; SetArgsList(); gumpMobile.SendGump( new PlugInsGump( gumpMobile, ArgsList ) ); break; } case 1: // Delete Empty Spawners { int count = 0; for ( int i = 0; i < MC.SpawnerList.Count; i++ ) { MegaSpawner megaSpawner = (MegaSpawner) MC.SpawnerList[i]; if ( megaSpawner.EntryList.Count == 0 ) { count++; megaSpawner.Delete(); } } MessagesTitle = "Delete Empty Spawners"; if ( count > 0 ) Messages = String.Format( "{0} empty Mega Spawner{1} been deleted.", count, count == 1 ? " has" : "s have" ); else Messages = "There are no empty Mega Spawners on the entire server."; SetArgsList(); ArgsList[34] = (bool) true; // RefreshSpawnerLists gumpMobile.SendGump( new PlugInsGump( gumpMobile, ArgsList ) ); break; } } } private void SetArgsList() { ArgsList[2] = MessagesTitle; ArgsList[4] = Messages; ArgsList[13] = MSGCheckBoxesList; } private void GetArgsList() { MessagesTitle = (string) ArgsList[2]; Messages = (string) ArgsList[4]; MSGCheckBoxesList = (ArrayList) ArgsList[13]; PersonalConfigList = (ArrayList) ArgsList[28]; StyleTypeConfig = (StyleType) PersonalConfigList[0]; BackgroundTypeConfig = (BackgroundType) PersonalConfigList[1]; DefaultTextColor = (TextColor) PersonalConfigList[4]; TitleTextColor = (TextColor) PersonalConfigList[5]; } private void GetTextColors() { defaultTextColor = MC.GetTextColor( DefaultTextColor ); titleTextColor = MC.GetTextColor( TitleTextColor ); } } }
alucardxlx/kaltar
Mega Spawner/Plug-Ins/RemoveEmptySpawnersGump.cs
C#
gpl-2.0
4,208
package com.frm.bdTask.controls; /** * @author: Larry Pham. * @since: 3/24/2014. * @version: 2014.03.24. */ public class ListTodosActivityControl { }
PhamPhi/birdy_task
src/com/frm/bdTask/controls/ListTodosActivityControl.java
Java
gpl-2.0
155
<?php prado::using ('Application.pages.s.report.MainPageReports'); class ReportDT1 extends MainPageReports { public function onLoad ($param) { parent::onLoad ($param); $this->showLokasi=true; $this->showDT1=true; $this->createObjFinance(); $this->createObjKegiatan(); if (!$this->IsPostBack&&!$this->IsCallBack) { $this->toolbarOptionsBulanRealisasi->Enabled=false; $this->toolbarOptionsTahunAnggaran->DataSource=$this->TGL->getYear(); $this->toolbarOptionsTahunAnggaran->Text=$this->session['ta']; $this->toolbarOptionsTahunAnggaran->dataBind(); if (isset($_SESSION['currentPageReportDT1']['datakegiatan']['iddt1'])) { $this->detailProcess(); }else { if (!isset($_SESSION['currentPageReportDT1'])||$_SESSION['currentPageReportDT1']['page_name']!='s.report.ReportDT1') { $_SESSION['currentPageReportDT1']=array('page_name'=>'s.report.ReportDT1','page_num'=>0,'datakegiatan'=>array()); } $this->literalHeader->Text='Laporan Kegiatan Berdasarkan Daerah Tingkat I '; $this->populateData (); } } } public function changeTahunAnggaran ($sender,$param) { if (isset($_SESSION['currentPageReportDT1']['datakegiatan']['iddt1'])) { $this->idProcess='view'; $_SESSION['ta']=$this->toolbarOptionsTahunAnggaran->Text; $this->contentReport->Text=$this->printContent(); }else { $_SESSION['ta']=$this->toolbarOptionsTahunAnggaran->Text; $this->populateData(); } } protected function populateData () { $ta=$this->session['ta']; $str = 'SELECT iddt1,nama_dt1 FROM dt1 ORDER BY dt1.iddt1 ASC'; $this->DB->setFieldTable(array('iddt1','nama_dt1')); $r=$this->DB->getRecord($str); $result=array(); $str = "SELECT idlok,COUNT(idproyek) AS jumlah_proyek,SUM(nilai_pagu) AS nilai_pagu FROM proyek WHERE ket_lok='dt1' AND tahun_anggaran=$ta GROUP BY idlok ORDER BY idlok ASC"; $this->DB->setFieldTable(array('idlok','jumlah_proyek','nilai_pagu')); $kegiatan=$this->DB->getRecord($str); while (list($k,$v)=each($r)) { $jumlah_kegiatan=0; $nilai_pagu=0; foreach ($kegiatan as $lokasi) { if ($lokasi['idlok']==$v['iddt1']) { $jumlah_kegiatan=$lokasi['jumlah_proyek']; $nilai_pagu=$this->finance->toRupiah($lokasi['nilai_pagu']); break; } } $v['jumlah_kegiatan']=$jumlah_kegiatan; $v['nilai_pagu']=$nilai_pagu; $result[$k]=$v; } $this->RepeaterS->DataSource=$result; $this->RepeaterS->dataBind(); } public function viewRecord($sender,$param) { $iddt1=$this->getDataKeyField($sender, $this->RepeaterS); $str = "SELECT iddt1,nama_dt1 FROM dt1 WHERE iddt1=$iddt1"; $this->DB->setFieldTable(array('iddt1','nama_dt1')); $r=$this->DB->getRecord($str); $_SESSION['currentPageReportDT1']['datakegiatan']=$r[1]; $this->redirect('s.report.ReportDT1'); } public function detailProcess () { $this->idProcess='view'; $datalokasi=$_SESSION['currentPageReportDT1']['datakegiatan']; $this->literalHeader->Text="Daftar Kegiatan di {$datalokasi['nama_dt1']} "; $this->contentReport->Text=$this->printContent(); } /** * digunakan untuk mendapatkan nilai total pagu untuk satu unit * */ private function getTotalNilaiPaguUnit ($idunit,$ta) { $iddt1=$_SESSION['currentPageReportDT1']['datakegiatan']['iddt1']; $str = "SELECT SUM(p.nilai_pagu) AS total FROM proyek p,program pr WHERE p.idprogram=pr.idprogram AND pr.idunit='$idunit' AND pr.tahun='$ta' AND ket_lok='dt1' AND idlok=$iddt1"; $this->DB->setFieldTable (array('total')); $r=$this->DB->getRecord($str); if (isset($r[1])) return $r[1]['total']; else return 0; } /** * * total fisik satu proyek, tahun, bulan penggunaan */ private function getTotalFisik ($idproyek,$tahun) { $str = "SELECT SUM(fisik) AS total FROM v_laporan_a WHERE tahun_penggunaan='$tahun' AND idproyek='$idproyek'"; $this->DB->setFieldTable (array('total')); $r=$this->DB->getRecord($str); if (isset($r[1])) return $r[1]['total']; else return 0; } /** * * jumlah realisasi satu proyek, tahun, bulan penggunaan */ private function getJumlahFisik ($idproyek,$tahun) { $str = "SELECT COUNT(realisasi) AS total FROM v_laporan_a WHERE tahun_penggunaan='$tahun' AND idproyek='$idproyek'"; $this->DB->setFieldTable (array('total')); $r=$this->DB->getRecord($str); if (isset($r[1])) return $r[1]['total']; else return 0; } public function printContent () { $datalokasi=$_SESSION['currentPageReportDT1']['datakegiatan']; $idunit=$this->idunit; $ta=$this->session['ta']; $this->DB->setFieldTable (array('idprogram','kode_program','nama_program')); $str = "SELECT idprogram,kode_program,nama_program FROM program WHERE idunit='$idunit' AND tahun='$ta'"; //daftar program pada unit $daftar_program=$this->DB->getRecord($str); $content="<p class=\"msg info\"> Belum ada program pada tahun anggaran $ta.</p>"; if (isset($daftar_program[1])) { //total pagu satu unit $totalPaguUnit = $this->getTotalNilaiPaguUnit ($idunit,$ta); if ($totalPaguUnit > 0) { $content= '<table class="list" style="font-size:9px"> <thead> <tr> <th rowspan="4" class="center">NO</th> <th rowspan="4" width="350" class="center">PROGRAM/KEGIATAN</th> <th rowspan="4" class="center">SUMBER<br />DANA</th> <th rowspan="4" class="center">PAGU DANA</th> <th rowspan="4" class="center">BOBOT</th> <th colspan="5" class="center">REALISASI</th> <th rowspan="2" colspan="2" class="center">SISA ANGGARAN</th> </tr> <tr> <th colspan="2" class="center">FISIK</th> <th colspan="3" class="center">KEUANGAN</th> </tr> <tr> <th class="center">% per</th> <th class="center">% per</th> <th rowspan="2" class="center">(Rp)</th> <th class="center">% per</th> <th class="center">% per</th> <th rowspan="2" class="center">(Rp)</th> <th rowspan="2" class="center">(%)</th> </tr> <tr> <th class="center">kegiatan</th> <th class="center">SPPD</th> <th class="center">kegiatan</th> <th class="center">SPPD</th> </tr> <tr> <th class="center">1</th> <th class="center">2</th> <th class="center">3</th> <th class="center">4</th> <th class="center">5</th> <th class="center">6</th> <th class="center">7</th> <th class="center">8</th> <th class="center">9</th> <th class="center">10</th> <th class="center">11</th> <th class="center">12</th> </tr> </thead><tbody>'; $no_huruf=ord('a'); $totalRealisasiKeseluruhan=0; $totalPersenRealisasiPerSPPD='0.00'; $totalSisaAnggaran=0; $jumlah_kegiatan=0; while (list($k,$v)=each($daftar_program)) { $idprogram=$v['idprogram']; $this->DB->setFieldTable(array('idproyek','nama_proyek','nilai_pagu','sumber_anggaran','idlok','ket_lok')); $str = "SELECT p.idproyek,p.nama_proyek,p.nilai_pagu,p.sumber_anggaran,idlok,ket_lok FROM proyek p WHERE idprogram='$idprogram' AND ket_lok='dt1' AND idlok='{$datalokasi['iddt1']}'"; $daftar_kegiatan = $this->DB->getRecord($str); if (isset($daftar_kegiatan[1])) { $totalpagueachprogram=0; foreach ($daftar_kegiatan as $eachprogram) { $totalpagueachprogram+=$eachprogram['nilai_pagu']; } $totalpagueachprogram=$this->finance->toRupiah($totalpagueachprogram,'tanpa_rp'); $content.= '<tr> <td class="center"><strong>'.chr($no_huruf).'</strong></td> <td class="left"><strong>'.$v['nama_program'].'</strong></td> <td class="left">&nbsp;</td> <td class="right"><strong>'.$totalpagueachprogram.'</strong></td> <td class="left">&nbsp;</td> <td class="left">&nbsp;</td> <td class="left">&nbsp;</td> <td class="left">&nbsp;</td> <td class="left">&nbsp;</td> <td class="left">&nbsp;</td> <td class="left">&nbsp;</td> <td class="left">&nbsp;</td> </tr>'; $no=1; while (list($m,$n)=each($daftar_kegiatan)) { $idproyek=$n['idproyek']; $content.= '<tr>'; $content.= '<td class="center">'.$n['no'].'</td>'; $content.= '<td class="left">'.$n['nama_proyek'].'</td>'; $content.= '<td class="center">'.$n['sumber_anggaran'].'</td>'; $nilai_pagu_proyek=$n['nilai_pagu']; $rp_nilai_pagu_proyek=$this->finance->toRupiah($nilai_pagu_proyek,'tanpa_rp'); $content.= "<td class=\"right\">$rp_nilai_pagu_proyek</td>"; $persen_bobot=number_format(($nilai_pagu_proyek/$totalPaguUnit)*100,2); $totalPersenBobot+=$persen_bobot; $content.= "<td class=\"center\">$persen_bobot</td>"; $str = "SELECT SUM(realisasi) AS total FROM v_laporan_a WHERE idproyek=$idproyek AND tahun_penggunaan='$ta'"; $this->DB->setFieldTable(array('total')); $realisasi=$this->DB->getRecord($str); $persen_fisik='0.00'; $persenFisikPerSPPD='0.00'; $totalrealisasi=0; $persen_realisasi='0.00'; $persenRealisasiPerSPPD='0.00'; $sisa_anggaran=0; $persen_sisa_anggaran='0.00'; if ($realisasi[1]['total'] > 0 ){ //fisik $totalFisikSatuProyek=$this->getTotalFisik($idproyek,$ta); $jumlahRealisasiFisikSatuProyek=$this->getJumlahFisik ($idproyek,$ta); $persen_fisik=number_format(($totalFisikSatuProyek/$jumlahRealisasiFisikSatuProyek),2); $totalPersenFisik+=$persen_fisik; $persenFisikPerSPPD=number_format(($persen_fisik/100)*$persen_bobot,2); $totalPersenFisikPerSPPD+=$persenFisikPerSPPD; $totalrealisasi=$realisasi[1]['total']; $totalRealisasiKeseluruhan+=$totalrealisasi; $persen_realisasi=number_format(($totalrealisasi/$nilai_pagu_proyek)*100,2); $totalPersenRealisasi+=$persen_realisasi; $persenRealisasiPerSPPD=number_format(($persen_realisasi/100)*$persen_bobot,2); $totalPersenRealisasiPerSPPD+=$persenRealisasiPerSPPD; $sisa_anggaran=$nilai_pagu_proyek- $totalrealisasi; $persen_sisa_anggaran=number_format(($sisa_anggaran/$totalPaguUnit)*100,2); $totalPersenSisaAnggaran+=$persen_sisa_anggaran; $totalSisaAnggaran+=$sisa_anggaran; } $content.= '<td class="center">'.$persen_fisik.'</td>'; $content.= '<td class="center">'.$persenFisikPerSPPD.'</td>'; $content.= '<td class="right">'.$this->finance->toRupiah($totalrealisasi,'tanpa_rp').'</td>'; $content.= '<td class="center">'.$persen_realisasi.'</td>'; $content.= '<td class="center">'.$persenRealisasiPerSPPD.'</td>'; $content.= '<td class="right">'.$this->finance->toRupiah($sisa_anggaran,'tanpa_rp').'</td>'; $content.= '<td class="center">'.$persen_sisa_anggaran.'</td>'; $content.='</tr>'; $no++; $jumlah_kegiatan++; } $no_huruf++; } } $rp_total_pagu_unit=$this->finance->toRupiah($totalPaguUnit,'tanpa_rp'); $totalPersenBobot=number_format($totalPersenBobot); $rp_total_realisasi_keseluruhan=$this->finance->toRupiah($totalRealisasiKeseluruhan,'tanpa_rp'); if ($totalPersenRealisasi > 0) $totalPersenRealisasi=number_format(($totalPersenRealisasi/$jumlah_kegiatan),2); if ($totalPersenSisaAnggaran > 0) $totalPersenSisaAnggaran=number_format(($totalPersenSisaAnggaran/$jumlah_kegiatan),2); $totalPersenFisik=number_format($totalPersenFisik/$jumlah_kegiatan,2); $totalPersenRealisasiPerSPPD=number_format($totalPersenRealisasiPerSPPD,2); $totalPersenFisikPerSPPD=number_format($totalPersenFisikPerSPPD,2); $rp_total_sisa_anggaran=$this->finance->toRupiah($totalSisaAnggaran,'tanpa_rp'); $content.= '<tr> <td colspan="2" class="right"><strong>Jumlah</strong></td> <td class="left"></td> <td class="right">'.$rp_total_pagu_unit.'</td> <td class="center">'.$totalPersenBobot.'</td> <td class="center">'.$totalPersenFisik.'</td> <td class="center">'.$totalPersenFisikPerSPPD.'</td> <td class="right">'.$rp_total_realisasi_keseluruhan.'</td> <td class="center">'.$totalPersenRealisasi.'</td> <td class="center">'.$totalPersenRealisasiPerSPPD.'</td> <td class="right">'.$rp_total_sisa_anggaran.'</td> <td class="center">'.$totalPersenSisaAnggaran.'</td> </tr>'; $content.='</tbody></table>'; } } return $content; } public function printOut ($sender,$param) { $this->idProcess='view'; $this->createObjReport(); $this->report->dataKegiatan=$_SESSION['currentPageReportDT1']['datakegiatan']; $this->report->dataKegiatan['idunit']=$this->idunit; $this->report->dataKegiatan['tahun']=$_SESSION['ta']; $this->report->dataKegiatan['userid']=$this->userid; $this->report->dataKegiatan['tipe_lokasi']='dt1'; $filetype=$this->cmbTipePrintOut->Text; switch($filetype) { case 'excel2003' : $this->report->setMode('excel2003'); $this->report->printLokasi($this->linkOutput); break; case 'excel2007' : $this->report->setMode('excel2007'); $this->report->printLokasi($this->linkOutput); break; } } public function close($sender,$param) { unset($_SESSION['currentPageReportDT1']); $this->redirect('s.report.ReportDT1'); } } ?>
ibnoe/simonev
protected/pages/s/report/ReportDT1.php
PHP
gpl-2.0
18,291
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package datagen.engine; import java.util.ArrayList; /** * * @author juan.garson */ public class Table { private final ArrayList<Column> columns; private final String name; private int count; private final ArrayList<String> reference; public Table(String name){ this.name = name; columns = new ArrayList<>(); reference = new ArrayList<>(); } public Column getColumn(String name){ Column response; try{ response = null; for(Column column: columns){ if(column.field.equals(name)){ response = column; break; } } }catch(Exception e){ response = null; } return response; } public String[] getRow(int position){ String[] response; try{ response = new String[columns.size()]; for(int i=0;i<columns.size();i++){ response[i] = columns.get(i).gen[position]; } }catch(Exception e){ System.err.println(e.getMessage()); response = null; } return response; } public boolean hasReferences(){ return reference.size() > 0; } public ArrayList<String> getReferences(){ return reference; } public void addColumn(Column column){ columns.add(column); } public String getName(){ return name; } public void setCount(int count){ this.count = count; } public int getCount(){ return count; } public ArrayList<Column> getColumns(){ return columns; } /*@Override public String toString() { StringBuilder builder; builder = new StringBuilder(); builder.append("Table : "); builder.append(name); builder.append("\n"); for(Column col : columns){ builder.append(col.toString()); builder.append("\n"); } return builder.toString(); }*/ @Override public String toString() { return name; } }
lanstat/DataGen
src/datagen/engine/Table.java
Java
gpl-2.0
2,373
############################################################# # Signal.rb # # Copyright (c) 2002 Phil Tomson # released under the GNU General Public License (GPL) # ################################################## ####################################################### # add a bin method to the built-in String class # converts a String composed of '1's and '0's to binary # (note: won't be needed in Ruby 1.7/1.8 # ##################################################### class String def bin val = self.strip pattern = /^([+-]?)(0b)?([01]+)(.*)$/ parts = pattern.match(val) return 0 if not parts sign = parts[1] num = parts[3] eval(sign+"0b"+num) end end ##################################################### # add a 'inv' method to the built-in Fixnum class # ##################################################### class Fixnum def inv binary = sprintf("%b",self) #get a binary representation of 'self' ones = '1'*binary.length #create a string of '1's the length of binary self ^ ones.bin #invert by XOR'ing with ones end end module RHDL ############################################################### # Signal - ############################################################### class Signal @@signalList = []#everytime we create a new signal we add it to this list @@deltaEvents = true attr_reader :valObj, :next_value, :event attr_writer :event def Signal.update_all @@signalList.each {|signal| signal.update } end def Signal.deltaEvents? @@deltaEvents end def Signal.clear_deltaEvents @@deltaEvents = false end def Signal.set_deltaEvents @@deltaEvents = true end def inspect @valObj.inspect end def value #was: #self.inspect #TODO: should it just be: @valObj @valObj end def value=(n) @valObj.assign(n) end #TODO: do we need Signal.clear_events ? def Signal.clear_events @@signalList.each { |signal| signal.event = false } end def type @valObj.class end def rising_edge event && value == '1' end def falling_edge event && value == '0' end #signals have history def initialize(valObj,width = 1) @valObj = valObj @@signalList << self @eventQueue = [] @event = false @next_value = nil end ####The old assign_at and assign methods:############## # define a driver function for this signal: #def assign_at (relTime=0,function=nil) # #schedule an event # nextValue = case function # when nil # Proc.new.call # when Proc # function.call # when Signal # proc{function.to_s}.call # else # function # end # @eventQueue[relTime] = nextValue # nextValInQueue = @eventQueue.shift # @next_value = nextValInQueue if nextValInQueue #end # #def assign(function=nil) # if function # assign_at(0,function) # else # assign_at(0,Proc.new) # end #end ####################################################### def call proc{self.to_s}.call end #.... def assign_at (relTime=0,nextValue=Proc.new) nextValue = nextValue.call if nextValue.respond_to? :call ###Experimental#### if(relTime < @eventQueue.length) @eventQueue.clear @eventQueue[0] = nextValue else @eventQueue[relTime] = nextValue end #@eventQueue[relTime] = nextValue if @@deltaEvents nextValInQueue = @eventQueue[0] #nextValInQueue = @eventQueue.shift else nextValInQueue = @eventQueue.shift end ###\Experimental#### puts "nextValInQueue: #{nextValInQueue}" if $DEBUG puts "@eventQueue:" if $DEBUG puts @eventQueue if $DEBUG @next_value = nextValInQueue if nextValInQueue != nil end def assign(nextValue=Proc.new) puts "assign #{nextValue}" if $DEBUG assign_at(0,nextValue) end #deprecated: #def <<(nextValue=Proc.new) # self.assign(nextValue) #end ########################################### # <= means assignment, not les-than-or-equal ########################################### def <=(nextValue=Proc.new) self.assign(nextValue) end ########################################### # less-than-or-equal (since we can't use <= anymore ) # ######################################### def lte(other) if other.class == Signal @valObj <= other.value else @valObj <= other end end ########################################## # greater-than-or-equal # ######################################## def gte(other) if other.class == Signal @valObj >= other.value else @valObj >= other end end #was commented: def method_missing(methID,*args) puts "methID is: #{methID}, args are: #{args}" if $DEBUG case methID when :+,:-,:*,:==,:===,:<=>,:>,:<,:or,:and,:^,:&,:|,:xor other = args[0] if other.class == Signal @valObj.send(methID,other.value) else @valObj.send(methID,other) end else @valObj.send(methID,*args) end end def to_s @valObj.to_s end def update puts "update: next_value = #@next_value current value = #{@valObj.inspect}" if $DEBUG puts "update: next_value = #@next_value current value = #{@valObj}" if $DEBUG puts "update: next_value.class = #{@next_value.class} current value.class = #{@valObj.class}" if $DEBUG #TODO: what about using 'inspect' to determine values for events? #was:if @next_value && @next_value.to_s != @valObj.inspect.to_s #if changed if @next_value && @valObj != @next_value #if changed puts "update: #{@next_value.to_s} #{valObj.inspect.to_s}" if $DEBUG puts "update: #{@next_value} #{valObj}" if $DEBUG puts "update: class:#{@next_value.class}!= #{@valObj.class}" if @next_value.class != @valObj.class if $DEBUG @event = true @@deltaEvents = true else @event = false end if @next_value if @valObj.respond_to?(:assign) @valObj.assign(@next_value) else @valObj = @next_value end end puts "update value is now: #@valObj" if $DEBUG end def coerce(other) puts "coersion called! other is: #{other}, other.class is: #{other.class}" case other when Fixnum #return [ Signal.new(other), self.value.to_i] return [ other, self.value.to_i] when String puts "Coerce String!!!!!!" return [ Signal(BitVector(other)), self] end end #the '==' that comes with all objects must be overridden def ==(other) if other.class == Signal @valObj == other.value else @valObj == other end end #NOTE: commented to try coerce #def ===(other) # puts "Signal::===" if $DEBUG # @valObj === other #end end def Signal(val,width=1) Signal.new(val,width) end end #RHDL if $0 == __FILE__ require 'Bit' include RHDL require "test/unit" puts "Test Signal" class Testing_Signal < Test::Unit::TestCase def setup @a_bit = Signal(Bit('1')) @b_bit = Signal(Bit('1')) @c_bit = Signal(Bit()) @counter = Signal(0) @a_bv = Signal(BitVector('1010')) @b_bv = Signal(BitVector('0101')) @c_bv = Signal(BitVector('XXXX')) end def test_add_bit @c_bit <= @a_bit + @b_bit @c_bit.update assert_equal(1, @c_bit) end def test_inv_bit @a_bit <= @a_bit.inv @a_bit.update assert_equal(0, @a_bit) end def test_compare_bv assert_not_equal(@a_bv, @b_bv) assert( @a_bv > @b_bv ) #compare with a string literal: assert( @a_bv > '0000') #compare with an integer: assert( @a_bv < 22 ) assert( @a_bv == 0b1010 ) assert( @a_bv.lte(0b1010) ) assert( @a_bv.gte(@b_bv )) end def test_add_bv @c_bv <= (@a_bv + @b_bv) @c_bv.update puts "@c_bv.value.class is: #{@c_bv.value.class}" #assert_equal( @c_bv, '1111') assert_equal( '1111', @c_bv.value.to_s) #try adding a literal to a Signal: @c_bv <= ( @c_bv + '0001' ) @c_bv.update assert_equal( '0000', @c_bv.value.to_s ) #try adding a BitVector to a BitVector Signal: @c_bv <= ( @c_bv + BitVector.new('1000')) @c_bv.update assert_equal( '1000', @c_bv.value.to_s ) #try adding an integer to a BitVector Signal: @c_bv <= ( @c_bv + 1 ) @c_bv.update assert_equal( '1001', @c_bv.value.to_s ) #try adding a Signal(BitVector) to an integer: @c_bv <= ( 1 + @c_bv ) @c_bv.update assert_equal( '1010', @c_bv.value.to_s ) #try adding a Bitvector to a Signal: @c_bv <= (@c_bv + BitVector('0011') ) @c_bv.update assert_equal( '1101', @c_bv.value.to_s ) #NOTE: the following doesn't work and probably won't ever #try adding Signal to string literal (which represents BitVector): #@c_bv <= ('0010' + @c_bv) #@c_bv.update #assert_equal( '1111', @c_bv.value.to_s ) end def test_reassignment_options @a_bit <= 0 @a_bit.update assert_equal(0, @a_bit) @a_bit <= '1' @a_bit.update assert_equal(1, @a_bit) @c_bv <= '0000' @c_bv.update assert_equal(RHDL::Signal, @c_bv.class) assert_equal(BitVector, @c_bv.value.class ) assert_equal('0000', @c_bv.value.to_s) end def test_integer_signal @counter <= @counter + 1 @counter.update assert_equal(1, @counter) #try adding two signals: val = Signal( 1 ) @counter <= @counter + val @counter.update assert_equal(2, @counter) end end if false c0 = 0 #Integer a = Signal(Bit('1')) b = Signal(Bit('1')) c = Signal(Bit()) c <= (a + b) c.update if c == '1' puts "yes" end counter = Signal(c0) counter.<<(counter + 1) counter.update puts counter.inspect puts c counter.assign(counter + 8) counter.update puts counter.inspect counter.assign(counter & 5) counter.update puts counter.inspect counter.assign(counter * 0b0101) counter.update puts counter.inspect counter.assign(counter ^ 0xF) counter.update puts counter.inspect if c == '1' puts "yes" end end end
philtomson/RHDL
lib/hardware/RHDL/Signal.rb
Ruby
gpl-2.0
10,266
#!/usr/bin/python # -*- encoding: utf-8; py-indent-offset: 4 -*- # +------------------------------------------------------------------+ # | ____ _ _ __ __ _ __ | # | / ___| |__ ___ ___| | __ | \/ | |/ / | # | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / | # | | |___| | | | __/ (__| < | | | | . \ | # | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ | # | | # | Copyright Mathias Kettner 2014 mk@mathias-kettner.de | # +------------------------------------------------------------------+ # # This file is part of Check_MK. # The official homepage is at http://mathias-kettner.de/check_mk. # # check_mk 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 in version 2. check_mk is distributed # in the hope that it will be useful, but WITHOUT ANY WARRANTY; with- # out even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. See the GNU General Public License for more de- # tails. You should have received a copy of the GNU General Public # License along with GNU Make; see the file COPYING. If not, write # to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, # Boston, MA 02110-1301 USA. import utils import config, time, os, re, pprint import hashlib import weblib, traceback, forms, valuespec, inventory, visuals, metrics import sites import bi import inspect import livestatus from log import logger from gui_exceptions import MKGeneralException, MKUserError, MKInternalError import cmk.paths # Datastructures and functions needed before plugins can be loaded loaded_with_language = False display_options = None # Load all view plugins def load_plugins(force): global loaded_with_language if loaded_with_language == current_language and not force: # always reload the hosttag painters, because new hosttags might have been # added during runtime load_host_tag_painters() clear_alarm_sound_states() return global multisite_datasources ; multisite_datasources = {} global multisite_layouts ; multisite_layouts = {} global multisite_painters ; multisite_painters = {} global multisite_sorters ; multisite_sorters = {} global multisite_builtin_views ; multisite_builtin_views = {} global multisite_painter_options ; multisite_painter_options = {} global multisite_commands ; multisite_commands = [] global multisite_command_groups ; multisite_command_groups = {} global view_hooks ; view_hooks = {} global inventory_displayhints ; inventory_displayhints = {} config.declare_permission_section("action", _("Commands on host and services"), do_sort = True) utils.load_web_plugins("views", globals()) load_host_tag_painters() clear_alarm_sound_states() # This must be set after plugin loading to make broken plugins raise # exceptions all the time and not only the first time (when the plugins # are loaded). loaded_with_language = current_language # Declare permissions for builtin views config.declare_permission_section("view", _("Multisite Views"), do_sort = True) for name, view in multisite_builtin_views.items(): config.declare_permission("view.%s" % name, format_view_title(view), "%s - %s" % (name, _u(view["description"])), config.builtin_role_ids) # Make sure that custom views also have permissions config.declare_dynamic_permissions(lambda: visuals.declare_custom_permissions('views')) declare_inventory_columns() # Load all views - users or builtins def load_views(): global multisite_views, available_views # Skip views which do not belong to known datasources multisite_views = visuals.load('views', multisite_builtin_views, skip_func = lambda v: v['datasource'] not in multisite_datasources) available_views = visuals.available('views', multisite_views) transform_old_views() def permitted_views(): try: return available_views except: # In some cases, for example when handling AJAX calls the views might # have not been loaded yet load_views() return available_views def all_views(): return multisite_views # Convert views that are saved in the pre 1.2.6-style # FIXME: Can be removed one day. Mark as incompatible change or similar. def transform_old_views(): for view in multisite_views.values(): ds_name = view['datasource'] datasource = multisite_datasources[ds_name] if "context" not in view: # legacy views did not have this explicitly view.setdefault("user_sortable", True) if 'context_type' in view: # This code transforms views from user_views.mk which have been migrated with # daily snapshots from 2014-08 till beginning 2014-10. visuals.transform_old_visual(view) elif 'single_infos' not in view: # This tries to map the datasource and additional settings of the # views to get the correct view context # # This code transforms views from views.mk (legacy format) to the current format try: hide_filters = view.get('hide_filters') if 'service' in hide_filters and 'host' in hide_filters: view['single_infos'] = ['service', 'host'] elif 'service' in hide_filters and 'host' not in hide_filters: view['single_infos'] = ['service'] elif 'host' in hide_filters: view['single_infos'] = ['host'] elif 'hostgroup' in hide_filters: view['single_infos'] = ['hostgroup'] elif 'servicegroup' in hide_filters: view['single_infos'] = ['servicegroup'] elif 'aggr_service' in hide_filters: view['single_infos'] = ['service'] elif 'aggr_name' in hide_filters: view['single_infos'] = ['aggr'] elif 'aggr_group' in hide_filters: view['single_infos'] = ['aggr_group'] elif 'log_contact_name' in hide_filters: view['single_infos'] = ['contact'] elif 'event_host' in hide_filters: view['single_infos'] = ['host'] elif hide_filters == ['event_id', 'history_line']: view['single_infos'] = ['history'] elif 'event_id' in hide_filters: view['single_infos'] = ['event'] elif 'aggr_hosts' in hide_filters: view['single_infos'] = ['host'] else: # For all other context types assume the view is showing multiple objects # and the datasource can simply be gathered from the datasource view['single_infos'] = [] except: # Exceptions can happen for views saved with certain GIT versions if config.debug: raise # Convert from show_filters, hide_filters, hard_filters and hard_filtervars # to context construct if 'context' not in view: view['show_filters'] = view['hide_filters'] + view['hard_filters'] + view['show_filters'] single_keys = visuals.get_single_info_keys(view) # First get vars for the classic filters context = {} filtervars = dict(view['hard_filtervars']) all_vars = {} for filter_name in view['show_filters']: if filter_name in single_keys: continue # skip conflictings vars / filters context.setdefault(filter_name, {}) try: f = visuals.get_filter(filter_name) except: # The exact match filters have been removed. They where used only as # link filters anyway - at least by the builtin views. continue for var in f.htmlvars: # Check whether or not the filter is supported by the datasource, # then either skip or use the filter vars if var in filtervars and f.info in datasource['infos']: value = filtervars[var] all_vars[var] = value context[filter_name][var] = value # We changed different filters since the visuals-rewrite. This must be treated here, since # we need to transform views which have been created with the old filter var names. # Changes which have been made so far: changed_filter_vars = { 'serviceregex': { # Name of the filter # old var name: new var name 'service': 'service_regex', }, 'hostregex': { 'host': 'host_regex', }, 'hostgroupnameregex': { 'hostgroup_name': 'hostgroup_regex', }, 'servicegroupnameregex': { 'servicegroup_name': 'servicegroup_regex', }, 'opthostgroup': { 'opthostgroup': 'opthost_group', 'neg_opthostgroup': 'neg_opthost_group', }, 'optservicegroup': { 'optservicegroup': 'optservice_group', 'neg_optservicegroup': 'neg_optservice_group', }, 'hostgroup': { 'hostgroup': 'host_group', 'neg_hostgroup': 'neg_host_group', }, 'servicegroup': { 'servicegroup': 'service_group', 'neg_servicegroup': 'neg_service_group', }, 'host_contactgroup': { 'host_contactgroup': 'host_contact_group', 'neg_host_contactgroup': 'neg_host_contact_group', }, 'service_contactgroup': { 'service_contactgroup': 'service_contact_group', 'neg_service_contactgroup': 'neg_service_contact_group', }, } if filter_name in changed_filter_vars and f.info in datasource['infos']: for old_var, new_var in changed_filter_vars[filter_name].items(): if old_var in filtervars: value = filtervars[old_var] all_vars[new_var] = value context[filter_name][new_var] = value # Now, when there are single object infos specified, add these keys to the # context for single_key in single_keys: if single_key in all_vars: context[single_key] = all_vars[single_key] view['context'] = context # Cleanup unused attributes for k in [ 'hide_filters', 'hard_filters', 'show_filters', 'hard_filtervars' ]: try: del view[k] except KeyError: pass def save_views(us): visuals.save('views', multisite_views) # For each view a function can be registered that has to return either True # or False to show a view as context link view_is_enabled = {} def is_enabled_for(linking_view, view, context_vars): if view["name"] not in view_is_enabled: return True # Not registered are always visible! return view_is_enabled[view["name"]](linking_view, view, context_vars) #. # .--PainterOptions------------------------------------------------------. # | ____ _ _ ___ _ _ | # | | _ \ __ _(_)_ __ | |_ ___ _ __ / _ \ _ __ | |_(_) ___ _ __ ___ | # | | |_) / _` | | '_ \| __/ _ \ '__| | | | '_ \| __| |/ _ \| '_ \/ __| | # | | __/ (_| | | | | | || __/ | | |_| | |_) | |_| | (_) | | | \__ \ | # | |_| \__,_|_|_| |_|\__\___|_| \___/| .__/ \__|_|\___/|_| |_|___/ | # | |_| | # +----------------------------------------------------------------------+ # | Painter options are settings that can be changed per user per view. | # | These options are controlled throught the painter options form which | # | is accessible through the small monitor icon on the top left of the | # | views. | # '----------------------------------------------------------------------' # TODO: Better name it PainterOptions or DisplayOptions? There are options which only affect # painters, but some which affect generic behaviour of the views, so DisplayOptions might # be better. class PainterOptions(object): def __init__(self, view_name=None): self._view_name = view_name # The names of the painter options used by the current view self._used_option_names = None # The effective options for this view self._options = {} def load(self): self._load_from_config() # Load the options to be used for this view def _load_used_options(self, view): if self._used_option_names != None: return # only load once per request options = set([]) for cell in get_group_cells(view) + get_cells(view): options.update(cell.painter_options()) # Also layouts can register painter options layout_name = view.get("layout") if layout_name != None: options.update(multisite_layouts[layout_name].get("options", [])) # TODO: Improve sorting. Add a sort index? self._used_option_names = sorted(options) def _load_from_config(self): if self._is_anonymous_view(): return # never has options if not self.painter_options_permitted(): return # Options are stored per view. Get all options for all views vo = config.user.load_file("viewoptions", {}) self._options = vo.get(self._view_name, {}) def save_to_config(self): vo = config.user.load_file("viewoptions", {}, lock=True) vo[self._view_name] = self._options config.user.save_file("viewoptions", vo) def update_from_url(self, view): self._load_used_options(view) if not self.painter_option_form_enabled(): return if html.has_var("_reset_painter_options"): self._clear_painter_options() return elif html.has_var("_update_painter_options"): self._set_from_submitted_form() def _set_from_submitted_form(self): # TODO: Remove all keys that are in multisite_painter_options # but not in self._used_option_names modified = False for option_name in self._used_option_names: # Get new value for the option from the value spec vs = self.get_valuespec_of(option_name) value = vs.from_html_vars("po_%s" % option_name) if not self._is_set(option_name) or self.get(option_name) != value: modified = True self.set(option_name, value) if modified: self.save_to_config() def _clear_painter_options(self): # TODO: This never removes options that are not existant anymore modified = False for name in multisite_painter_options.keys(): try: del self._options[name] modified = True except KeyError: pass if modified: self.save_to_config() # Also remove the options from current html vars. Otherwise the # painter option form will display the just removed options as # defaults of the painter option form. for varname in html.all_varnames_with_prefix("po_"): html.del_var(varname) def get_valuespec_of(self, name): opt = multisite_painter_options[name] if type(lambda: None) == type(opt["valuespec"]): return opt["valuespec"]() else: return opt["valuespec"] def _is_set(self, name): return name in self._options # Sets a painter option value (only for this request). Is not persisted! def set(self, name, value): self._options[name] = value # Returns either the set value, the provided default value or if none # provided, it returns the default value of the valuespec. def get(self, name, dflt=None): if dflt == None: try: dflt = self.get_valuespec_of(name).default_value() except KeyError: # Some view options (that are not declared as display options) # like "refresh" don't have a valuespec. So they need to default # to None. # TODO: Find all occurences and simply declare them as "invisible" # painter options. pass return self._options.get(name, dflt) # Not falling back to a default value, simply returning None in case # the option is not set. def get_without_default(self, name): return self._options.get(name) def get_all(self): return self._options def _is_anonymous_view(self): return self._view_name == None def painter_options_permitted(self): return config.user.may("general.painter_options") def painter_option_form_enabled(self): return self._used_option_names and self.painter_options_permitted() def show_form(self, view): self._load_used_options(view) if not display_options.enabled(display_options.D) or not self.painter_option_form_enabled(): return html.open_div(id_="painteroptions", class_=["view_form"], style="display: none;") html.begin_form("painteroptions") forms.header(_("Display Options")) for name in self._used_option_names: vs = self.get_valuespec_of(name) forms.section(vs.title()) # TODO: Possible improvement for vars which default is specified # by the view: Don't just default to the valuespecs default. Better # use the view default value here to get the user the current view # settings reflected. vs.render_input("po_%s" % name, self.get(name)) forms.end() html.button("_update_painter_options", _("Submit"), "submit") html.button("_reset_painter_options", _("Reset"), "submit") html.hidden_fields() html.end_form() html.close_div() def prepare_painter_options(view_name=None): global painter_options painter_options = PainterOptions(view_name) painter_options.load() #. # .--Cells---------------------------------------------------------------. # | ____ _ _ | # | / ___|___| | |___ | # | | | / _ \ | / __| | # | | |__| __/ | \__ \ | # | \____\___|_|_|___/ | # | | # +----------------------------------------------------------------------+ # | View cell handling classes. Each cell instanciates a multisite | # | painter to render a table cell. | # '----------------------------------------------------------------------' # A cell is an instance of a painter in a view (-> a cell or a grouping cell) class Cell(object): # Wanted to have the "parse painter spec logic" in one place (The Cell() class) # but this should be cleaned up more. TODO: Move this to another place @staticmethod def painter_exists(painter_spec): if type(painter_spec[0]) == tuple: painter_name = painter_spec[0][0] else: painter_name = painter_spec[0] return painter_name in multisite_painters # Wanted to have the "parse painter spec logic" in one place (The Cell() class) # but this should be cleaned up more. TODO: Move this to another place @staticmethod def is_join_cell(painter_spec): return len(painter_spec) >= 4 def __init__(self, view, painter_spec=None): self._view = view self._painter_name = None self._painter_params = None self._link_view_name = None self._tooltip_painter_name = None if painter_spec: self._from_view(painter_spec) # In views the painters are saved as tuples of the following formats: # # Painter name, Link view name # ('service_discovery_service', None), # # Painter name, Link view name, Hover painter name # ('host_plugin_output', None, None), # # Join column: Painter name, Link view name, hover painter name, Join service description # ('service_description', None, None, u'CPU load') # # Join column: Painter name, Link view name, hover painter name, Join service description, custom title # ('service_description', None, None, u'CPU load') # # Parameterized painters: # Same as above but instead of the "Painter name" a two element tuple with the painter name as # first element and a dictionary of parameters as second element is set. def _from_view(self, painter_spec): if type(painter_spec[0]) == tuple: self._painter_name, self._painter_params = painter_spec[0] else: self._painter_name = painter_spec[0] if painter_spec[1] != None: self._link_view_name = painter_spec[1] # Clean this call to Cell.painter_exists() up! if len(painter_spec) >= 3 and Cell.painter_exists((painter_spec[2], None)): self._tooltip_painter_name = painter_spec[2] # Get a list of columns we need to fetch in order to render this cell def needed_columns(self): columns = set(get_painter_columns(self.painter())) if self._link_view_name: # Make sure that the information about the available views is present. If # called via the reporting, then this might not be the case # TODO: Move this to some better place. views = permitted_views() if self._has_link(): link_view = self._link_view() if link_view: # TODO: Clean this up here for filt in [ visuals.get_filter(fn) for fn in visuals.get_single_info_keys(link_view) ]: columns.update(filt.link_columns) if self.has_tooltip(): columns.update(get_painter_columns(self.tooltip_painter())) return columns def is_joined(self): return False def join_service(self): return None def _has_link(self): return self._link_view_name != None def _link_view(self): try: return get_view_by_name(self._link_view_name) except KeyError: return None def painter(self): return multisite_painters[self._painter_name] def painter_name(self): return self._painter_name def export_title(self): return self._painter_name def painter_options(self): return self.painter().get("options", []) # The parameters configured in the view for this painter. In case the # painter has params, it defaults to the valuespec default value and # in case the painter has no params, it returns None. def painter_parameters(self): vs_painter_params = get_painter_params_valuespec(self.painter()) if not vs_painter_params: return if vs_painter_params and self._painter_params == None: return vs_painter_params.default_value() else: return self._painter_params def title(self, use_short=True): painter = self.painter() if use_short: return painter.get("short", painter["title"]) else: return painter["title"] # Can either be: # True : Is printable in PDF # False : Is not printable at all # "<string>" : ID of a painter_printer (Reporting module) def printable(self): return self.painter().get("printable", True) def has_tooltip(self): return self._tooltip_painter_name != None def tooltip_painter_name(self): return self._tooltip_painter_name def tooltip_painter(self): return multisite_painters[self._tooltip_painter_name] def paint_as_header(self, is_last_column_header=False): # Optional: Sort link in title cell # Use explicit defined sorter or implicit the sorter with the painter name # Important for links: # - Add the display options (Keeping the same display options as current) # - Link to _self (Always link to the current frame) classes = [] onclick = '' title = '' if display_options.enabled(display_options.L) \ and self._view.get('user_sortable', False) \ and get_sorter_name_of_painter(self.painter_name()) is not None: params = [ ('sort', self._sort_url()), ] if display_options.title_options: params.append(('display_options', display_options.title_options)) classes += [ "sort", get_primary_sorter_order(self._view, self.painter_name()) ] onclick = "location.href=\'%s\'" % html.makeuri(params, 'sort') title = _('Sort by %s') % self.title() if is_last_column_header: classes.append("last_col") html.open_th(class_=classes, onclick=onclick, title=title) html.write(self.title()) html.close_th() #html.guitest_record_output("view", ("header", title)) def _sort_url(self): """ The following sorters need to be handled in this order: 1. group by sorter (needed in grouped views) 2. user defined sorters (url sorter) 3. configured view sorters """ sorter = [] group_sort, user_sort, view_sort = get_separated_sorters(self._view) sorter = group_sort + user_sort + view_sort # Now apply the sorter of the current column: # - Negate/Disable when at first position # - Move to the first position when already in sorters # - Add in the front of the user sorters when not set sorter_name = get_sorter_name_of_painter(self.painter_name()) if self.is_joined(): # TODO: Clean this up and then remove Cell.join_service() this_asc_sorter = (sorter_name, False, self.join_service()) this_desc_sorter = (sorter_name, True, self.join_service()) else: this_asc_sorter = (sorter_name, False) this_desc_sorter = (sorter_name, True) if user_sort and this_asc_sorter == user_sort[0]: # Second click: Change from asc to desc order sorter[sorter.index(this_asc_sorter)] = this_desc_sorter elif user_sort and this_desc_sorter == user_sort[0]: # Third click: Remove this sorter sorter.remove(this_desc_sorter) else: # First click: add this sorter as primary user sorter # Maybe the sorter is already in the user sorters or view sorters, remove it for s in [ user_sort, view_sort ]: if this_asc_sorter in s: s.remove(this_asc_sorter) if this_desc_sorter in s: s.remove(this_desc_sorter) # Now add the sorter as primary user sorter sorter = group_sort + [this_asc_sorter] + user_sort + view_sort p = [] for s in sorter: if len(s) == 2: p.append((s[1] and '-' or '') + s[0]) else: p.append((s[1] and '-' or '') + s[0] + '~' + s[2]) return ','.join(p) def render(self, row): row = join_row(row, self) try: tdclass, content = self.render_content(row) except: logger.exception("Failed to render painter '%s' (Row: %r)" % (self._painter_name, row)) raise if tdclass == None: tdclass = "" if tdclass == "" and content == "": return "", "" # Add the optional link to another view if content and self._has_link(): content = link_to_view(content, row, self._link_view_name) # Add the optional mouseover tooltip if content and self.has_tooltip(): tooltip_cell = Cell(self._view, (self.tooltip_painter_name(), None)) tooltip_tdclass, tooltip_content = tooltip_cell.render_content(row) tooltip_text = html.strip_tags(tooltip_content) content = '<span title="%s">%s</span>' % (tooltip_text, content) return tdclass, content # Same as self.render() for HTML output: Gets a painter and a data # row and creates the text for being painted. def render_for_pdf(self, row, time_range): # TODO: Move this somewhere else! def find_htdocs_image_path(filename): dirs = [ cmk.paths.local_web_dir + "/htdocs/", cmk.paths.web_dir + "/htdocs/", ] for d in dirs: if os.path.exists(d + filename): return d + filename try: row = join_row(row, self) css_classes, txt = self.render_content(row) if txt is None: return css_classes, "" txt = txt.strip() # Handle <img...>. Our PDF writer cannot draw arbitrary # images, but all that we need for showing simple icons. # Current limitation: *one* image if txt.lower().startswith("<img"): img_filename = re.sub('.*src=["\']([^\'"]*)["\'].*', "\\1", str(txt)) img_path = find_htdocs_image_path(img_filename) if img_path: txt = ("icon", img_path) else: txt = img_filename if isinstance(txt, HTML): txt = "%s" % txt elif not isinstance(txt, tuple): txt = html.escaper.unescape_attributes(txt) txt = html.strip_tags(txt) return css_classes, txt except Exception: raise MKGeneralException('Failed to paint "%s": %s' % (self.painter_name(), traceback.format_exc())) def render_content(self, row): if not row: return "", "" # nothing to paint painter = self.painter() paint_func = painter["paint"] # Painters can request to get the cell object handed over. # Detect that and give the painter this argument. arg_names = inspect.getargspec(paint_func)[0] painter_args = [] for arg_name in arg_names: if arg_name == "row": painter_args.append(row) elif arg_name == "cell": painter_args.append(self) # Add optional painter arguments from painter specification if "args" in painter: painter_args += painter["args"] return painter["paint"](*painter_args) def paint(self, row, tdattrs="", is_last_cell=False): tdclass, content = self.render(row) has_content = content != "" if is_last_cell: if tdclass == None: tdclass = "last_col" else: tdclass += " last_col" if tdclass: html.write("<td %s class=\"%s\">" % (tdattrs, tdclass)) html.write(content) html.close_td() else: html.write("<td %s>" % (tdattrs)) html.write(content) html.close_td() #html.guitest_record_output("view", ("cell", content)) return has_content class JoinCell(Cell): def __init__(self, view, painter_spec): self._join_service_descr = None self._custom_title = None super(JoinCell, self).__init__(view, painter_spec) def _from_view(self, painter_spec): super(JoinCell, self)._from_view(painter_spec) if len(painter_spec) >= 4: self._join_service_descr = painter_spec[3] if len(painter_spec) == 5: self._custom_title = painter_spec[4] def is_joined(self): return True def join_service(self): return self._join_service_descr def livestatus_filter(self, join_column_name): return "Filter: %s = %s" % \ (livestatus.lqencode(join_column_name), livestatus.lqencode(self._join_service_descr)) def title(self, use_short=True): if self._custom_title: return self._custom_title else: return self._join_service_descr def export_title(self): return "%s.%s" % (self._painter_name, self.join_service()) class EmptyCell(Cell): def __init__(self, view): super(EmptyCell, self).__init__(view) def render(self, row): return "", "" def paint(self, row): return False #. # .--Table of views------------------------------------------------------. # | _____ _ _ __ _ | # | |_ _|_ _| |__ | | ___ ___ / _| __ _(_) _____ _____ | # | | |/ _` | '_ \| |/ _ \ / _ \| |_ \ \ / / |/ _ \ \ /\ / / __| | # | | | (_| | |_) | | __/ | (_) | _| \ V /| | __/\ V V /\__ \ | # | |_|\__,_|_.__/|_|\___| \___/|_| \_/ |_|\___| \_/\_/ |___/ | # | | # +----------------------------------------------------------------------+ # | Show list of all views with buttons for editing | # '----------------------------------------------------------------------' def page_edit_views(): load_views() cols = [ (_('Datasource'), lambda v: multisite_datasources[v["datasource"]]['title']) ] visuals.page_list('views', _("Edit Views"), multisite_views, cols) #. # .--Create View---------------------------------------------------------. # | ____ _ __ ___ | # | / ___|_ __ ___ __ _| |_ ___ \ \ / (_) _____ __ | # | | | | '__/ _ \/ _` | __/ _ \ \ \ / /| |/ _ \ \ /\ / / | # | | |___| | | __/ (_| | || __/ \ V / | | __/\ V V / | # | \____|_| \___|\__,_|\__\___| \_/ |_|\___| \_/\_/ | # | | # +----------------------------------------------------------------------+ # | Select the view type of the new view | # '----------------------------------------------------------------------' # First step: Select the data source # Create datasource selection valuespec, also for other modules # FIXME: Sort the datasources by (assumed) common usage def DatasourceSelection(): # FIXME: Sort the datasources by (assumed) common usage datasources = [] for ds_name, ds in multisite_datasources.items(): datasources.append((ds_name, ds['title'])) return DropdownChoice( title = _('Datasource'), help = _('The datasources define which type of objects should be displayed with this view.'), choices = datasources, sorted = True, columns = 1, default_value = 'services', ) def page_create_view(next_url = None): vs_ds = DatasourceSelection() ds = 'services' # Default selection html.header(_('Create View'), stylesheets=["pages"]) html.begin_context_buttons() back_url = html.var("back", "") html.context_button(_("Back"), back_url or "edit_views.py", "back") html.end_context_buttons() if html.var('save') and html.check_transaction(): try: ds = vs_ds.from_html_vars('ds') vs_ds.validate_value(ds, 'ds') if not next_url: next_url = html.makeuri([('datasource', ds)], filename = "create_view_infos.py") else: next_url = next_url + '&datasource=%s' % ds html.http_redirect(next_url) return except MKUserError, e: html.div(e, class_=["error"]) html.add_user_error(e.varname, e) html.begin_form('create_view') html.hidden_field('mode', 'create') forms.header(_('Select Datasource')) forms.section(vs_ds.title()) vs_ds.render_input('ds', ds) html.help(vs_ds.help()) forms.end() html.button('save', _('Continue'), 'submit') html.hidden_fields() html.end_form() html.footer() def page_create_view_infos(): ds_name = html.var('datasource') if ds_name not in multisite_datasources: raise MKGeneralException(_('The given datasource is not supported')) visuals.page_create_visual('views', multisite_datasources[ds_name]['infos'], next_url = 'edit_view.py?mode=create&datasource=%s&single_infos=%%s' % ds_name) #. # .--Edit View-----------------------------------------------------------. # | _____ _ _ _ __ ___ | # | | ____|__| (_) |_ \ \ / (_) _____ __ | # | | _| / _` | | __| \ \ / /| |/ _ \ \ /\ / / | # | | |__| (_| | | |_ \ V / | | __/\ V V / | # | |_____\__,_|_|\__| \_/ |_|\___| \_/\_/ | # | | # +----------------------------------------------------------------------+ # | | # '----------------------------------------------------------------------' # Return list of available datasources (used to render filters) def get_view_infos(view): ds_name = view.get('datasource', html.var('datasource')) return multisite_datasources[ds_name]['infos'] def page_edit_view(): load_views() visuals.page_edit_visual('views', multisite_views, custom_field_handler = render_view_config, load_handler = transform_view_to_valuespec_value, create_handler = create_view_from_valuespec, info_handler = get_view_infos, ) def view_choices(only_with_hidden = False): choices = [("", "")] for name, view in available_views.items(): if not only_with_hidden or view['single_infos']: title = format_view_title(view) choices.append(("%s" % name, title)) return choices def format_view_title(view): if view.get('mobile', False): return _('Mobile: ') + _u(view["title"]) else: return _u(view["title"]) def view_editor_options(): return [ ('mobile', _('Show this view in the Mobile GUI')), ('mustsearch', _('Show data only on search')), ('force_checkboxes', _('Always show the checkboxes')), ('user_sortable', _('Make view sortable by user')), ('play_sounds', _('Play alarm sounds')), ] def view_editor_specs(ds_name, general_properties=True): load_views() # make sure that available_views is present specs = [] if general_properties: specs.append( ('view', Dictionary( title = _('View Properties'), render = 'form', optional_keys = None, elements = [ ('datasource', FixedValue(ds_name, title = _('Datasource'), totext = multisite_datasources[ds_name]['title'], help = _('The datasource of a view cannot be changed.'), )), ('options', ListChoice( title = _('Options'), choices = view_editor_options(), default_value = ['user_sortable'], )), ('browser_reload', Integer( title = _('Automatic page reload'), unit = _('seconds'), minvalue = 0, help = _('Leave this empty or at 0 for no automatic reload.'), )), ('layout', DropdownChoice( title = _('Basic Layout'), choices = [ (k, v["title"]) for k,v in multisite_layouts.items() if not v.get("hide")], default_value = 'table', sorted = True, )), ('num_columns', Integer( title = _('Number of Columns'), default_value = 1, minvalue = 1, maxvalue = 50, )), ('column_headers', DropdownChoice( title = _('Column Headers'), choices = [ ("off", _("off")), ("pergroup", _("once per group")), ("repeat", _("repeat every 20'th row")), ], default_value = 'pergroup', )), ], )) ) def column_spec(ident, title, ds_name): painters = painters_of_datasource(ds_name) allow_empty = True empty_text = None if ident == 'columns': allow_empty = False empty_text = _("Please add at least one column to your view.") vs_column = Tuple( title = _('Column'), elements = [ CascadingDropdown( title = _('Column'), choices = painter_choices_with_params(painters), no_preselect = True, ), DropdownChoice( title = _('Link'), choices = view_choices, sorted = True, ), DropdownChoice( title = _('Tooltip'), choices = [(None, "")] + painter_choices(painters), ), ], ) join_painters = join_painters_of_datasource(ds_name) if ident == 'columns' and join_painters: join_painters = join_painters_of_datasource(ds_name) vs_column = Alternative( elements = [ vs_column, Tuple( title = _('Joined column'), help = _("A joined column can display information about specific services for " "host objects in a view showing host objects. You need to specify the " "service description of the service you like to show the data for."), elements = [ CascadingDropdown( title = _('Column'), choices = painter_choices_with_params(join_painters), no_preselect = True, ), TextUnicode( title = _('of Service'), allow_empty = False, ), DropdownChoice( title = _('Link'), choices = view_choices, sorted = True, ), DropdownChoice( title = _('Tooltip'), choices = [(None, "")] + painter_choices(join_painters), ), TextUnicode( title = _('Title'), ), ], ), ], style = 'dropdown', match = lambda x: 1 * (x is not None and len(x) == 5), ) return (ident, Dictionary( title = title, render = 'form', optional_keys = None, elements = [ (ident, ListOf(vs_column, title = title, add_label = _('Add column'), allow_empty = allow_empty, empty_text = empty_text, )), ], )) specs.append(column_spec('columns', _('Columns'), ds_name)) specs.append( ('sorting', Dictionary( title = _('Sorting'), render = 'form', optional_keys = None, elements = [ ('sorters', ListOf( Tuple( elements = [ DropdownChoice( title = _('Column'), choices = [ (name, get_painter_title_for_choices(p)) for name, p in sorters_of_datasource(ds_name).items() ], sorted = True, no_preselect = True, ), DropdownChoice( title = _('Order'), choices = [(False, _("Ascending")), (True, _("Descending"))], ), ], orientation = 'horizontal', ), title = _('Sorting'), add_label = _('Add sorter'), )), ], )), ) specs.append(column_spec('grouping', _('Grouping'), ds_name)) return specs def render_view_config(view, general_properties=True): ds_name = view.get("datasource", html.var("datasource")) if not ds_name: raise MKInternalError(_("No datasource defined.")) if ds_name not in multisite_datasources: raise MKInternalError(_('The given datasource is not supported.')) view['datasource'] = ds_name for ident, vs in view_editor_specs(ds_name, general_properties): vs.render_input(ident, view.get(ident)) # Is used to change the view structure to be compatible to # the valuespec This needs to perform the inverted steps of the # transform_valuespec_value_to_view() function. FIXME: One day we should # rewrite this to make no transform needed anymore def transform_view_to_valuespec_value(view): view["view"] = {} # Several global variables are put into a sub-dict # Only copy our known keys. Reporting element, etc. might have their own keys as well for key in [ "datasource", "browser_reload", "layout", "num_columns", "column_headers" ]: if key in view: view["view"][key] = view[key] view["view"]['options'] = [] for key, title in view_editor_options(): if view.get(key): view['view']['options'].append(key) view['visibility'] = {} for key in [ 'hidden', 'hidebutton', 'public' ]: if view.get(key): view['visibility'][key] = view[key] view['grouping'] = { "grouping" : view.get('group_painters', []) } view['sorting'] = { "sorters" : view.get('sorters', {}) } columns = [] view['columns'] = { "columns" : columns } for entry in view.get('painters', []): if len(entry) == 5: pname, viewname, tooltip, join_index, col_title = entry columns.append((pname, join_index, viewname, tooltip or None, col_title)) elif len(entry) == 4: pname, viewname, tooltip, join_index = entry columns.append((pname, join_index, viewname, tooltip or None, '')) elif len(entry) == 3: pname, viewname, tooltip = entry columns.append((pname, viewname, tooltip or None)) else: pname, viewname = entry columns.append((pname, viewname, None)) def transform_valuespec_value_to_view(view): for ident, attrs in view.items(): # Transform some valuespec specific options to legacy view # format. We do not want to change the view data structure # at the moment. if ident == 'view': if "options" in attrs: # First set all options to false for option in dict(view_editor_options()).keys(): view[option] = False # Then set the selected single options for option in attrs['options']: view[option] = True # And cleanup del attrs['options'] view.update(attrs) del view["view"] elif ident == 'sorting': view.update(attrs) del view["sorting"] elif ident == 'grouping': view['group_painters'] = attrs['grouping'] del view["grouping"] elif ident == 'columns': painters = [] for column in attrs['columns']: if len(column) == 5: pname, join_index, viewname, tooltip, col_title = column else: pname, viewname, tooltip = column join_index, col_title = None, None viewname = viewname if viewname else None if join_index and col_title: painters.append((pname, viewname, tooltip, join_index, col_title)) elif join_index: painters.append((pname, viewname, tooltip, join_index)) else: painters.append((pname, viewname, tooltip)) view['painters'] = painters del view["columns"] # Extract properties of view from HTML variables and construct # view object, to be used for saving or displaying # # old_view is the old view dict which might be loaded from storage. # view is the new dict object to be updated. def create_view_from_valuespec(old_view, view): ds_name = old_view.get('datasource', html.var('datasource')) view['datasource'] = ds_name vs_value = {} for ident, vs in view_editor_specs(ds_name): attrs = vs.from_html_vars(ident) vs.validate_value(attrs, ident) vs_value[ident] = attrs transform_valuespec_value_to_view(vs_value) view.update(vs_value) return view #. # .--Display View--------------------------------------------------------. # | ____ _ _ __ ___ | # | | _ \(_)___ _ __ | | __ _ _ _ \ \ / (_) _____ __ | # | | | | | / __| '_ \| |/ _` | | | | \ \ / /| |/ _ \ \ /\ / / | # | | |_| | \__ \ |_) | | (_| | |_| | \ V / | | __/\ V V / | # | |____/|_|___/ .__/|_|\__,_|\__, | \_/ |_|\___| \_/\_/ | # | |_| |___/ | # +----------------------------------------------------------------------+ # | | # '----------------------------------------------------------------------' def show_filter(f): if not f.visible(): html.open_div(style="display:none;") f.display() html.close_div() else: visuals.show_filter(f) def show_filter_form(is_open, filters): # Table muss einen anderen Namen, als das Formular html.open_div(id_="filters", class_=["view_form"], style="display: none;" if not is_open else None) html.begin_form("filter") html.open_table(class_=["filterform"], cellpadding="0", cellspacing="0", border="0") html.open_tr() html.open_td() # sort filters according to title s = [(f.sort_index, f.title, f) for f in filters if f.available()] s.sort() # First show filters with double height (due to better floating # layout) for sort_index, title, f in s: if f.double_height(): show_filter(f) # Now single height filters for sort_index, title, f in s: if not f.double_height(): show_filter(f) html.close_td() html.close_tr() html.open_tr() html.open_td() html.button("search", _("Search"), "submit") html.close_td() html.close_tr() html.close_table() html.hidden_fields() html.end_form() html.close_div() def page_view(): bi.reset_cache_status() # needed for status icon load_views() view_name = html.var("view_name") if view_name == None: raise MKGeneralException(_("Missing the variable view_name in the URL.")) view = available_views.get(view_name) if not view: raise MKGeneralException(_("No view defined with the name '%s'.") % html.attrencode(view_name)) # Gather the page context which is needed for the "add to visual" popup menu # to add e.g. views to dashboards or reports datasource = multisite_datasources[view['datasource']] context = visuals.get_context_from_uri_vars(datasource['infos']) context.update(visuals.get_singlecontext_html_vars(view)) html.set_page_context(context) prepare_painter_options(view_name) painter_options.update_from_url(view) show_view(view, True, True, True) def get_painter_columns(painter): if type(lambda: None) == type(painter["columns"]): return painter["columns"]() else: return painter["columns"] # Display view with real data. This is *the* function everying # is about. def show_view(view, show_heading = False, show_buttons = True, show_footer = True, render_function = None, only_count=False, all_filters_active=False, limit=None): weblib.prepare_display_options(globals()) # Load from hard painter options > view > hard coded default num_columns = painter_options.get("num_columns", view.get("num_columns", 1)) browser_reload = painter_options.get("refresh", view.get("browser_reload", None)) force_checkboxes = view.get("force_checkboxes", False) show_checkboxes = force_checkboxes or html.var('show_checkboxes', '0') == '1' # Get the datasource (i.e. the logical table) try: datasource = multisite_datasources[view["datasource"]] except KeyError: if view["datasource"].startswith("mkeventd_"): raise MKUserError(None, _("The Event Console view '%s' can not be rendered. The Event Console is possibly " "disabled.") % view["name"]) else: raise MKUserError(None, _("The view '%s' using the datasource '%s' can not be rendered " "because the datasource does not exist.") % (view["name"], view["datasource"])) tablename = datasource["table"] # Filters to use in the view # In case of single object views, the needed filters are fixed, but not always present # in context. In this case, take them from the context type definition. use_filters = visuals.filters_of_visual(view, datasource['infos'], all_filters_active, datasource.get('link_filters', {})) # Not all filters are really shown later in show_filter_form(), because filters which # have a hardcoded value are not changeable by the user show_filters = visuals.visible_filters_of_visual(view, use_filters) # FIXME TODO HACK to make grouping single contextes possible on host/service infos # Is hopefully cleaned up soon. if view['datasource'] in ['hosts', 'services']: if html.has_var('hostgroup') and not html.has_var("opthost_group"): html.set_var("opthost_group", html.var("hostgroup")) if html.has_var('servicegroup') and not html.has_var("optservice_group"): html.set_var("optservice_group", html.var("servicegroup")) # TODO: Another hack :( Just like the above one: When opening the view "ec_events_of_host", # which is of single context "host" using a host name of a unrelated event, the list of # events is always empty since the single context filter "host" is sending a "host_name = ..." # filter to livestatus which is not matching a "unrelated event". Instead the filter event_host # needs to be used. # But this may only be done for the unrelated events view. The "ec_events_of_monhost" view still # needs the filter. :-/ # Another idea: We could change these views to non single context views, but then we would not # be able to show the buttons to other host related views, which is also bad. So better stick # with the current mode. if view["datasource"] in [ "mkeventd_events", "mkeventd_history" ] \ and "host" in view["single_infos"] and view["name"] != "ec_events_of_monhost": # Remove the original host name filter use_filters = [ f for f in use_filters if f.name != "host" ] # Set the value for the event host filter if not html.has_var("event_host"): html.set_var("event_host", html.var("host")) # Now populate the HTML vars with context vars from the view definition. Hard # coded default values are treated differently: # # a) single context vars of the view are enforced # b) multi context vars can be overwritten by existing HTML vars visuals.add_context_to_uri_vars(view, datasource["infos"], only_count) # Check that all needed information for configured single contexts are available visuals.verify_single_contexts('views', view, datasource.get('link_filters', {})) # Prepare Filter headers for Livestatus # TODO: When this is used by the reporting then *all* filters are # active. That way the inventory data will always be loaded. When # we convert this to the visuals principle the we need to optimize # this. filterheaders = "" all_active_filters = [ f for f in use_filters if f.available() ] for filt in all_active_filters: header = filt.filter(tablename) filterheaders += header # Apply the site hint / filter if html.var("site"): only_sites = [html.var("site")] else: only_sites = None # Prepare limit: # We had a problem with stats queries on the logtable where # the limit was not applied on the resulting rows but on the # lines of the log processed. This resulted in wrong stats. # For these datasources we ignore the query limits. if limit == None: # Otherwise: specified as argument if not datasource.get('ignore_limit', False): limit = get_limit() # Fork to availability view. We just need the filter headers, since we do not query the normal # hosts and service table, but "statehist". This is *not* true for BI availability, though (see later) if html.var("mode") == "availability" and ( "aggr" not in datasource["infos"] or html.var("timeline_aggr")): context = visuals.get_context_from_uri_vars(datasource['infos']) context.update(visuals.get_singlecontext_html_vars(view)) return render_availability_page(view, datasource, context, filterheaders, only_sites, limit) query = filterheaders + view.get("add_headers", "") # Sorting - use view sorters and URL supplied sorters if not only_count: user_sorters = parse_url_sorters(html.var("sort")) if user_sorters: sorter_list = user_sorters else: sorter_list = view["sorters"] sorters = [ (multisite_sorters[s[0]],) + s[1:] for s in sorter_list if s[0] in multisite_sorters ] else: sorters = [] # Prepare cells of the view # Group cells: Are displayed as titles of grouped rows # Regular cells: Are displaying information about the rows of the type the view is about # Join cells: Are displaying information of a joined source (e.g.service data on host views) group_cells = get_group_cells(view) cells = get_cells(view) regular_cells = get_regular_cells(cells) join_cells = get_join_cells(cells) # Now compute the list of all columns we need to query via Livestatus. # Those are: (1) columns used by the sorters in use, (2) columns use by # column- and group-painters in use and - note - (3) columns used to # satisfy external references (filters) of views we link to. The last bit # is the trickiest. Also compute this list of view options use by the # painters columns = get_needed_regular_columns(group_cells + cells, sorters, datasource) join_columns = get_needed_join_columns(join_cells, sorters, datasource) # Fetch data. Some views show data only after pressing [Search] if (only_count or (not view.get("mustsearch")) or html.var("filled_in") in ["filter", 'actions', 'confirm', 'painteroptions']): # names for additional columns (through Stats: headers) add_columns = datasource.get("add_columns", []) # tablename may be a function instead of a livestatus tablename # In that case that function is used to compute the result. # It may also be a tuple. In this case the first element is a function and the second element # is a list of argument to hand over to the function together with all other arguments that # are passed to query_data(). if type(tablename) == type(lambda x:None): rows = tablename(columns, query, only_sites, limit, all_active_filters) elif type(tablename) == tuple: func, args = tablename rows = func(datasource, columns, add_columns, query, only_sites, limit, *args) else: rows = query_data(datasource, columns, add_columns, query, only_sites, limit) # Now add join information, if there are join columns if join_cells: do_table_join(datasource, rows, filterheaders, join_cells, join_columns, only_sites) # If any painter, sorter or filter needs the information about the host's # inventory, then we load it and attach it as column "host_inventory" if is_inventory_data_needed(group_cells, cells, sorters, all_active_filters): for row in rows: if "host_name" in row: row["host_inventory"] = inventory.load_tree(row["host_name"]) sort_data(rows, sorters) else: rows = [] # Apply non-Livestatus filters for filter in all_active_filters: rows = filter.filter_table(rows) if html.var("mode") == "availability": render_bi_availability(view_title(view), rows) return # TODO: Use livestatus Stats: instead of fetching rows! if only_count: for fname, filter_vars in view["context"].items(): for varname, value in filter_vars.items(): html.del_var(varname) return len(rows) # The layout of the view: it can be overridden by several specifying # an output format (like json or python). Note: the layout is not # always needed. In case of an embedded view in the reporting this # field is simply missing, because the rendering is done by the # report itself. # TODO: CSV export should be handled by the layouts. It cannot # be done generic in most cases if html.output_format == "html": if "layout" in view: layout = multisite_layouts[view["layout"]] else: layout = None else: if "layout" in view and "csv_export" in multisite_layouts[view["layout"]]: multisite_layouts[view["layout"]]["csv_export"](rows, view, group_cells, cells) return else: # Generic layout of export layout = multisite_layouts.get(html.output_format) if not layout: layout = multisite_layouts["json"] # Set browser reload if browser_reload and display_options.enabled(display_options.R) and not only_count: html.set_browser_reload(browser_reload) # Until now no single byte of HTML code has been output. # Now let's render the view. The render_function will be # replaced by the mobile interface for an own version. if not render_function: render_function = render_view render_function(view, rows, datasource, group_cells, cells, show_heading, show_buttons, show_checkboxes, layout, num_columns, show_filters, show_footer, browser_reload) def get_group_cells(view): return [ Cell(view, e) for e in view["group_painters"] if Cell.painter_exists(e) ] def get_cells(view): cells = [] for e in view["painters"]: if not Cell.painter_exists(e): continue if Cell.is_join_cell(e): cells.append(JoinCell(view, e)) else: cells.append(Cell(view, e)) return cells def get_join_cells(cell_list): return filter(lambda x: type(x) == JoinCell, cell_list) def get_regular_cells(cell_list): return filter(lambda x: type(x) == Cell, cell_list) def get_needed_regular_columns(cells, sorters, datasource): # BI availability needs aggr_tree # TODO: wtf? a full reset of the list? Move this far away to a special place! if html.var("mode") == "availability" and "aggr" in datasource["infos"]: return [ "aggr_tree", "aggr_name", "aggr_group" ] columns = columns_of_cells(cells) # Columns needed for sorters # TODO: Move sorter parsing and logic to something like Cells() for s in sorters: if len(s) == 2: columns.update(s[0]["columns"]) # Add key columns, needed for executing commands columns.update(datasource["keys"]) # Add idkey columns, needed for identifying the row columns.update(datasource["idkeys"]) # Remove (implicit) site column try: columns.remove("site") except KeyError: pass return list(columns) def get_needed_join_columns(join_cells, sorters, datasource): join_columns = columns_of_cells(join_cells) # Columns needed for sorters # TODO: Move sorter parsing and logic to something like Cells() for s in sorters: if len(s) != 2: join_columns.update(s[0]["columns"]) return list(join_columns) def is_inventory_data_needed(group_cells, cells, sorters, all_active_filters): for cell in cells: if cell.has_tooltip(): if cell.tooltip_painter_name().startswith("inv_"): return True for s in sorters: if s[0].get("load_inv"): return True for cell in group_cells + cells: if cell.painter().get("load_inv"): return True for filt in all_active_filters: if filt.need_inventory(): return True return False def columns_of_cells(cells): columns = set([]) for cell in cells: columns.update(cell.needed_columns()) return columns # Output HTML code of a view. If you add or remove paramters here, # then please also do this in htdocs/mobile.py! def render_view(view, rows, datasource, group_painters, painters, show_heading, show_buttons, show_checkboxes, layout, num_columns, show_filters, show_footer, browser_reload): if html.transaction_valid() and html.do_actions(): html.set_browser_reload(0) # Show heading (change between "preview" mode and full page mode) if show_heading: # Show/Hide the header with page title, MK logo, etc. if display_options.enabled(display_options.H): # FIXME: view/layout/module related stylesheets/javascripts e.g. in case of BI? html.body_start(view_title(view), stylesheets=["pages","views","status","bi"]) if display_options.enabled(display_options.T): html.top_heading(view_title(view)) has_done_actions = False row_count = len(rows) # This is a general flag which makes the command form render when the current # view might be able to handle commands. When no commands are possible due missing # permissions or datasources without commands, the form is not rendered command_form = should_show_command_form(datasource) if command_form: weblib.init_selection() # Is the layout able to display checkboxes? can_display_checkboxes = layout.get('checkboxes', False) if show_buttons: show_combined_graphs_button = \ ("host" in datasource["infos"] or "service" in datasource["infos"]) and \ (type(datasource["table"]) == str) and \ ("host" in datasource["table"] or "service" in datasource["table"]) show_context_links(view, datasource, show_filters, # Take into account: permissions, display_options row_count > 0 and command_form, # Take into account: layout capabilities can_display_checkboxes and not view.get("force_checkboxes"), show_checkboxes, # Show link to availability datasource["table"] in [ "hosts", "services" ] or "aggr" in datasource["infos"], # Show link to combined graphs show_combined_graphs_button,) # User errors in filters html.show_user_errors() # Filter form filter_isopen = view.get("mustsearch") and not html.var("filled_in") if display_options.enabled(display_options.F) and len(show_filters) > 0: show_filter_form(filter_isopen, show_filters) # Actions if command_form: # If we are currently within an action (confirming or executing), then # we display only the selected rows (if checkbox mode is active) if show_checkboxes and html.do_actions(): rows = filter_selected_rows(view, rows, weblib.get_rowselection('view-' + view['name'])) # There are one shot actions which only want to affect one row, filter the rows # by this id during actions if html.has_var("_row_id") and html.do_actions(): rows = filter_by_row_id(view, rows) if html.do_actions() and html.transaction_valid(): # submit button pressed, no reload try: # Create URI with all actions variables removed backurl = html.makeuri([], delvars=['filled_in', 'actions']) has_done_actions = do_actions(view, datasource["infos"][0], rows, backurl) except MKUserError, e: html.show_error(e) html.add_user_error(e.varname, e) if display_options.enabled(display_options.C): show_command_form(True, datasource) elif display_options.enabled(display_options.C): # (*not* display open, if checkboxes are currently shown) show_command_form(False, datasource) # Also execute commands in cases without command form (needed for Python- # web service e.g. for NagStaMon) elif row_count > 0 and config.user.may("general.act") \ and html.do_actions() and html.transaction_valid(): # There are one shot actions which only want to affect one row, filter the rows # by this id during actions if html.has_var("_row_id") and html.do_actions(): rows = filter_by_row_id(view, rows) try: do_actions(view, datasource["infos"][0], rows, '') except: pass # currently no feed back on webservice painter_options.show_form(view) # The refreshing content container if display_options.enabled(display_options.R): html.open_div(id_="data_container") if not has_done_actions: # Limit exceeded? Show warning if display_options.enabled(display_options.W): check_limit(rows, get_limit()) layout["render"](rows, view, group_painters, painters, num_columns, show_checkboxes and not html.do_actions()) headinfo = "%d %s" % (row_count, _("row") if row_count == 1 else _("rows")) if show_checkboxes: selected = filter_selected_rows(view, rows, weblib.get_rowselection('view-' + view['name'])) headinfo = "%d/%s" % (len(selected), headinfo) if html.output_format == "html": html.javascript("update_headinfo('%s');" % headinfo) # The number of rows might have changed to enable/disable actions and checkboxes if show_buttons: update_context_links( # don't take display_options into account here ('c' is set during reload) row_count > 0 and should_show_command_form(datasource, ignore_display_option=True), # and not html.do_actions(), can_display_checkboxes ) # Play alarm sounds, if critical events have been displayed if display_options.enabled(display_options.S) and view.get("play_sounds"): play_alarm_sounds() else: # Always hide action related context links in this situation update_context_links(False, False) # In multi site setups error messages of single sites do not block the # output and raise now exception. We simply print error messages here. # In case of the web service we show errors only on single site installations. if config.show_livestatus_errors \ and display_options.enabled(display_options.W) \ and html.output_format == "html": for sitename, info in sites.live().dead_sites().items(): html.show_error("<b>%s - %s</b><br>%s" % (info["site"]["alias"], _('Livestatus error'), info["exception"])) # FIXME: Sauberer waere noch die Status Icons hier mit aufzunehmen if display_options.enabled(display_options.R): html.close_div() if show_footer: pid = os.getpid() if sites.live().successfully_persisted(): html.add_status_icon("persist", _("Reused persistent livestatus connection from earlier request (PID %d)") % pid) if bi.reused_compilation(): html.add_status_icon("aggrcomp", _("Reused cached compiled BI aggregations (PID %d)") % pid) html.bottom_focuscode() if display_options.enabled(display_options.Z): html.bottom_footer() if display_options.enabled(display_options.H): html.body_end() def check_limit(rows, limit): count = len(rows) if limit != None and count >= limit + 1: text = _("Your query produced more than %d results. ") % limit if html.var("limit", "soft") == "soft" and config.user.may("general.ignore_soft_limit"): text += html.render_a(_('Repeat query and allow more results.'), target="_self", href=html.makeuri([("limit", "hard")])) elif html.var("limit") == "hard" and config.user.may("general.ignore_hard_limit"): text += html.render_a(_('Repeat query without limit.'), target="_self", href=html.makeuri([("limit", "none")])) text += " " + _("<b>Note:</b> the shown results are incomplete and do not reflect the sort order.") html.show_warning(text) del rows[limit:] return False return True def do_table_join(master_ds, master_rows, master_filters, join_cells, join_columns, only_sites): join_table, join_master_column = master_ds["join"] slave_ds = multisite_datasources[join_table] join_slave_column = slave_ds["joinkey"] # Create additional filters join_filters = [] for cell in join_cells: join_filters.append(cell.livestatus_filter(join_slave_column)) join_filters.append("Or: %d" % len(join_filters)) query = "%s%s\n" % (master_filters, "\n".join(join_filters)) rows = query_data(slave_ds, [join_master_column, join_slave_column] + join_columns, [], query, only_sites, None) per_master_entry = {} current_key = None current_entry = None for row in rows: master_key = (row["site"], row[join_master_column]) if master_key != current_key: current_key = master_key current_entry = {} per_master_entry[current_key] = current_entry current_entry[row[join_slave_column]] = row # Add this information into master table in artificial column "JOIN" for row in master_rows: key = (row["site"], row[join_master_column]) joininfo = per_master_entry.get(key, {}) row["JOIN"] = joininfo g_alarm_sound_states = set([]) def clear_alarm_sound_states(): g_alarm_sound_states.clear() def save_state_for_playing_alarm_sounds(row): if not config.enable_sounds or not config.sounds: return # TODO: Move this to a generic place. What about -1? host_state_map = { 0: "up", 1: "down", 2: "unreachable"} service_state_map = { 0: "up", 1: "warning", 2: "critical", 3: "unknown"} for state_map, state in [ (host_state_map, row.get("host_hard_state", row.get("host_state"))), (service_state_map, row.get("service_last_hard_state", row.get("service_state"))) ]: if state is None: continue try: state_name = state_map[int(state)] except KeyError: continue g_alarm_sound_states.add(state_name) def play_alarm_sounds(): if not config.enable_sounds or not config.sounds: return url = config.sound_url if not url.endswith("/"): url += "/" for state_name, wav in config.sounds: if not state_name or state_name in g_alarm_sound_states: html.play_sound(url + wav) break # only one sound at one time # How many data rows may the user query? def get_limit(): limitvar = html.var("limit", "soft") if limitvar == "hard" and config.user.may("general.ignore_soft_limit"): return config.hard_query_limit elif limitvar == "none" and config.user.may("general.ignore_hard_limit"): return None else: return config.soft_query_limit def view_title(view): return visuals.visual_title('view', view) def view_optiondial(view, option, choices, help): # Darn: The option "refresh" has the name "browser_reload" in the # view definition if option == "refresh": name = "browser_reload" else: name = option # Take either the first option of the choices, the view value or the # configured painter option. value = painter_options.get(option, dflt=view.get(name, choices[0][0])) title = dict(choices).get(value, value) html.begin_context_buttons() # just to be sure # Remove unicode strings choices = [ [c[0], str(c[1])] for c in choices ] html.open_div(id_="optiondial_%s" % option, class_=["optiondial", option, "val_%s" % value], title=help, onclick="view_dial_option(this, \'%s\', \'%s\', %r)" % (view["name"], option, choices)) html.div(title) html.close_div() html.final_javascript("init_optiondial('optiondial_%s');" % option) def view_optiondial_off(option): html.div('', class_=["optiondial", "off", option]) # FIXME: Consolidate with html.toggle_button() rendering functions def toggler(id, icon, help, onclick, value, hidden = False): html.begin_context_buttons() # just to be sure hide = ' style="display:none"' if hidden else '' html.write('<div id="%s_on" title="%s" class="togglebutton %s %s" %s>' '<a href="javascript:void(0)" onclick="%s"><img src="images/icon_%s.png"></a></div>' % ( id, help, icon, value and "down" or "up", hide, onclick, icon)) # Will be called when the user presses the upper button, in order # to persist the new setting - and to make it active before the # browser reload of the DIV containing the actual status data is done. def ajax_set_viewoption(): view_name = html.var("view_name") option = html.var("option") value = html.var("value") value = { 'true' : True, 'false' : False }.get(value, value) if type(value) == str and value[0].isdigit(): try: value = int(value) except: pass po = PainterOptions(view_name) po.load() po.set(option, value) po.save_to_config() def show_context_links(thisview, datasource, show_filters, enable_commands, enable_checkboxes, show_checkboxes, show_availability, show_combined_graphs): # html.begin_context_buttons() called automatically by html.context_button() # That way if no button is painted we avoid the empty container if display_options.enabled(display_options.B): execute_hooks('buttons-begin') filter_isopen = html.var("filled_in") != "filter" and thisview.get("mustsearch") if display_options.enabled(display_options.F): if html.var("filled_in") == "filter": icon = "filters_set" help = _("The current data is being filtered") else: icon = "filters" help = _("Set a filter for refining the shown data") html.toggle_button("filters", filter_isopen, icon, help, disabled=not show_filters) if display_options.enabled(display_options.D): html.toggle_button("painteroptions", False, "painteroptions", _("Modify display options"), disabled=not painter_options.painter_option_form_enabled()) if display_options.enabled(display_options.C): html.toggle_button("commands", False, "commands", _("Execute commands on hosts, services and other objects"), hidden = not enable_commands) html.toggle_button("commands", False, "commands", "", hidden=enable_commands, disabled=True) selection_enabled = (enable_commands and enable_checkboxes) or thisview.get("force_checkboxes") if not thisview.get("force_checkboxes"): toggler("checkbox", "checkbox", _("Enable/Disable checkboxes for selecting rows for commands"), "location.href='%s';" % html.makeuri([('show_checkboxes', show_checkboxes and '0' or '1')]), show_checkboxes, hidden = True) # not selection_enabled) html.toggle_button("checkbox", False, "checkbox", "", hidden=not thisview.get("force_checkboxes"), disabled=True) html.javascript('g_selection_enabled = %s;' % ('true' if selection_enabled else 'false')) if display_options.enabled(display_options.O): if config.user.may("general.view_option_columns"): choices = [ [x, "%s" % x] for x in config.view_option_columns ] view_optiondial(thisview, "num_columns", choices, _("Change the number of display columns")) else: view_optiondial_off("num_columns") if display_options.enabled(display_options.R) and config.user.may("general.view_option_refresh"): choices = [ [x, {0:_("off")}.get(x, str(x) + "s") ] for x in config.view_option_refreshes ] view_optiondial(thisview, "refresh", choices, _("Change the refresh rate")) else: view_optiondial_off("refresh") if display_options.enabled(display_options.B): # WATO: If we have a host context, then show button to WATO, if permissions allow this if html.has_var("host") \ and config.wato_enabled \ and config.user.may("wato.use") \ and (config.user.may("wato.hosts") or config.user.may("wato.seeall")): host = html.var("host") if host: url = wato.link_to_host_by_name(host) else: url = wato.link_to_folder_by_path(html.var("wato_folder", "")) html.context_button(_("WATO"), url, "wato", id="wato", bestof = config.context_buttons_to_show) # Button for creating an instant report (if reporting is available) if config.reporting_available() and config.user.may("general.reporting"): html.context_button(_("Export as PDF"), html.makeuri([], filename="report_instant.py"), "report", class_="context_pdf_export") # Buttons to other views, dashboards, etc. links = visuals.collect_context_links(thisview) for linktitle, uri, icon, buttonid in links: html.context_button(linktitle, url=uri, icon=icon, id=buttonid, bestof=config.context_buttons_to_show) # Customize/Edit view button if display_options.enabled(display_options.E) and config.user.may("general.edit_views"): url_vars = [ ("back", html.requested_url()), ("load_name", thisview["name"]), ] if thisview["owner"] != config.user.id: url_vars.append(("load_user", thisview["owner"])) url = html.makeuri_contextless(url_vars, filename="edit_view.py") html.context_button(_("Edit View"), url, "edit", id="edit", bestof=config.context_buttons_to_show) if display_options.enabled(display_options.E): if show_availability: html.context_button(_("Availability"), html.makeuri([("mode", "availability")]), "availability") if show_combined_graphs and config.combined_graphs_available(): html.context_button(_("Combined graphs"), html.makeuri([ ("single_infos", ",".join(thisview["single_infos"])), ("datasource", thisview["datasource"]), ("view_title", view_title(thisview)), ], filename="combined_graphs.py"), "pnp") if display_options.enabled(display_options.B): execute_hooks('buttons-end') html.end_context_buttons() def update_context_links(enable_command_toggle, enable_checkbox_toggle): html.javascript("update_togglebutton('commands', %d);" % (enable_command_toggle and 1 or 0)) html.javascript("update_togglebutton('checkbox', %d);" % (enable_command_toggle and enable_checkbox_toggle and 1 or 0, )) def ajax_count_button(): id = html.var("id") counts = config.user.load_file("buttoncounts", {}) for i in counts: counts[i] *= 0.95 counts.setdefault(id, 0) counts[id] += 1 config.user.save_file("buttoncounts", counts) # Retrieve data via livestatus, convert into list of dicts, # prepare row-function needed for painters # datasource: the datasource object as defined in plugins/views/datasources.py # columns: the list of livestatus columns to query # add_columns: list of columns the datasource is known to add itself # (couldn't we get rid of this parameter by looking that up ourselves?) # add_headers: additional livestatus headers to add # only_sites: list of sites the query is limited to # limit: maximum number of data rows to query def query_data(datasource, columns, add_columns, add_headers, only_sites = None, limit = None, tablename=None): if only_sites is None: only_sites = [] if tablename == None: tablename = datasource["table"] add_headers += datasource.get("add_headers", "") merge_column = datasource.get("merge_by") if merge_column: columns = [merge_column] + columns # Most layouts need current state of object in order to # choose background color - even if no painter for state # is selected. Make sure those columns are fetched. This # must not be done for the table 'log' as it cannot correctly # distinguish between service_state and host_state if "log" not in datasource["infos"]: state_columns = [] if "service" in datasource["infos"]: state_columns += [ "service_has_been_checked", "service_state" ] if "host" in datasource["infos"]: state_columns += [ "host_has_been_checked", "host_state" ] for c in state_columns: if c not in columns: columns.append(c) auth_domain = datasource.get("auth_domain", "read") # Remove columns which are implicitely added by the datasource columns = [ c for c in columns if c not in add_columns ] query = "GET %s\n" % tablename rows = do_query_data(query, columns, add_columns, merge_column, add_headers, only_sites, limit, auth_domain) # Datasource may have optional post processing function to filter out rows post_process_func = datasource.get("post_process") if post_process_func: return post_process_func(rows) else: return rows def do_query_data(query, columns, add_columns, merge_column, add_headers, only_sites, limit, auth_domain): query += "Columns: %s\n" % " ".join(columns) query += add_headers sites.live().set_prepend_site(True) if limit != None: sites.live().set_limit(limit + 1) # + 1: We need to know, if limit is exceeded else: sites.live().set_limit(None) if config.debug_livestatus_queries \ and html.output_format == "html" and display_options.enabled(display_options.W): html.open_div(class_=["livestatus", "message"]) html.tt(query.replace('\n', '<br>\n')) html.close_div() if only_sites: sites.live().set_only_sites(only_sites) sites.live().set_auth_domain(auth_domain) data = sites.live().query(query) sites.live().set_auth_domain("read") sites.live().set_only_sites(None) sites.live().set_prepend_site(False) sites.live().set_limit() # removes limit if merge_column: data = merge_data(data, columns) # convert lists-rows into dictionaries. # performance, but makes live much easier later. columns = ["site"] + columns + add_columns rows = [ dict(zip(columns, row)) for row in data ] return rows # Merge all data rows with different sites but the same value # in merge_column. We require that all column names are prefixed # with the tablename. The column with the merge key is required # to be the *second* column (right after the site column) def merge_data(data, columns): merged = {} mergefuncs = [lambda a,b: ""] # site column is not merged def worst_service_state(a, b): if a == 2 or b == 2: return 2 else: return max(a, b) def worst_host_state(a, b): if a == 1 or b == 1: return 1 else: return max(a, b) for c in columns: tablename, col = c.split("_", 1) if col.startswith("num_") or col.startswith("members"): mergefunc = lambda a,b: a+b elif col.startswith("worst_service"): return worst_service_state elif col.startswith("worst_host"): return worst_host_state else: mergefunc = lambda a,b: a mergefuncs.append(mergefunc) for row in data: mergekey = row[1] if mergekey in merged: oldrow = merged[mergekey] merged[mergekey] = [ f(a,b) for f,a,b in zip(mergefuncs, oldrow, row) ] else: merged[mergekey] = row # return all rows sorted according to merge key mergekeys = merged.keys() mergekeys.sort() return [ merged[k] for k in mergekeys ] # Sort data according to list of sorters. The tablename # is needed in order to handle different column names # for same objects (e.g. host_name in table services and # simply name in table hosts) def sort_data(data, sorters): if len(sorters) == 0: return # Handle case where join columns are not present for all rows def save_compare(compfunc, row1, row2, args): if row1 == None and row2 == None: return 0 elif row1 == None: return -1 elif row2 == None: return 1 else: if args: return compfunc(row1, row2, *args) else: return compfunc(row1, row2) sort_cmps = [] for s in sorters: cmpfunc = s[0]["cmp"] negate = -1 if s[1] else 1 if len(s) > 2: joinkey = s[2] # e.g. service description else: joinkey = None sort_cmps.append((cmpfunc, negate, joinkey, s[0].get('args'))) def multisort(e1, e2): for func, neg, joinkey, args in sort_cmps: if joinkey: # Sorter for join column, use JOIN info c = neg * save_compare(func, e1["JOIN"].get(joinkey), e2["JOIN"].get(joinkey), args) else: if args: c = neg * func(e1, e2, *args) else: c = neg * func(e1, e2) if c != 0: return c return 0 # equal data.sort(multisort) def sorters_of_datasource(ds_name): return allowed_for_datasource(multisite_sorters, ds_name) def painters_of_datasource(ds_name): return allowed_for_datasource(multisite_painters, ds_name) def join_painters_of_datasource(ds_name): ds = multisite_datasources[ds_name] if "join" not in ds: return {} # no joining with this datasource # Get the painters allowed for the join "source" and "target" painters = painters_of_datasource(ds_name) join_painters_unfiltered = allowed_for_datasource(multisite_painters, ds['join'][0]) # Filter out painters associated with the "join source" datasource join_painters = {} for key, val in join_painters_unfiltered.items(): if key not in painters: join_painters[key] = val return join_painters # Filters a list of sorters or painters and decides which of # those are available for a certain data source def allowed_for_datasource(collection, datasourcename): datasource = multisite_datasources[datasourcename] infos_available = set(datasource["infos"]) add_columns = datasource.get("add_columns", []) allowed = {} for name, item in collection.items(): infos_needed = infos_needed_by_painter(item, add_columns) if len(infos_needed.difference(infos_available)) == 0: allowed[name] = item return allowed def infos_needed_by_painter(painter, add_columns=None): if add_columns is None: add_columns = [] columns = get_painter_columns(painter) return set([ c.split("_", 1)[0] for c in columns if c != "site" and c not in add_columns]) # Returns either the valuespec of the painter parameters or None def get_painter_params_valuespec(painter): if "params" not in painter: return if type(lambda: None) == type(painter["params"]): return painter["params"]() else: return painter["params"] def painter_choices(painters, add_params=False): choices = [] for name, painter in painters.items(): title = get_painter_title_for_choices(painter) # Add the optional valuespec for painter parameters if add_params and "params" in painter: vs_params = get_painter_params_valuespec(painter) choices.append((name, title, vs_params)) else: choices.append((name, title)) return sorted(choices, key=lambda x: x[1]) def get_painter_title_for_choices(painter): info_title = "/".join([ visuals.infos[info_name]["title_plural"] for info_name in sorted(infos_needed_by_painter(painter)) ]) # TODO: Cleanup the special case for sites. How? Add an info for it? if painter["columns"] == ["site"]: info_title = _("Site") return "%s: %s" % (info_title, painter["title"]) def painter_choices_with_params(painters): return painter_choices(painters, add_params=True) #. # .--Commands------------------------------------------------------------. # | ____ _ | # | / ___|___ _ __ ___ _ __ ___ __ _ _ __ __| |___ | # | | | / _ \| '_ ` _ \| '_ ` _ \ / _` | '_ \ / _` / __| | # | | |__| (_) | | | | | | | | | | | (_| | | | | (_| \__ \ | # | \____\___/|_| |_| |_|_| |_| |_|\__,_|_| |_|\__,_|___/ | # | | # +----------------------------------------------------------------------+ # | Functions dealing with external commands send to the monitoring | # | core. The commands themselves are defined as a plugin. Shipped | # | command definitions are in plugins/views/commands.py. | # | We apologize for the fact that we one time speak of "commands" and | # | the other time of "action". Both is the same here... | # '----------------------------------------------------------------------' # Checks whether or not this view handles commands for the current user # When it does not handle commands the command tab, command form, row # selection and processing commands is disabled. def should_show_command_form(datasource, ignore_display_option=False): if not ignore_display_option and display_options.disabled(display_options.C): return False if not config.user.may("general.act"): return False # What commands are available depends on the Livestatus table we # deal with. If a data source provides information about more # than one table, (like services datasource also provide host # information) then the first info is the primary table. So 'what' # will be one of "host", "service", "command" or "downtime". what = datasource["infos"][0] for command in multisite_commands: if what in command["tables"] and config.user.may(command["permission"]): return True return False def show_command_form(is_open, datasource): # What commands are available depends on the Livestatus table we # deal with. If a data source provides information about more # than one table, (like services datasource also provide host # information) then the first info is the primary table. So 'what' # will be one of "host", "service", "command" or "downtime". what = datasource["infos"][0] html.open_div(id_="commands", class_=["view_form"], style="display:none;" if not is_open else None) html.begin_form("actions") html.hidden_field("_do_actions", "yes") html.hidden_field("actions", "yes") html.hidden_fields() # set all current variables, exception action vars # Show command forms, grouped by (optional) command group by_group = {} for command in multisite_commands: if what in command["tables"] and config.user.may(command["permission"]): # Some special commands can be shown on special views using this option. # It is currently only used in custom views, not shipped with check_mk. if command.get('only_view') and html.var('view_name') != command['only_view']: continue group = command.get("group", "various") by_group.setdefault(group, []).append(command) for group_ident, group_commands in sorted(by_group.items(), key=lambda x: multisite_command_groups[x[0]]["sort_index"]): forms.header(multisite_command_groups[group_ident]["title"], narrow=True) for command in group_commands: forms.section(command["title"]) command["render"]() forms.end() html.end_form() html.close_div() # Examine the current HTML variables in order determine, which # command the user has selected. The fetch ids from a data row # (host name, service description, downtime/commands id) and # construct one or several core command lines and a descriptive # title. def core_command(what, row, row_nr, total_rows): host = row.get("host_name") descr = row.get("service_description") if what == "host": spec = host cmdtag = "HOST" elif what == "service": spec = "%s;%s" % (host, descr) cmdtag = "SVC" else: spec = row.get(what + "_id") if descr: cmdtag = "SVC" else: cmdtag = "HOST" commands = None title = None # Call all command actions. The first one that detects # itself to be executed (by examining the HTML variables) # will return a command to execute and a title for the # confirmation dialog. for cmd in multisite_commands: if config.user.may(cmd["permission"]): # Does the command need information about the total number of rows # and the number of the current row? Then specify that if cmd.get("row_stats"): result = cmd["action"](cmdtag, spec, row, row_nr, total_rows) else: result = cmd["action"](cmdtag, spec, row) if result: executor = cmd.get("executor", command_executor_livestatus) commands, title = result break # Use the title attribute to determine if a command exists, since the list # of commands might be empty (e.g. in case of "remove all downtimes" where) # no downtime exists in a selection of rows. if not title: raise MKUserError(None, _("Sorry. This command is not implemented.")) # Some commands return lists of commands, others # just return one basic command. Convert those if type(commands) != list: commands = [commands] return commands, title, executor def command_executor_livestatus(command, site): sites.live().command("[%d] %s" % (int(time.time()), command), site) # make gettext localize some magic texts _("services") _("hosts") _("commands") _("downtimes") _("aggregations") # Returns: # True -> Actions have been done # False -> No actions done because now rows selected # [...] new rows -> Rows actions (shall/have) be performed on def do_actions(view, what, action_rows, backurl): if not config.user.may("general.act"): html.show_error(_("You are not allowed to perform actions. " "If you think this is an error, please ask " "your administrator grant you the permission to do so.")) return False # no actions done if not action_rows: message = _("No rows selected to perform actions for.") if html.output_format == "html": # sorry for this hack message += '<br><a href="%s">%s</a>' % (backurl, _('Back to view')) html.show_error(message) return False # no actions done command = None title, executor = core_command(what, action_rows[0], 0, len(action_rows))[1:3] # just get the title and executor if not html.confirm(_("Do you really want to %(title)s the following %(count)d %(what)s?") % { "title" : title, "count" : len(action_rows), "what" : visuals.infos[what]["title_plural"], }, method = 'GET'): return False count = 0 already_executed = set([]) for nr, row in enumerate(action_rows): core_commands, title, executor = core_command(what, row, nr, len(action_rows)) for command_entry in core_commands: site = row.get("site") # site is missing for BI rows (aggregations can spawn several sites) if (site, command_entry) not in already_executed: # Some command functions return the information about the site per-command (e.g. for BI) if type(command_entry) == tuple: site, command = command_entry else: command = command_entry if type(command) == unicode: command = command.encode("utf-8") executor(command, site) already_executed.add((site, command_entry)) count += 1 message = None if command: message = _("Successfully sent %d commands.") % count if config.debug: message += _("The last one was: <pre>%s</pre>") % command elif count == 0: message = _("No matching data row. No command sent.") if message: if html.output_format == "html": # sorry for this hack message += '<br><a href="%s">%s</a>' % (backurl, _('Back to view')) if html.var("show_checkboxes") == "1": html.del_var("selection") weblib.selection_id() backurl += "&selection=" + html.var("selection") message += '<br><a href="%s">%s</a>' % (backurl, _('Back to view with checkboxes reset')) if html.var("_show_result") == "0": html.immediate_browser_redirect(0.5, backurl) html.message(message) return True def filter_by_row_id(view, rows): wanted_row_id = html.var("_row_id") for row in rows: if row_id(view, row) == wanted_row_id: return [row] return [] def filter_selected_rows(view, rows, selected_ids): action_rows = [] for row in rows: if row_id(view, row) in selected_ids: action_rows.append(row) return action_rows def get_context_link(user, viewname): if viewname in available_views: return "view.py?view_name=%s" % viewname else: return None def ajax_export(): load_views() for name, view in available_views.items(): view["owner"] = '' view["public"] = True html.write(pprint.pformat(available_views)) def get_view_by_name(view_name): load_views() return available_views[view_name] #. # .--Plugin Helpers------------------------------------------------------. # | ____ _ _ _ _ _ | # | | _ \| |_ _ __ _(_)_ __ | | | | ___| |_ __ ___ _ __ ___ | # | | |_) | | | | |/ _` | | '_ \ | |_| |/ _ \ | '_ \ / _ \ '__/ __| | # | | __/| | |_| | (_| | | | | | | _ | __/ | |_) | __/ | \__ \ | # | |_| |_|\__,_|\__, |_|_| |_| |_| |_|\___|_| .__/ \___|_| |___/ | # | |___/ |_| | # +----------------------------------------------------------------------+ # | | # '----------------------------------------------------------------------' def register_command_group(ident, title, sort_index): multisite_command_groups[ident] = { "title" : title, "sort_index" : sort_index, } def register_hook(hook, func): if not hook in view_hooks: view_hooks[hook] = [] if func not in view_hooks[hook]: view_hooks[hook].append(func) def execute_hooks(hook): for hook_func in view_hooks.get(hook, []): try: hook_func() except: if config.debug: raise MKGeneralException(_('Problem while executing hook function %s in hook %s: %s') % (hook_func.__name__, hook, traceback.format_exc())) else: pass def join_row(row, cell): if type(cell) == JoinCell: return row.get("JOIN", {}).get(cell.join_service()) else: return row def url_to_view(row, view_name): if display_options.disabled(display_options.I): return None view = permitted_views().get(view_name) if view: # Get the context type of the view to link to, then get the parameters of this # context type and try to construct the context from the data of the row url_vars = [] datasource = multisite_datasources[view['datasource']] for info_key in datasource['infos']: if info_key in view['single_infos']: # Determine which filters (their names) need to be set # for specifying in order to select correct context for the # target view. for filter_name in visuals.info_params(info_key): filter_object = visuals.get_filter(filter_name) # Get the list of URI vars to be set for that filter new_vars = filter_object.variable_settings(row) url_vars += new_vars # See get_link_filter_names() comment for details for src_key, dst_key in visuals.get_link_filter_names(view, datasource['infos'], datasource.get('link_filters', {})): try: url_vars += visuals.get_filter(src_key).variable_settings(row) except KeyError: pass try: url_vars += visuals.get_filter(dst_key).variable_settings(row) except KeyError: pass # Some special handling for the site filter which is meant as optional hint # Always add the site filter var when some useful information is available add_site_hint = True for filter_key in datasource.get('multiple_site_filters', []): if filter_key in dict(url_vars): add_site_hint = False # Hack for servicedesc view which is meant to show all services with the given # description: Don't add the site filter for this view. if view_name == "servicedesc": add_site_hint = False if add_site_hint and row.get('site'): url_vars.append(('site', row['site'])) do = html.var("display_options") if do: url_vars.append(("display_options", do)) filename = "mobile_view.py" if html.mobile else "view.py" return filename + "?" + html.urlencode_vars([("view_name", view_name)] + url_vars) def link_to_view(content, row, view_name): if display_options.disabled(display_options.I): return content url = url_to_view(row, view_name) if url: return "<a href=\"%s\">%s</a>" % (url, content) else: return content def docu_link(topic, text): return '<a href="%s" target="_blank">%s</a>' % (config.doculink_urlformat % topic, text) # Calculates a uniq id for each data row which identifies the current # row accross different page loadings. def row_id(view, row): key = u'' for col in multisite_datasources[view['datasource']]['idkeys']: key += u'~%s' % row[col] return hashlib.sha256(key.encode('utf-8')).hexdigest() def paint_stalified(row, text): if is_stale(row): return "stale", text else: return "", text def substract_sorters(base, remove): for s in remove: if s in base: base.remove(s) elif (s[0], not s[1]) in base: base.remove((s[0], not s[1])) def parse_url_sorters(sort): sorters = [] if not sort: return sorters for s in sort.split(','): if not '~' in s: sorters.append((s.replace('-', ''), s.startswith('-'))) else: sorter, join_index = s.split('~', 1) sorters.append((sorter.replace('-', ''), sorter.startswith('-'), join_index)) return sorters def get_sorter_name_of_painter(painter_name): painter = multisite_painters[painter_name] if 'sorter' in painter: return painter['sorter'] elif painter_name in multisite_sorters: return painter_name def get_primary_sorter_order(view, painter_name): sorter_name = get_sorter_name_of_painter(painter_name) this_asc_sorter = (sorter_name, False) this_desc_sorter = (sorter_name, True) group_sort, user_sort, view_sort = get_separated_sorters(view) if user_sort and this_asc_sorter == user_sort[0]: return 'asc' elif user_sort and this_desc_sorter == user_sort[0]: return 'desc' else: return '' def get_separated_sorters(view): group_sort = [ (get_sorter_name_of_painter(p[0]), False) for p in view['group_painters'] if p[0] in multisite_painters and get_sorter_name_of_painter(p[0]) is not None ] view_sort = [ s for s in view['sorters'] if not s[0] in group_sort ] # Get current url individual sorters. Parse the "sort" url parameter, # then remove the group sorters. The left sorters must be the user # individual sorters for this view. # Then remove the user sorters from the view sorters user_sort = parse_url_sorters(html.var('sort')) substract_sorters(user_sort, group_sort) substract_sorters(view_sort, user_sort) return group_sort, user_sort, view_sort # The Group-value of a row is used for deciding whether # two rows are in the same group or not def group_value(row, group_cells): group = [] for cell in group_cells: painter = cell.painter() groupvalfunc = painter.get("groupby") if groupvalfunc: if "args" in painter: group.append(groupvalfunc(row, *painter["args"])) else: group.append(groupvalfunc(row)) else: for c in get_painter_columns(painter): if c in row: group.append(row[c]) return create_dict_key(group) def create_dict_key(value): if type(value) in (list, tuple): return tuple(map(create_dict_key, value)) elif type(value) == dict: return tuple([ (k, create_dict_key(v)) for (k, v) in sorted(value.items()) ]) else: return value def get_host_tags(row): if type(row.get("host_custom_variables")) == dict: return row["host_custom_variables"].get("TAGS", "") if type(row.get("host_custom_variable_names")) != list: return "" for name, val in zip(row["host_custom_variable_names"], row["host_custom_variable_values"]): if name == "TAGS": return val return "" # Get the definition of a tag group g_taggroups_by_id = {} def get_tag_group(tgid): # Build a cache if not g_taggroups_by_id: for entry in config.host_tag_groups(): g_taggroups_by_id[entry[0]] = (entry[1], entry[2]) return g_taggroups_by_id.get(tgid, (_("N/A"), [])) def get_custom_var(row, key): for name, val in zip(row["custom_variable_names"], row["custom_variable_values"]): if name == key: return val return "" def is_stale(row): return row.get('service_staleness', row.get('host_staleness', 0)) >= config.staleness_threshold def cmp_insensitive_string(v1, v2): c = cmp(v1.lower(), v2.lower()) # force a strict order in case of equal spelling but different # case! if c == 0: return cmp(v1, v2) else: return c # Sorting def cmp_ip_address(column, r1, r2): def split_ip(ip): try: return tuple(int(part) for part in ip.split('.')) except: return ip v1, v2 = split_ip(r1.get(column, '')), split_ip(r2.get(column, '')) return cmp(v1, v2) def cmp_simple_string(column, r1, r2): v1, v2 = r1.get(column, ''), r2.get(column, '') return cmp_insensitive_string(v1, v2) def cmp_num_split(column, r1, r2): return utils.cmp_num_split(r1[column].lower(), r2[column].lower()) def cmp_string_list(column, r1, r2): v1 = ''.join(r1.get(column, [])) v2 = ''.join(r2.get(column, [])) return cmp_insensitive_string(v1, v2) def cmp_simple_number(column, r1, r2): return cmp(r1.get(column), r2.get(column)) def cmp_custom_variable(r1, r2, key, cmp_func): return cmp(get_custom_var(r1, key), get_custom_var(r2, key)) def cmp_service_name_equiv(r): if r == "Check_MK": return -6 elif r == "Check_MK Agent": return -5 elif r == "Check_MK Discovery": return -4 elif r == "Check_MK inventory": return -3 # FIXME: Remove old name one day elif r == "Check_MK HW/SW Inventory": return -2 else: return 0 def declare_simple_sorter(name, title, column, func): multisite_sorters[name] = { "title" : title, "columns" : [ column ], "cmp" : lambda r1, r2: func(column, r1, r2) } def declare_1to1_sorter(painter_name, func, col_num = 0, reverse = False): multisite_sorters[painter_name] = { "title" : multisite_painters[painter_name]['title'], "columns" : multisite_painters[painter_name]['columns'], } if not reverse: multisite_sorters[painter_name]["cmp"] = \ lambda r1, r2: func(multisite_painters[painter_name]['columns'][col_num], r1, r2) else: multisite_sorters[painter_name]["cmp"] = \ lambda r1, r2: func(multisite_painters[painter_name]['columns'][col_num], r2, r1) return painter_name # Ajax call for fetching parts of the tree def ajax_inv_render_tree(): hostname = html.var("host") invpath = html.var("path") tree_id = html.var("treeid", "") if html.var("show_internal_tree_paths"): show_internal_tree_paths = True else: show_internal_tree_paths = False if tree_id: struct_tree = inventory.load_delta_tree(hostname, int(tree_id[1:])) tree_renderer = DeltaNodeRenderer(hostname, tree_id, invpath) else: struct_tree = inventory.load_tree(hostname) tree_renderer = AttributeRenderer(hostname, "", invpath, show_internal_tree_paths=show_internal_tree_paths) if struct_tree is None: html.show_error(_("No such inventory tree.")) struct_tree = struct_tree.get_filtered_tree(inventory.get_permitted_inventory_paths()) parsed_path, attributes_key = inventory.parse_tree_path(invpath) if parsed_path: children = struct_tree.get_sub_children(parsed_path) else: children = [struct_tree.get_root_container()] if children is None: html.show_error(_("Invalid path in inventory tree: '%s' >> %s") % (invpath, repr(parsed_path))) else: for child in inventory.sort_children(children): child.show(tree_renderer, path=invpath) def output_csv_headers(view): filename = '%s-%s.csv' % (view['name'], time.strftime('%Y-%m-%d_%H-%M-%S', time.localtime(time.time()))) if type(filename) == unicode: filename = filename.encode("utf-8") html.req.headers_out['Content-Disposition'] = 'Attachment; filename="%s"' % filename def paint_host_list(site, hosts): entries = [] for host in hosts: args = [ ("view_name", "hoststatus"), ("site", site), ("host", host), ] if html.var("display_options"): args.append(("display_options", html.var("display_options"))) url = html.makeuri_contextless(args, filename="view.py") entries.append(html.render_a(host, href=url)) return "", HTML(", ").join(entries) # There is common code with modules/events.py:format_plugin_output(). Please check # whether or not that function needs to be changed too # TODO(lm): Find a common place to unify this functionality. def format_plugin_output(output, row = None): ok_marker = '<b class="stmark state0">OK</b>' warn_marker = '<b class="stmark state1">WARN</b>' crit_marker = '<b class="stmark state2">CRIT</b>' unknown_marker = '<b class="stmark state3">UNKN</b>' shall_escape = config.escape_plugin_output # In case we have a host or service row use the optional custom attribute # ESCAPE_PLUGIN_OUTPUT (set by host / service ruleset) to override the global # setting. if row: custom_vars = row.get("service_custom_variables", row.get("host_custom_variables", {})) if "ESCAPE_PLUGIN_OUTPUT" in custom_vars: shall_escape = custom_vars["ESCAPE_PLUGIN_OUTPUT"] == "1" if shall_escape: output = html.attrencode(output) output = output.replace("(!)", warn_marker) \ .replace("(!!)", crit_marker) \ .replace("(?)", unknown_marker) \ .replace("(.)", ok_marker) if row and "[running on" in output: a = output.index("[running on") e = output.index("]", a) hosts = output[a+12:e].replace(" ","").split(",") css, h = paint_host_list(row["site"], hosts) output = output[:a] + "running on " + h + output[e+1:] if shall_escape: # (?:&lt;A HREF=&quot;), (?: target=&quot;_blank&quot;&gt;)? and endswith(" </A>") is a special # handling for the HTML code produced by check_http when "clickable URL" option is active. output = re.sub("(?:&lt;A HREF=&quot;)?(http[s]?://[^\"'>\t\s\n,]+)(?: target=&quot;_blank&quot;&gt;)?", lambda p: '<a href="%s"><img class=pluginurl align=absmiddle title="%s" src="images/pluginurl.png"></a>' % (p.group(1).replace('&quot;', ''), p.group(1).replace('&quot;', '')), output) if output.endswith(" &lt;/A&gt;"): output = output[:-11] return output #. # .--Icon Selector-------------------------------------------------------. # | ___ ____ _ _ | # | |_ _|___ ___ _ __ / ___| ___| | ___ ___| |_ ___ _ __ | # | | |/ __/ _ \| '_ \ \___ \ / _ \ |/ _ \/ __| __/ _ \| '__| | # | | | (_| (_) | | | | ___) | __/ | __/ (__| || (_) | | | # | |___\___\___/|_| |_| |____/ \___|_|\___|\___|\__\___/|_| | # | | # +----------------------------------------------------------------------+ # | AJAX API call for rendering the icon selector | # '----------------------------------------------------------------------' def ajax_popup_icon_selector(): varprefix = html.var('varprefix') value = html.var('value') allow_empty = html.var('allow_empty') == '1' vs = IconSelector(allow_empty=allow_empty) vs.render_popup_input(varprefix, value) #. # .--Action Menu---------------------------------------------------------. # | _ _ _ __ __ | # | / \ ___| |_(_) ___ _ __ | \/ | ___ _ __ _ _ | # | / _ \ / __| __| |/ _ \| '_ \ | |\/| |/ _ \ '_ \| | | | | # | / ___ \ (__| |_| | (_) | | | | | | | | __/ | | | |_| | | # | /_/ \_\___|\__|_|\___/|_| |_| |_| |_|\___|_| |_|\__,_| | # | | # +----------------------------------------------------------------------+ # | Realizes the popup action menu for hosts/services in views | # '----------------------------------------------------------------------' def query_action_data(what, host, site, svcdesc): # Now fetch the needed data from livestatus columns = list(iconpainter_columns(what, toplevel=False)) try: columns.remove('site') except KeyError: pass if site: sites.live().set_only_sites([site]) sites.live().set_prepend_site(True) query = 'GET %ss\n' \ 'Columns: %s\n' \ 'Filter: host_name = %s\n' \ % (what, ' '.join(columns), host) if what == 'service': query += 'Filter: service_description = %s\n' % svcdesc row = sites.live().query_row(query) sites.live().set_prepend_site(False) sites.live().set_only_sites(None) return dict(zip(['site'] + columns, row)) def ajax_popup_action_menu(): site = html.var('site') host = html.var('host') svcdesc = html.var('service') what = 'service' if svcdesc else 'host' weblib.prepare_display_options(globals()) row = query_action_data(what, host, site, svcdesc) icons = get_icons(what, row, toplevel=False) html.open_ul() for icon in icons: if len(icon) != 4: html.open_li() html.write(icon[1]) html.close_li() else: html.open_li() icon_name, title, url_spec = icon[1:] if url_spec: url, target_frame = sanitize_action_url(url_spec) url = replace_action_url_macros(url, what, row) onclick = None if url.startswith('onclick:'): onclick = url[8:] url = 'javascript:void(0);' target = None if target_frame and target_frame != "_self": target = target_frame html.open_a(href=url, target=target, onclick=onclick) html.icon('', icon_name) if title: html.write(title) else: html.write_text(_("No title")) if url_spec: html.close_a() html.close_li() html.close_ul() def sanitize_action_url(url_spec): if type(url_spec) == tuple: return url_spec else: return (url_spec, None) #. # .--Reschedule----------------------------------------------------------. # | ____ _ _ _ | # | | _ \ ___ ___ ___| |__ ___ __| |_ _| | ___ | # | | |_) / _ \/ __|/ __| '_ \ / _ \/ _` | | | | |/ _ \ | # | | _ < __/\__ \ (__| | | | __/ (_| | |_| | | __/ | # | |_| \_\___||___/\___|_| |_|\___|\__,_|\__,_|_|\___| | # | | # +----------------------------------------------------------------------+ # | Ajax webservice for reschedulung host- and service checks | # '----------------------------------------------------------------------' def ajax_reschedule(): try: do_reschedule() except Exception, e: html.write("['ERROR', '%s']\n" % e) def do_reschedule(): if not config.user.may("action.reschedule"): raise MKGeneralException("You are not allowed to reschedule checks.") site = html.var("site") host = html.var("host", "") if not host: raise MKGeneralException("Action reschedule: missing host name") service = html.get_unicode_input("service", "") wait_svc = html.get_unicode_input("wait_svc", "") if service: cmd = "SVC" what = "service" spec = "%s;%s" % (host, service.encode("utf-8")) if wait_svc: wait_spec = u'%s;%s' % (host, wait_svc) add_filter = "Filter: service_description = %s\n" % livestatus.lqencode(wait_svc) else: wait_spec = spec add_filter = "Filter: service_description = %s\n" % livestatus.lqencode(service) else: cmd = "HOST" what = "host" spec = host wait_spec = spec add_filter = "" try: now = int(time.time()) sites.live().command("[%d] SCHEDULE_FORCED_%s_CHECK;%s;%d" % (now, cmd, livestatus.lqencode(spec), now), site) sites.live().set_only_sites([site]) query = u"GET %ss\n" \ "WaitObject: %s\n" \ "WaitCondition: last_check >= %d\n" \ "WaitTimeout: %d\n" \ "WaitTrigger: check\n" \ "Columns: last_check state plugin_output\n" \ "Filter: host_name = %s\n%s" \ % (what, livestatus.lqencode(wait_spec), now, config.reschedule_timeout * 1000, livestatus.lqencode(host), add_filter) row = sites.live().query_row(query) sites.live().set_only_sites() last_check = row[0] if last_check < now: html.write("['TIMEOUT', 'Check not executed within %d seconds']\n" % (config.reschedule_timeout)) else: if service == "Check_MK": # Passive services triggered by Check_MK often are updated # a few ms later. We introduce a small wait time in order # to increase the chance for the passive services already # updated also when we return. time.sleep(0.7); html.write("['OK', %d, %d, %r]\n" % (row[0], row[1], row[2].encode("utf-8"))) except Exception, e: sites.live().set_only_sites() raise MKGeneralException(_("Cannot reschedule check: %s") % e)
huiyiqun/check_mk
web/htdocs/views.py
Python
gpl-2.0
129,902
<?php namespace Drupal\message_subscribe; use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Session\AccountInterface; use Drupal\message\MessageInterface; /** * Subscribers service. */ interface SubscribersInterface { /** * Process a message and send to subscribed users. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity object to process subscriptions and send notifications for. * @param \Drupal\message\MessageInterface $message * The message object. * @param array $notify_options * (optional) An array of options to be passed to the message notifier * service. See `\Drupal\message_notify\MessageNotifier::send()`. * @param array $subscribe_options * (optional) Array with the following optional values: * - 'save message' (defaults to TRUE) Determine if the Message should be * saved. * - 'skip context' (defaults to FALSE) determine if extracting basic * context should be skipped in `self::getSubscribers()`. * - 'last uid' (defaults to 0) Only query UIDs greater than this UID. * - 'uids': Array of user IDs to be processed. Setting this, will cause * skipping `self::getSubscribers()` to get the subscribed * users. * - 'range': (defaults to FALSE) limit the number of items to fetch in the * subscribers query. * - 'end time': The timestamp of the time limit for the function to * execute. Defaults to FALSE, meaning there is no time limitation. * - 'use queue': Determine if queue API should be used to * - 'queue': Set to TRUE to indicate the processing is done via a queue * worker. * - 'entity access: (defaults to TRUE) determine if access to view the * entity should be applied when getting the list of subscribed users. * - 'notify blocked users' (defaults to the global setting in * `message_subscribe.settings`) determine whether blocked users * should be notified. Typically this should be used in conjunction with * 'entity access' to ensure that blocked users don't receive * notifications about entities which they used to have access to * before they were blocked. * - 'notify message owner' (defaults to the global setting in * `message_subscribe.settings`) determines if the user that created the * entity gets notified of their own action. If TRUE the author will get * notified. * @param array $context * (optional) array keyed with the entity type and array of entity IDs as * the value. For example, if the event is related to a node * entity, the implementing module might pass along with the node * itself, the node author and related taxonomy terms. * * Example usage. * * @code * $subscribe_options['uids'] = array( * 1 => array( * 'notifiers' => array('email'), * ), * ); * $context = array( * 'node' => array(1), * // The node author. * 'user' => array(10), * // Related taxonomy terms. * 'taxonomy_term' => array(100, 200, 300) * ); * @endcode */ public function sendMessage(EntityInterface $entity, MessageInterface $message, array $notify_options = [], array $subscribe_options = [], array $context = []); /** * Retrieve a list of subscribers for a given entity. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity to retrieve subscribers for. * @param \Drupal\message\MessageInterface $message * The message entity. * @param array $options * (optional) An array of options with the same elements as the * `$subscribe_options` array for `self::sendMessage()`. * @param array $context * (optional) The context array, passed by reference. This has the same * elements as the `$context` paramater for `self::sendMessage()`. * * @return \Drupal\message_subscribe\Subscribers\DeliveryCandidateInterface[] * Array of delivery candidate objects keyed with the user IDs to send * notifications to. */ public function getSubscribers(EntityInterface $entity, MessageInterface $message, array $options = [], array &$context = []); /** * Get context from a given entity type. * * This is a naive implementation, which extracts context from an entity. * For example, given a node we extract the node author and related * taxonomy terms. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity object. * @param bool $skip_detailed_context * (optional) Skip detailed context detection and just use entity ID/type. * Defaults to FALSE. * @param array $context * (optional) The starting context array to modify. * * @return array * Array keyed with the entity type and array of entity IDs as the value. */ public function getBasicContext(EntityInterface $entity, $skip_detailed_context = FALSE, array $context = []); /** * Get Message subscribe related flags. * * Return Flags related to message subscribe using a name convention -- * the flag name should start with "subscribe_". * * @param string $entity_type * (optional) The entity type for which to load the flags. * @param string $bundle * (optional) The bundle for which to load the flags. * @param \Drupal\Core\Session\AccountInterface $account * (optional) The user account to filter available flags. If not set, all * flags for the given entity and bundle will be returned. * * @return \Drupal\flag\FlagInterface[] * An array of the structure [fid] = flag_object. * * @see \Drupal\flag\FlagServiceInterface::getAllFlags() */ public function getFlags($entity_type = NULL, $bundle = NULL, AccountInterface $account = NULL); }
rahulrasgon/Music-Store-Theme
modules/message_subscribe/src/SubscribersInterface.php
PHP
gpl-2.0
5,817
<?php /** * Table Definition for Items_Translations * * PHP version 5 * * Copyright (C) Demian Katz 2012. * * 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 GeebyDeeby * @package Db_Table * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://github.com/demiankatz/Geeby-Deeby Main Site */ namespace GeebyDeeby\Db\Table; use Laminas\Db\Adapter\Adapter; use Laminas\Db\RowGateway\RowGateway; use Laminas\Db\Sql\Expression; use Laminas\Db\Sql\Select; /** * Table Definition for Items_Translations * * @category GeebyDeeby * @package Db_Table * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://github.com/demiankatz/Geeby-Deeby Main Site */ class ItemsTranslations extends Gateway { /** * Constructor * * @param Adapter $adapter Database adapter * @param PluginManager $tm Table manager * @param RowGateway $rowObj Row prototype object (null for default) */ public function __construct(Adapter $adapter, PluginManager $tm, RowGateway $rowObj = null ) { parent::__construct($adapter, $tm, $rowObj, 'Items_Translations'); } /** * Support method to add language information to a query. * * @param \Laminas\Db\Sql\Select $select Query to modify * * @return void */ public static function addLanguageToSelect($select) { $select->join( ['eds' => 'Editions'], 'eds.Item_ID = i.Item_ID', [], Select::JOIN_LEFT ); $select->join( ['s' => 'Series'], 's.Series_ID = eds.Series_ID', [], Select::JOIN_LEFT ); $select->join( ['l' => 'Languages'], 'l.Language_ID = s.Language_ID', [ 'Language_Name' => new Expression( 'min(?)', ['Language_Name'], [Expression::TYPE_IDENTIFIER] ) ], Select::JOIN_LEFT ); $select->group('i.Item_ID'); } /** * Get a list of items translated from the specified item. * * @param int $itemID Item ID * @param bool $includeLang Should we also load language information? * * @return mixed */ public function getTranslatedFrom($itemID, $includeLang = false) { $callback = function ($select) use ($itemID, $includeLang) { $select->join( ['i' => 'Items'], 'Items_Translations.Trans_Item_ID = i.Item_ID' ); $select->where->equalTo('Source_Item_ID', $itemID); $select->order('i.Item_Name'); if ($includeLang) { ItemsTranslations::addLanguageToSelect($select); } }; return $this->select($callback); } /** * Get a list of items translated into the specified item. * * @param int $itemID Item ID * @param bool $includeLang Should we also load language information? * * @return mixed */ public function getTranslatedInto($itemID, $includeLang = false) { $callback = function ($select) use ($itemID, $includeLang) { $select->join( ['i' => 'Items'], 'Items_Translations.Source_Item_ID = i.Item_ID' ); $select->where->equalTo('Trans_Item_ID', $itemID); $select->order('i.Item_Name'); if ($includeLang) { ItemsTranslations::addLanguageToSelect($select); } }; return $this->select($callback); } }
demiankatz/Geeby-Deeby
module/GeebyDeeby/src/GeebyDeeby/Db/Table/ItemsTranslations.php
PHP
gpl-2.0
4,351
/* * irctabitem.cpp * * Copyright 2008 David Vachulka <david@konstrukce-cad.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. */ #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <shellapi.h> #endif #include "irctabitem.h" #include "tetristabitem.h" #include "icons.h" #include "config.h" #include "i18n.h" FXDEFMAP(DccSendDialog) DccSendDialogMap[] = { FXMAPFUNC(SEL_COMMAND, DccSendDialog_FILE, DccSendDialog::onFile), FXMAPFUNC(SEL_COMMAND, DccSendDialog_SEND, DccSendDialog::onSend), FXMAPFUNC(SEL_COMMAND, DccSendDialog_CANCEL, DccSendDialog::onCancel), FXMAPFUNC(SEL_CLOSE, 0, DccSendDialog::onCancel), FXMAPFUNC(SEL_KEYPRESS, 0, DccSendDialog::onKeyPress) }; FXIMPLEMENT(DccSendDialog, FXDialogBox, DccSendDialogMap, ARRAYNUMBER(DccSendDialogMap)) DccSendDialog::DccSendDialog(FXMainWindow* owner, FXString nick) : FXDialogBox(owner, FXStringFormat(_("Send file to %s"), nick.text()), DECOR_RESIZE|DECOR_TITLE|DECOR_BORDER, 0,0,0,0, 0,0,0,0, 0,0) { m_mainFrame = new FXVerticalFrame(this, LAYOUT_FILL_X|LAYOUT_FILL_Y); m_fileFrame = new FXHorizontalFrame(m_mainFrame, LAYOUT_FILL_X); new FXLabel(m_fileFrame, _("File:")); m_fileText = new FXTextField(m_fileFrame, 25, NULL, 0, TEXTFIELD_READONLY|FRAME_THICK|FRAME_SUNKEN|LAYOUT_FILL_X); m_buttonFile = new dxEXButton(m_fileFrame, "...", NULL, this, DccSendDialog_FILE, FRAME_RAISED|FRAME_THICK|LAYOUT_CENTER_X, 0,0,0,0, 10,10,2,2); m_passiveFrame = new FXHorizontalFrame(m_mainFrame, LAYOUT_FILL_X); m_checkPassive = new FXCheckButton(m_passiveFrame, _("Send passive"), NULL, 0); m_buttonFrame = new FXHorizontalFrame(m_mainFrame, LAYOUT_FILL_X|PACK_UNIFORM_WIDTH); m_buttonCancel = new dxEXButton(m_buttonFrame, _("&Cancel"), NULL, this, DccSendDialog_CANCEL, FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0,0,0,0, 10,10,2,2); m_buttonSend = new dxEXButton(m_buttonFrame, _("&Send file"), NULL, this, DccSendDialog_SEND, BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0,0,0,0, 10,10,2,2); } DccSendDialog::~DccSendDialog() { } FXuint DccSendDialog::execute(FXuint placement) { create(); show(placement); getApp()->refresh(); dxEXFileDialog dialog(this, _("Select file")); if(dialog.execute()) { m_fileText->setText(dialog.getFilename()); } return getApp()->runModalFor(this); } long DccSendDialog::onFile(FXObject*, FXSelector, void*) { dxEXFileDialog dialog(this, _("Select file")); if(dialog.execute()) { m_fileText->setText(dialog.getFilename()); } return 1; } long DccSendDialog::onSend(FXObject*, FXSelector, void*) { getApp()->stopModal(this,TRUE); hide(); return 1; } long DccSendDialog::onCancel(FXObject*, FXSelector, void*) { getApp()->stopModal(this,FALSE); hide(); return 1; } long DccSendDialog::onKeyPress(FXObject *sender, FXSelector sel, void *ptr) { if(FXTopWindow::onKeyPress(sender,sel,ptr)) return 1; if(((FXEvent*)ptr)->code == KEY_Escape) { handle(this,FXSEL(SEL_COMMAND,DccSendDialog_CANCEL),NULL); return 1; } return 0; } FXDEFMAP(NickList) NickListMap [] = { FXMAPFUNC(SEL_QUERY_TIP, 0, NickList::onQueryTip) }; FXIMPLEMENT(NickList, FXList, NickListMap, ARRAYNUMBER(NickListMap)) NickList::NickList(FXComposite* p, IrcTabItem* tgt, FXSelector sel, FXuint opts, FXint x, FXint y, FXint w, FXint h) : FXList(p, tgt, sel, opts, x, y, w, h), m_parent(tgt) { } long NickList::onQueryTip(FXObject *sender, FXSelector sel, void *ptr) { if(FXWindow::onQueryTip(sender, sel, ptr)) return 1; if((flags&FLAG_TIP) && !(options&LIST_AUTOSELECT) && (0<=cursor)) // No tip when autoselect! { FXString string = items[cursor]->getText(); string.append('\n'); NickInfo nick = m_parent->m_engine->getNickInfo(items[cursor]->getText()); string.append(FXStringFormat(_("User: %s@%s\n"), nick.user.text(), nick.host.text())); string.append(FXStringFormat(_("Realname: %s"), nick.real.text())); sender->handle(this, FXSEL(SEL_COMMAND,ID_SETSTRINGVALUE), (void*)&string); return 1; } return 0; } FXIMPLEMENT(NickListItem, FXListItem, NULL, 0) void NickListItem::setUserMode(UserMode mode) { m_mode = mode; FXbool away = m_tab->m_engine->getNickInfo(getText()).away; m_parent->recalc(); switch(m_mode){ case ADMIN: setIcon(away? ICO_IRCAWAYADMIN:ICO_IRCADMIN);break; case OWNER: setIcon(away? ICO_IRCAWAYOWNER:ICO_IRCOWNER);break; case OP: setIcon(away? ICO_IRCAWAYOP:ICO_IRCOP);break; case HALFOP: setIcon(away? ICO_IRCAWAYHALFOP:ICO_IRCHALFOP);break; case VOICE: setIcon(away? ICO_IRCAWAYVOICE:ICO_IRCVOICE);break; case NONE: setIcon(away? ICO_IRCAWAYNORMAL:ICO_IRCNORMAL);break; } } void NickListItem::changeAway(FXbool away) { m_parent->recalc(); switch(m_mode){ case ADMIN: setIcon(away? ICO_IRCAWAYADMIN:ICO_IRCADMIN);break; case OWNER: setIcon(away? ICO_IRCAWAYOWNER:ICO_IRCOWNER);break; case OP: setIcon(away? ICO_IRCAWAYOP:ICO_IRCOP);break; case HALFOP: setIcon(away? ICO_IRCAWAYHALFOP:ICO_IRCHALFOP);break; case VOICE: setIcon(away? ICO_IRCAWAYVOICE:ICO_IRCVOICE);break; case NONE: setIcon(away? ICO_IRCAWAYNORMAL:ICO_IRCNORMAL);break; } } FXDEFMAP(IrcTabItem) IrcTabItemMap[] = { FXMAPFUNC(SEL_COMMAND, IrcTabItem_COMMANDLINE, IrcTabItem::onCommandline), FXMAPFUNC(SEL_KEYPRESS, IrcTabItem_COMMANDLINE, IrcTabItem::onKeyPress), FXMAPFUNC(SEL_COMMAND, IrcEngine_SERVER, IrcTabItem::onIrcEvent), FXMAPFUNC(SEL_TIMEOUT, IrcTabItem_PTIME, IrcTabItem::onPipeTimeout), FXMAPFUNC(SEL_TIMEOUT, IrcTabItem_ETIME, IrcTabItem::onEggTimeout), FXMAPFUNC(SEL_TEXTLINK, IrcTabItem_TEXT, IrcTabItem::onTextLink), FXMAPFUNC(SEL_RIGHTBUTTONRELEASE, IrcTabItem_USERS, IrcTabItem::onRightMouse), FXMAPFUNC(SEL_DOUBLECLICKED, IrcTabItem_USERS, IrcTabItem::onDoubleclick), FXMAPFUNC(SEL_COMMAND, IrcTabItem_NEWQUERY, IrcTabItem::onNewQuery), FXMAPFUNC(SEL_COMMAND, IrcTabItem_WHOIS, IrcTabItem::onWhois), FXMAPFUNC(SEL_COMMAND, IrcTabItem_DCCCHAT, IrcTabItem::onDccChat), FXMAPFUNC(SEL_COMMAND, IrcTabItem_DCCSEND, IrcTabItem::onDccSend), FXMAPFUNC(SEL_COMMAND, IrcTabItem_OP, IrcTabItem::onOp), FXMAPFUNC(SEL_COMMAND, IrcTabItem_DEOP, IrcTabItem::onDeop), FXMAPFUNC(SEL_COMMAND, IrcTabItem_VOICE, IrcTabItem::onVoice), FXMAPFUNC(SEL_COMMAND, IrcTabItem_DEVOICE, IrcTabItem::onDevoice), FXMAPFUNC(SEL_COMMAND, IrcTabItem_KICK, IrcTabItem::onKick), FXMAPFUNC(SEL_COMMAND, IrcTabItem_BAN, IrcTabItem::onBan), FXMAPFUNC(SEL_COMMAND, IrcTabItem_KICKBAN, IrcTabItem::onKickban), FXMAPFUNC(SEL_COMMAND, IrcTabItem_IGNORE, IrcTabItem::onIgnore), FXMAPFUNC(SEL_COMMAND, IrcTabItem_TOPIC, IrcTabItem::onTopic), FXMAPFUNC(SEL_LINK, IrcTabItem_TOPIC, IrcTabItem::onTopicLink), FXMAPFUNC(SEL_COMMAND, dxPipe::ID_PIPE, IrcTabItem::onPipe), FXMAPFUNC(SEL_COMMAND, IrcTabItem_AWAY, IrcTabItem::onSetAway), FXMAPFUNC(SEL_COMMAND, IrcTabItem_DEAWAY, IrcTabItem::onRemoveAway), FXMAPFUNC(SEL_COMMAND, IrcTabItem_SPELL, IrcTabItem::onSpellLang) }; FXIMPLEMENT(IrcTabItem, dxTabItem, IrcTabItemMap, ARRAYNUMBER(IrcTabItemMap)) IrcTabItem::IrcTabItem(dxTabBook *tab, const FXString &tabtext, FXIcon *icon, FXuint opts, FXint id, TYPE type, IrcEngine *socket, FXbool ownServerWindow, FXbool usersShown, FXbool logging, FXString commandsList, FXString logPath, FXint maxAway, IrcColor colors, FXString nickChar, FXFont *font, FXbool sameCommand, FXbool sameList, FXbool coloredNick, FXbool stripColors, FXbool useSpell, FXbool showSpellCombo) : dxTabItem(tab, tabtext, icon, opts, id), m_engine(socket), m_parent(tab), m_type(type), m_usersShown(usersShown), m_logging(logging), m_ownServerWindow(ownServerWindow), m_sameCmd(sameCommand), m_sameList(sameList), m_coloredNick(coloredNick), m_stripColors(stripColors), m_useSpell(useSpell), m_showSpellCombo(showSpellCombo), m_colors(colors), m_commandsList(commandsList), m_logPath(logPath), m_maxAway(maxAway), m_nickCompletionChar(nickChar), m_logstream(NULL) { m_currentPosition = 0; m_historyMax = 25; m_numberUsers = 0; m_maxLen = 460; m_iamOp = FALSE; m_topic = _("No topic is set"); m_editableTopic = TRUE; m_pipe = NULL; m_sendPipe = FALSE; m_scriptHasAll = FALSE; m_scriptHasMyMsg = FALSE; m_unreadColor = FXRGB(0,0,255); m_highlightColor = FXRGB(255,0,0); if(m_type == CHANNEL && m_engine->getConnected()) { m_engine->sendMode(getText()); } m_mainframe = new FXVerticalFrame(m_parent, FRAME_RAISED|LAYOUT_SIDE_TOP|LAYOUT_FILL_X|LAYOUT_FILL_Y); m_splitter = new FXSplitter(m_mainframe, LAYOUT_SIDE_TOP|LAYOUT_FILL_X|LAYOUT_FILL_Y|SPLITTER_REVERSED|SPLITTER_TRACKING); m_textframe = new FXVerticalFrame(m_splitter, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_X|LAYOUT_FILL_Y); m_topicline = new dxTextField(m_textframe, 50, this, IrcTabItem_TOPIC, FRAME_SUNKEN|TEXTFIELD_ENTER_ONLY|JUSTIFY_LEFT|LAYOUT_FILL_X); m_topicline->setFont(font); m_topicline->setLinkColor(m_colors.link); m_topicline->setText(m_topic); m_topicline->setUseLink(TRUE); m_topicline->setTopicline(TRUE); if(m_type != CHANNEL) { m_topicline->hide(); } m_text = new dxText(m_textframe, this, IrcTabItem_TEXT, FRAME_SUNKEN|LAYOUT_FILL_X|LAYOUT_FILL_Y|TEXT_READONLY|TEXT_WORDWRAP|TEXT_SHOWACTIVE|TEXT_AUTOSCROLL); m_text->setFont(font); m_text->setSelTextColor(getApp()->getSelforeColor()); m_text->setSelBackColor(getApp()->getSelbackColor()); m_usersframe = new FXVerticalFrame(m_splitter, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_X|LAYOUT_FILL_Y|LAYOUT_FIX_WIDTH); m_users = new NickList(m_usersframe, this, IrcTabItem_USERS, LAYOUT_FILL_X|LAYOUT_FILL_Y); m_users->setSortFunc(FXList::ascendingCase); m_users->setScrollStyle(HSCROLLING_OFF); if(m_sameList) m_users->setFont(font); if(m_type != CHANNEL || !m_usersShown) { m_usersframe->hide(); m_users->hide(); } m_commandframe = new FXHorizontalFrame(m_mainframe, LAYOUT_FILL_X, 0,0,0,0, 0,0,0,0); m_commandline = new dxTextField(m_commandframe, 25, this, IrcTabItem_COMMANDLINE, TEXTFIELD_ENTER_ONLY|FRAME_SUNKEN|JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_BOTTOM, 0, 0, 0, 0, 1, 1, 1, 1); if(m_sameCmd) m_commandline->setFont(font); m_spellLangs = new FXComboBox(m_commandframe, 6, this, IrcTabItem_SPELL, COMBOBOX_STATIC); m_spellLangs->setTipText(_("Spellchecking language list")); m_spellLangs->hide(); if(m_sameCmd) m_spellLangs->setFont(font); if(m_useSpell && (m_type==CHANNEL || m_type==QUERY) && utils::instance().getLangsNum()) { dxStringArray langs = utils::instance().getLangs(); FXString lang = utils::instance().getChannelLang(getText()); for(FXint i=0; i<langs.no(); i++) { m_spellLangs->appendItem(langs[i]); if(langs[i]==lang) m_spellLangs->setCurrentItem(i);; } if(m_showSpellCombo) m_spellLangs->show(); m_commandline->setUseSpell(TRUE); m_commandline->setLanguage(lang); m_commandline->setTipText(FXStringFormat(_("Current spellchecking language: %s"),lang.text())); } dxHiliteStyle style = {m_colors.text,m_colors.back,getApp()->getSelforeColor(),getApp()->getSelbackColor(),0,FALSE}; for(int i=0; i<17; i++) { m_textStyleList.append(style); } //gray text - user commands m_textStyleList[0].normalForeColor = m_colors.user; //orange text - Actions m_textStyleList[1].normalForeColor = m_colors.action; //blue text - Notice m_textStyleList[2].normalForeColor = m_colors.notice; //red text - Errors m_textStyleList[3].normalForeColor = m_colors.error; //bold style m_textStyleList[4].style = FXText::STYLE_BOLD; //underline style m_textStyleList[5].style = FXText::STYLE_UNDERLINE; //bold & underline m_textStyleList[6].style = FXText::STYLE_UNDERLINE; m_textStyleList[6].style ^=FXText::STYLE_BOLD; //highlight text m_textStyleList[7].normalForeColor = m_colors.hilight; //link style m_textStyleList[8].normalForeColor = m_colors.link; m_textStyleList[8].link = TRUE; //next styles for colored nicks m_textStyleList[9].normalForeColor = FXRGB(196, 160, 0); m_textStyleList[10].normalForeColor = FXRGB(206, 92, 0); m_textStyleList[11].normalForeColor = FXRGB(143, 89, 2); m_textStyleList[12].normalForeColor = FXRGB(78, 154, 6); m_textStyleList[13].normalForeColor = FXRGB(32, 74, 135); m_textStyleList[14].normalForeColor = FXRGB(117, 80, 123); m_textStyleList[15].normalForeColor = FXRGB(164, 0, 0); m_textStyleList[16].normalForeColor = FXRGB(85, 87, 83); //text->setStyled(TRUE); m_text->setHiliteStyles(m_textStyleList.data()); m_text->setBackColor(m_colors.back); m_commandline->setBackColor(m_colors.back); m_topicline->setBackColor(m_colors.back); m_users->setBackColor(m_colors.back); m_text->setTextColor(m_colors.text); m_commandline->setTextColor(m_colors.text); m_commandline->setCursorColor(m_colors.text); m_topicline->setTextColor(m_colors.text); m_topicline->setCursorColor(m_colors.text); m_users->setTextColor(m_colors.text); m_spellLangs->setBackColor(m_colors.back); m_spellLangs->setTextColor(m_colors.text); this->setIconPosition(ICON_BEFORE_TEXT); } IrcTabItem::~IrcTabItem() { this->stopLogging(); if(m_pipe) m_pipe->stopCmd(); m_pipeStrings.clear(); getApp()->removeTimeout(this, IrcTabItem_PTIME); } void IrcTabItem::createGeom() { m_mainframe->create(); m_commandline->setFocus(); } void IrcTabItem::clearChat() { m_textStyleList.no(17); m_text->setHiliteStyles(m_textStyleList.data()); m_text->clearText(); } //usefull for set tab current void IrcTabItem::makeLastRowVisible() { m_text->makeLastRowVisible(TRUE); } FXString IrcTabItem::getSpellLang() { #ifdef HAVE_ENCHANT if(m_spellLangs->getNumItems()) return m_spellLangs->getItemText(m_spellLangs->getCurrentItem()); #endif return ""; } void IrcTabItem::reparentTab() { reparent(m_parent); m_mainframe->reparent(m_parent); } void IrcTabItem::hideUsers() { m_usersShown = !m_usersShown; if(m_type == CHANNEL) { m_usersframe->hide(); m_users->hide(); m_splitter->setSplit(1, 0); } } void IrcTabItem::showUsers() { m_usersShown = !m_usersShown; if(m_type == CHANNEL) { m_usersframe->show(); m_users->show(); m_splitter->recalc(); } } void IrcTabItem::setType(const TYPE &typ, const FXString &tabtext) { if(typ == CHANNEL) { if(m_usersShown) m_usersframe->show(); if(m_usersShown) m_users->show(); m_topicline->show(); m_topicline->setText(m_topic); m_splitter->recalc(); setText(tabtext); if(m_engine->getConnected()) m_engine->sendMode(getText()); m_type = typ; } else if(typ == SERVER || typ == QUERY) { m_usersframe->hide(); m_users->hide(); m_topicline->setText(""); m_topicline->hide(); m_topic = _("No topic is set"); setText(tabtext); m_splitter->setSplit(1, 0); if(m_type == CHANNEL) { m_users->clearItems(); m_numberUsers = 0; } m_type = typ; } this->stopLogging(); if(m_type == SERVER) this->setIcon(ICO_SERVER); else if(m_type == CHANNEL) this->setIcon(ICO_CHANNEL); else this->setIcon(ICO_QUERY); if(m_useSpell && (m_type==CHANNEL || m_type==QUERY) && utils::instance().getLangsNum()) { dxStringArray langs = utils::instance().getLangs(); FXString lang = utils::instance().getChannelLang(getText()); for(FXint i=0; i<langs.no(); i++) { m_spellLangs->appendItem(langs[i]); if(langs[i]==lang) m_spellLangs->setCurrentItem(i);; } if(m_showSpellCombo) m_spellLangs->show(); m_commandline->setUseSpell(TRUE); m_commandline->setLanguage(lang); m_commandline->setTipText(FXStringFormat(_("Current spellchecking language: %s"),lang.text())); } else { m_commandline->setUseSpell(FALSE); m_commandline->setTipText(""); m_spellLangs->hide(); m_commandframe->recalc(); } } void IrcTabItem::setColor(IrcColor clrs) { m_colors = clrs; setTextForeColor(clrs.text); setTextBackColor(clrs.back); setUserColor(clrs.user); setActionsColor(clrs.action); setNoticeColor(clrs.notice); setErrorColor(clrs.error); setHilightColor(clrs.hilight); setLinkColor(m_colors.link); } void IrcTabItem::setTextBackColor(FXColor clr) { for(FXint i=0; i<m_textStyleList.no(); i++) { m_textStyleList[i].normalBackColor = clr; } m_text->setBackColor(clr); m_commandline->setBackColor(clr); m_topicline->setBackColor(clr); m_users->setBackColor(clr); m_spellLangs->setBackColor(clr); } void IrcTabItem::setTextForeColor(FXColor clr) { m_textStyleList[4].normalForeColor = clr; m_textStyleList[5].normalForeColor = clr; m_textStyleList[6].normalForeColor = clr; m_text->setTextColor(clr); m_commandline->setTextColor(clr); m_commandline->setCursorColor(clr); m_topicline->setTextColor(clr); m_topicline->setCursorColor(clr); m_users->setTextColor(clr); m_spellLangs->setTextColor(clr); } void IrcTabItem::setUserColor(FXColor clr) { m_textStyleList[0].normalForeColor = clr; } void IrcTabItem::setActionsColor(FXColor clr) { m_textStyleList[1].normalForeColor = clr; } void IrcTabItem::setNoticeColor(FXColor clr) { m_textStyleList[2].normalForeColor = clr; } void IrcTabItem::setErrorColor(FXColor clr) { m_textStyleList[3].normalForeColor = clr; } void IrcTabItem::setHilightColor(FXColor clr) { m_textStyleList[7].normalForeColor = clr; } void IrcTabItem::setLinkColor(FXColor clr) { m_textStyleList[8].normalForeColor = clr; m_topicline->setLinkColor(clr); } void IrcTabItem::setUnreadTabColor(FXColor clr) { if(m_unreadColor!=clr) { FXbool update = this->getTextColor()==m_unreadColor; m_unreadColor = clr; if(update) this->setTextColor(m_unreadColor); } } void IrcTabItem::setHighlightTabColor(FXColor clr) { if(m_highlightColor!=clr) { FXbool update = this->getTextColor()==m_highlightColor; m_highlightColor = clr; if(update) this->setTextColor(m_highlightColor); } } void IrcTabItem::setCommandsList(FXString clst) { m_commandsList = clst; } void IrcTabItem::setMaxAway(FXint maxa) { m_maxAway = maxa; } void IrcTabItem::setLogging(FXbool log) { m_logging = log; } void IrcTabItem::setLogPath(FXString pth) { m_logPath = pth; this->stopLogging(); } void IrcTabItem::setNickCompletionChar(FXString nichr) { m_nickCompletionChar = nichr; } void IrcTabItem::setIrcFont(FXFont *fnt) { if(m_text->getFont() != fnt) { m_text->setFont(fnt); m_text->recalc(); } if(m_topicline->getFont() != fnt) { m_topicline->setFont(fnt); m_topicline->recalc(); } if(m_sameCmd && m_commandline->getFont() != fnt) { m_commandline->setFont(fnt); m_commandline->recalc(); m_spellLangs->setFont(fnt); m_spellLangs->recalc(); } else { m_commandline->setFont(getApp()->getNormalFont()); m_commandline->recalc(); m_spellLangs->setFont(getApp()->getNormalFont()); m_spellLangs->recalc(); } if(m_sameList && m_users->getFont() != fnt) { m_users->setFont(fnt); m_users->recalc(); } else { m_users->setFont(getApp()->getNormalFont()); m_users->recalc(); } } void IrcTabItem::setSameCmd(FXbool scmd) { m_sameCmd = scmd; } void IrcTabItem::setSameList(FXbool slst) { m_sameList = slst; } void IrcTabItem::setColoredNick(FXbool cnick) { m_coloredNick = cnick; } void IrcTabItem::setStripColors(FXbool sclr) { m_stripColors = sclr; } void IrcTabItem::setSmileys(FXbool smiley, dxSmileyArray nsmileys) { m_text->setSmileys(smiley, nsmileys); } void IrcTabItem::setUseSpell(FXbool useSpell) { m_useSpell = useSpell; if(m_useSpell && (m_type==CHANNEL || m_type==QUERY) && utils::instance().getLangsNum()) { dxStringArray langs = utils::instance().getLangs(); FXString lang = utils::instance().getChannelLang(getText()); for(FXint i=0; i<langs.no(); i++) { m_spellLangs->appendItem(langs[i]); if(langs[i]==lang) m_spellLangs->setCurrentItem(i);; } if(m_showSpellCombo) m_spellLangs->show(); m_commandline->setUseSpell(TRUE); m_commandline->setLanguage(lang); m_commandline->setTipText(FXStringFormat(_("Current spellchecking language: %s"),lang.text())); } else { m_commandline->setUseSpell(FALSE); m_commandline->setTipText(""); m_spellLangs->hide(); } m_commandframe->recalc(); } void IrcTabItem::setShowSpellCombo(FXbool showSpellCombo) { if(m_showSpellCombo!=showSpellCombo) { m_showSpellCombo = showSpellCombo; if(m_showSpellCombo) m_spellLangs->show(); else m_spellLangs->hide(); m_commandframe->recalc(); } } void IrcTabItem::removeSmileys() { m_text->removeSmileys(); } //if highlight==TRUE, highlight tab void IrcTabItem::appendText(FXString msg, FXbool highlight, FXbool logLine) { appendIrcText(msg, 0, FALSE, logLine); if(highlight && m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) { if(msg.contains(getNickName())) { this->setTextColor(m_highlightColor); if(m_type == CHANNEL) this->setIcon(ICO_CHANNELNEWMSG); } else this->setTextColor(m_unreadColor); if(m_type == QUERY) this->setIcon(ICO_QUERYNEWMSG); } } void IrcTabItem::appendIrcText(FXString msg, FXTime time, FXbool disableStrip, FXbool logLine) { if(!time) time = FXSystem::now(); if(m_type != OTHER) m_text->appendText("["+FXSystem::time("%H:%M:%S", time) +"] "); appendLinkText(m_stripColors && !disableStrip ? stripColors(msg, FALSE) : msg, 0); if(logLine) this->logLine(stripColors(msg, TRUE), time); } void IrcTabItem::appendIrcNickText(FXString nick, FXString msg, FXint style, FXTime time, FXbool logLine) { if(!time) time = FXSystem::now(); if(m_type != OTHER) m_text->appendText("["+FXSystem::time("%H:%M:%S", time) +"] "); m_text->appendStyledText(nick+": ", style); appendLinkText(m_stripColors ? stripColors(msg, FALSE) : msg, 0); if(logLine) this->logLine(stripColors("<"+nick+"> "+msg, TRUE), time); } /* if highlight==TRUE, highlight tab * disableStrip is for dxirc.Print */ void IrcTabItem::appendStyledText(FXString text, FXint style, FXbool highlight, FXbool disableStrip, FXbool logLine) { if(style) appendIrcStyledText(text, style, 0, disableStrip, logLine); else appendIrcText(text, 0, disableStrip, logLine); if(highlight && m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) { if(m_type != OTHER && text.contains(getNickName())) { this->setTextColor(m_highlightColor); if(m_type == CHANNEL) this->setIcon(ICO_CHANNELNEWMSG); } else this->setTextColor(m_unreadColor); if(m_type == QUERY) this->setIcon(ICO_QUERYNEWMSG); } } void IrcTabItem::appendIrcStyledText(FXString styled, FXint stylenum, FXTime time, FXbool disableStrip, FXbool logLine) { if(!time) time = FXSystem::now(); if(m_type != OTHER) m_text->appendText("["+FXSystem::time("%H:%M:%S", time) +"] "); appendLinkText(m_stripColors && !disableStrip ? stripColors(styled, TRUE) : styled, stylenum); if(logLine) this->logLine(stripColors(styled, TRUE), time); } static FXbool isBadchar(FXchar c) { switch(c) { case ' ': case ',': case '\0': case '\02': case '\03': case '\017': case '\021': case '\026': case '\035': case '\037': case '\n': case '\r': case '<': case '>': case '"': case '\'': return TRUE; default: return FALSE; } } // checks is char nick/word delimiter static FXbool isDelimiter(FXchar c) { switch(c) { case ' ': case '.': case ',': case '/': case '\\': case '`': case '\'': case '!': case '(': case ')': case '{': case '}': case '|': case '[': case ']': case '\"': case ':': case ';': case '<': case '>': case '?': return TRUE; default: return FALSE; } } void IrcTabItem::appendLinkText(const FXString &txt, FXint stylenum) { FXint i = 0; FXint linkLength = 0; FXbool bold = FALSE; FXbool under = FALSE; FXint lastStyle = stylenum; FXColor foreColor = stylenum && stylenum<=m_textStyleList.no() ? m_textStyleList[stylenum-1].normalForeColor : m_colors.text; FXColor backColor = stylenum && stylenum<=m_textStyleList.no() ? m_textStyleList[stylenum-1].normalBackColor : m_colors.back; FXString normalText = ""; FXint length = txt.length(); while(i<length) { if(txt[i]=='h' && !comparecase(txt.mid(i,7),"http://")) { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } for(FXint j=i; j<length; j++) { if(isBadchar(txt[j])) { break; } linkLength++; } m_text->appendStyledText(txt.mid(i, linkLength), linkLength>7 ? 9 : stylenum); i+=linkLength-1; linkLength=0; } else if(txt[i]=='h' && !comparecase(txt.mid(i,8),"https://")) { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } for(FXint j=i; j<length; j++) { if(isBadchar(txt[j])) { break; } linkLength++; } m_text->appendStyledText(txt.mid(i, linkLength), linkLength>8 ? 9 : stylenum); i+=linkLength-1; linkLength=0; } else if(txt[i]=='f' && !comparecase(txt.mid(i,6),"ftp://")) { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } for(FXint j=i; j<length; j++) { if(isBadchar(txt[j])) { break; } linkLength++; } m_text->appendStyledText(txt.mid(i, linkLength), linkLength>6 ? 9 : stylenum); i+=linkLength-1; linkLength=0; } else if(txt[i]=='w' && !comparecase(txt.mid(i,4),"www.")) { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } for(FXint j=i; j<length; j++) { if(isBadchar(txt[j])) { break; } linkLength++; } m_text->appendStyledText(txt.mid(i, linkLength), linkLength>4 ? 9 : stylenum); i+=linkLength-1; linkLength=0; } else { if(txt[i] == '\002') //bold { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } bold = !bold; FXuint style = 0; if(bold && under) style = FXText::STYLE_BOLD|FXText::STYLE_UNDERLINE; else if(bold && !under) style = FXText::STYLE_BOLD; else if(!bold && under) style = FXText::STYLE_UNDERLINE; lastStyle = hiliteStyleExist(foreColor, backColor, style); if(lastStyle == -1) { //dxText has available max. 255 styles if(m_textStyleList.no()<256) { createHiliteStyle(foreColor, backColor, style); lastStyle = m_textStyleList.no(); } else lastStyle = 0; } } else if(txt[i] == '\026') //reverse { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } FXuint style = 0; if(bold && under) style = FXText::STYLE_BOLD|FXText::STYLE_UNDERLINE; else if(bold && !under) style = FXText::STYLE_BOLD; else if(!bold && under) style = FXText::STYLE_UNDERLINE; FXColor tempColor = foreColor; foreColor = backColor; backColor = tempColor; lastStyle = hiliteStyleExist(foreColor, backColor, style); if(lastStyle == -1) { //dxText has available max. 255 styles if(m_textStyleList.no()<256) { createHiliteStyle(foreColor, backColor, style); lastStyle = m_textStyleList.no(); } else lastStyle = 0; } } else if(txt[i] == '\037') //underline { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } under = !under; FXuint style = 0; if(bold && under) style = FXText::STYLE_BOLD|FXText::STYLE_UNDERLINE; else if(bold && !under) style = FXText::STYLE_BOLD; else if(!bold && under) style = FXText::STYLE_UNDERLINE; lastStyle = hiliteStyleExist(foreColor, backColor, style); if(lastStyle == -1) { //dxText has available max. 255 styles if(m_textStyleList.no()<256) { createHiliteStyle(foreColor, backColor, style); lastStyle = m_textStyleList.no(); } else lastStyle = 0; } } else if(txt[i] == '\021') //fixed { utils::instance().debugLine("Poslan fixed styl"); } else if(txt[i] == '\035') //italic { utils::instance().debugLine("Poslan italic styl"); } else if(txt[i] == '\003') //color { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } FXuint style=0; if(bold && under) style = FXText::STYLE_BOLD|FXText::STYLE_UNDERLINE; else if(bold && !under) style = FXText::STYLE_BOLD; else if(!bold && under) style = FXText::STYLE_UNDERLINE; FXbool isHexColor = FALSE; FXint colorLength = 0; foreColor = m_colors.text; backColor = m_colors.back; if(i+1<length) { if(txt[i+1] == '#') isHexColor = TRUE; } if(isHexColor) { if(FXRex("^\\h\\h\\h\\h\\h\\h+$").match(txt.mid(i+2,6))) { foreColor = FXRGB(FXIntVal(txt.mid(i+2,2),16),FXIntVal(txt.mid(i+4,2),16),FXIntVal(txt.mid(i+6,2),16)); colorLength +=7; } if(i+8 < length && txt[i+8] == ',' && FXRex("^\\h\\h\\h\\h\\h\\h+$").match(txt.mid(i+10,6))) { backColor = FXRGB(FXIntVal(txt.mid(i+10,2),16),FXIntVal(txt.mid(i+12,2),16),FXIntVal(txt.mid(i+14,2),16)); colorLength +=8; } } else { if(i+2<length) { FXint code = -1; if(isdigit(txt[i+1])) { if(isdigit(txt[i+2])) { code = (txt[i+1]-48)*10+txt[i+2]-48; colorLength +=2; } else { code = txt[i+1]-48; colorLength ++; } } if(code!=-1) foreColor = getIrcColor(code%16); } if(i+colorLength+1 < length && txt[i+colorLength+1] == ',') { FXint code = -1; if(isdigit(txt[i+colorLength+2])) { if(isdigit(txt[i+colorLength+3])) { code = (txt[i+colorLength+2]-48)*10+txt[i+colorLength+3]-48; colorLength +=3; } else { code = txt[i+colorLength+2]-48; colorLength +=2; } } if(code!=-1) backColor = getIrcColor(code%16); } } lastStyle = hiliteStyleExist(foreColor, backColor, style); if(lastStyle == -1) { //dxText has available max. 255 styles if(m_textStyleList.no()<256) { createHiliteStyle(foreColor, backColor, style); lastStyle = m_textStyleList.no(); } else lastStyle = 0; }; i +=colorLength; } else if(txt[i] == '\017') //reset { if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); normalText.clear(); } bold = FALSE; under = FALSE; foreColor = m_colors.text; backColor = m_colors.back; lastStyle = stylenum; } else { normalText.append(txt[i]); } } i++; } if(!normalText.empty()) { m_text->appendStyledText(normalText, lastStyle); } m_text->appendText("\n"); } void IrcTabItem::startLogging() { if(m_logstream && FXStat::exists(m_logPath+PATHSEPSTRING+m_engine->getNetworkName()+PATHSEPSTRING+getText()+PATHSEPSTRING+FXSystem::time("%Y-%m-%d", FXSystem::now()))) return; if(m_logging && m_type != SERVER) { if(!FXStat::exists(m_logPath+PATHSEPSTRING+m_engine->getNetworkName())) FXDir::create(m_logPath+PATHSEPSTRING+m_engine->getNetworkName()); if(!FXStat::exists(m_logPath+PATHSEPSTRING+m_engine->getNetworkName()+PATHSEPSTRING+getText())) FXDir::create(m_logPath+PATHSEPSTRING+m_engine->getNetworkName()+PATHSEPSTRING+getText()); m_logstream = new std::ofstream(FXString(m_logPath+PATHSEPSTRING+m_engine->getNetworkName()+PATHSEPSTRING+getText()+PATHSEPSTRING+FXSystem::time("%Y-%m-%d", FXSystem::now())).text(), std::ios::out|std::ios::app); } } void IrcTabItem::stopLogging() { if(m_logstream) { m_logstream->close(); delete m_logstream; m_logstream = NULL; } } void IrcTabItem::logLine(const FXString &line, const FXTime &time) { if(m_logging && m_type != SERVER) { this->startLogging(); *m_logstream << "[" << FXSystem::time("%H:%M:%S", time).text() << "] " << line.text() << std::endl; } } FXbool IrcTabItem::isChannel(const FXString &text) { if(text.length()) return m_engine->getChanTypes().contains(text[0]); return FALSE; } long IrcTabItem::onCommandline(FXObject *, FXSelector, void *) { FXString commandtext = m_commandline->getText(); if(commandtext.empty()) return 1; m_commandsHistory.append(commandtext); if (m_commandsHistory.no() > m_historyMax) m_commandsHistory.erase(0); m_currentPosition = m_commandsHistory.no()-1; m_commandline->setText(""); if(comparecase(commandtext.left(4),"/say") != 0) commandtext.substitute("^B", "\002").substitute("^C", "\003").substitute("^O", "\017").substitute("^V", "\026").substitute("^_", "\037"); for(FXint i=0; i<=commandtext.contains('\n'); i++) { FXString text = commandtext.section('\n', i).before('\r'); if(comparecase(text.after('/').before(' '), "quit") == 0 || comparecase(text.after('/').before(' '), "lua") == 0) { processLine(text); return 1; } #ifdef HAVE_LUA if(text[0] != '/') m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_MYMSG), &text); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_COMMAND), &text); if(text[0] == '/' && !m_scriptHasAll) processLine(text); else if(!m_scriptHasMyMsg && !m_scriptHasAll) processLine(text); #else processLine(text); #endif } return 1; } FXbool IrcTabItem::processLine(const FXString& commandtext) { FXString command = (commandtext[0] == '/' ? commandtext.before(' ') : ""); if(!utils::instance().getAlias(command).empty()) { FXString acommand = utils::instance().getAlias(command); if(acommand.contains("%s")) acommand.substitute("%s", commandtext.after(' ')); else acommand += commandtext.after(' '); FXint num = acommand.contains("&&"); if(num) { FXbool result = FALSE; for(FXint i=0; i<=acommand.contains('&'); i++) { if(!acommand.section('&',i).trim().empty()) result = processCommand(acommand.section('&',i).trim()); } return result; } else { return processCommand(acommand); } } return processCommand(commandtext); } FXbool IrcTabItem::processCommand(const FXString& commandtext) { FXString command = (commandtext[0] == '/' ? commandtext.after('/').before(' ').lower() : ""); if(m_type == OTHER) { if(utils::instance().isScriptCommand(command)) { LuaRequest lua; lua.type = LUA_COMMAND; lua.text = commandtext.after('/'); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_LUA), &lua); return TRUE; } if(command == "commands") { appendIrcStyledText(utils::instance().availableScriptsCommands(), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "egg") { m_text->clearText(); m_text->appendStyledText(FXString("ahoj sem pan Vajíčko.\n"), 3); getApp()->addTimeout(this, IrcTabItem_ETIME, 1000); m_pics = 0; return TRUE; } if(command == "help") { return showHelp(commandtext.after(' ').lower().trim()); } if(command == "tetris") { m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_NEWTETRIS), NULL); return TRUE; } return TRUE; } if(commandtext[0] == '/') { if(utils::instance().isScriptCommand(command)) { LuaRequest lua; lua.type = LUA_COMMAND; lua.text = commandtext.after('/'); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_LUA), &lua); return TRUE; } if(command == "admin") { if(m_engine->getConnected()) return m_engine->sendAdmin(commandtext.after(' ')); else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "away") { if(m_engine->getConnected()) { if(commandtext.after(' ').length() > m_engine->getAwayLen()) { appendIrcStyledText(FXStringFormat(_("Warning: Away message is too long. Max. away message length is %d."), m_engine->getAwayLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendAway(commandtext.after(' ')); } else return m_engine->sendAway(commandtext.after(' ')); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "banlist") { if(m_engine->getConnected()) { FXString channel = commandtext.after(' '); if(channel.empty() && m_type == CHANNEL) return m_engine->sendBanlist(getText()); else if(!isChannel(channel) && m_type != CHANNEL) { appendIrcStyledText(_("/banlist <channel>, shows banlist for channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else return m_engine->sendBanlist(channel); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "connect") { if(commandtext.after(' ').empty()) { appendIrcStyledText(_("/connect <server> [port] [nick] [password] [realname] [channels], connects for given server."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else { ServerInfo srv; srv.hostname = commandtext.after(' ').section(' ', 0); srv.port = commandtext.after(' ').section(' ', 1).empty() ? 6667 : FXIntVal(commandtext.after(' ').section(' ', 1)); srv.nick = commandtext.after(' ').section(' ', 2).empty() ? FXSystem::currentUserName() : commandtext.after(' ').section(' ', 2); srv.passwd = commandtext.after(' ').section(' ', 3).empty() ? "" : commandtext.after(' ').section(' ', 3); srv.realname = commandtext.after(' ').section(' ', 4).empty() ? FXSystem::currentUserName() : commandtext.after(' ').section(' ', 4); srv.channels = commandtext.after(' ').section(' ', 5).empty() ? "" : commandtext.after(' ').section(' ', 5); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CSERVER), &srv); return TRUE; } } if(command == "commands") { appendIrcStyledText(utils::instance().availableCommands(), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "ctcp") { if(m_engine->getConnected()) { FXString to = commandtext.after(' ').before(' '); FXString msg = commandtext.after(' ', 2); if(to.empty() || msg.empty()) { appendIrcStyledText(_("/ctcp <nick> <message>, sends a CTCP message to a user."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(msg.length() > m_maxLen-12-to.length()) { appendIrcStyledText(FXStringFormat(_("Warning: ctcp message is too long. Max. ctcp message length is %d."), m_maxLen-12-to.length()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendCtcp(to, msg); } else return m_engine->sendCtcp(to, msg); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "cycle") { if(m_engine->getConnected()) { if(m_type == CHANNEL) { if(isChannel(commandtext.after(' '))) { FXString channel = commandtext.after(' ').before(' '); FXString reason = commandtext.after(' ', 2); reason.empty() ? m_engine->sendPart(channel) : m_engine->sendPart(channel, reason); return m_engine->sendJoin(channel); } else { commandtext.after(' ').empty() ? m_engine->sendPart(getText()) : m_engine->sendPart(getText(), commandtext.after(' ')); return m_engine->sendJoin(getText()); } } else { if(isChannel(commandtext.after(' '))) { FXString channel = commandtext.after(' ').before(' '); FXString reason = commandtext.after(' ', 2); reason.empty() ? m_engine->sendPart(channel) : m_engine->sendPart(channel, reason); return m_engine->sendJoin(channel); } else { appendIrcStyledText(_("/cycle <channel> [message], leaves and join channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "dcc") { if(m_engine->getConnected()) { FXString dccCommand = utils::instance().getParam(commandtext, 2, FALSE).lower(); if(dccCommand == "chat") { FXString nick = utils::instance().getParam(commandtext, 3, FALSE); if(!comparecase(nick, "chat")) { appendIrcStyledText(_("Nick for chat wasn't entered."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(!comparecase(nick, getNickName())) { appendIrcStyledText(_("Chat with yourself isn't good idea."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } IrcEvent ev; ev.eventType = IRC_DCCSERVER; ev.param1 = nick; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); return TRUE; } else if(dccCommand == "send") { FXString nick = utils::instance().getParam(commandtext, 3, FALSE); FXString file = utils::instance().getParam(commandtext, 4, TRUE); if(!comparecase(nick, "send")) { appendIrcStyledText(_("Nick for sending file wasn't entered."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(!comparecase(nick, getNickName())) { appendIrcStyledText(_("Sending to yourself isn't good idea."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(!comparecase(nick, file)) { appendIrcStyledText(_("Filename wasn't entered"), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(!FXStat::exists(file)) { appendIrcStyledText(FXStringFormat(_("File '%s' doesn't exist"), file.text()), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } IrcEvent ev; ev.eventType = IRC_DCCOUT; ev.param1 = nick; ev.param2 = file; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); return TRUE; } else if(dccCommand == "psend") { FXString nick = utils::instance().getParam(commandtext, 3, FALSE); FXString file = utils::instance().getParam(commandtext, 4, TRUE); if(!comparecase(nick, "psend")) { appendIrcStyledText(_("Nick for sending file wasn't entered."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(!comparecase(nick, getNickName())) { appendIrcStyledText(_("Sending to yourself isn't good idea."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(!comparecase(nick, file)) { appendIrcStyledText(_("Filename wasn't entered"), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(!FXStat::exists(file)) { appendIrcStyledText(FXStringFormat(_("File '%s' doesn't exist"), file.text()), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } IrcEvent ev; ev.eventType = IRC_DCCPOUT; ev.param1 = nick; ev.param2 = file; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); return TRUE; } else { appendIrcStyledText(FXStringFormat(_("'%s' isn't dcc command <chat|send|psend>"), dccCommand.text()), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "deop") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) { appendIrcStyledText(_("/deop <nicks>, removes operator status from one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && params.after(' ').empty()) { appendIrcStyledText(_("/deop <channel> <nicks>, removes operator status from one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('-', 'o', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { FXString channel = getText(); FXString nicks = params; FXString modeparams = utils::instance().createModes('-', 'o', nicks); return m_engine->sendMode(channel+" "+modeparams); } } else { if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('-', 'o', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { appendIrcStyledText(_("/deop <channel> <nicks>, removes operator status from one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "devoice") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) { appendIrcStyledText(_("/devoice <nicks>, removes voice from one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && params.after(' ').empty()) { appendIrcStyledText(_("/devoice <channel> <nicks>, removes voice from one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('-', 'v', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { FXString channel = getText(); FXString nicks = params; FXString modeparams = utils::instance().createModes('-', 'v', nicks); return m_engine->sendMode(channel+" "+modeparams); } } else { if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('-', 'v', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { appendIrcStyledText(_("/devoice <channel> <nicks>, removes voice from one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "disconnect") { if(m_engine->getConnected()) { if(commandtext.after(' ').empty()) m_engine->disconnect(); else m_engine->disconnect(commandtext.after(' ')); return TRUE; } else { m_engine->closeConnection(TRUE); return TRUE; } } if(command == "dxirc") { for(FXint i=0; i<5+rand()%5; i++) { appendIrcText("", FXSystem::now(), FALSE, FALSE); } appendIrcText(" __ __ _", FXSystem::now(), FALSE, FALSE); appendIrcText(" _/__//__/|_ | | _", FXSystem::now(), FALSE, FALSE); appendIrcText(" /_| |_| |/_/| __| |__ __|_| _ _ ___", FXSystem::now(), FALSE, FALSE); appendIrcText(" |_ _ _|/ / _ |\\ \\/ /| || '_)/ __)", FXSystem::now(), FALSE, FALSE); appendIrcText(" /_| |_| |/_/| | (_| | | | | || | | (__", FXSystem::now(), FALSE, FALSE); appendIrcText(" |_ _ _|/ \\____|/_/\\_\\|_||_| \\___)", FXSystem::now(), FALSE, FALSE); appendIrcText(" |_|/|_|/ (c) 2008~ David Vachulka", FXSystem::now(), FALSE, FALSE); appendIrcText(" http://dxirc.org", FXSystem::now(), FALSE, FALSE); for(FXint i=0; i<5+rand()%5; i++) { appendIrcText("", FXSystem::now(), FALSE, FALSE); } return TRUE; } if(command == "egg") { m_text->clearText(); m_text->appendStyledText(FXString("ahoj sem pan Vajíčko.\n"), 3); getApp()->addTimeout(this, IrcTabItem_ETIME, 1000); m_pics = 0; return TRUE; } if(command == "exec") { FXString params = commandtext.after(' '); if(params.empty()) { appendIrcStyledText(_("/exec [-o|-c] <command>, executes command, -o sends output to channel/query, -c closes running command."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else { if(!m_pipe) m_pipe = new dxPipe(getApp(), this); m_pipeStrings.clear(); if(params.before(' ').contains("-o")) { m_sendPipe = TRUE; m_pipe->execCmd(params.after(' ')); } else if(params.before(' ').contains("-c")) { m_sendPipe = FALSE; m_pipeStrings.clear(); m_pipe->stopCmd(); } else { m_sendPipe = FALSE; m_pipe->execCmd(params); } return TRUE; } } if(command == "help") { return showHelp(commandtext.after(' ').lower().trim()); } if(command == "ignore") { FXString ignorecommand = commandtext.after(' ').before(' '); FXString ignoretext = commandtext.after(' ').after(' '); if(ignorecommand.empty()) { appendIrcStyledText(_("/ignore <list|addcmd|rmcmd|addusr|rmusr> [command|user] [channel] [server]"), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(comparecase(ignorecommand, "list")==0) { appendIrcStyledText(_("Ignored commands:"), 7, FXSystem::now(), FALSE, FALSE); if(m_commandsList.empty()) appendIrcText(_("No ignored commands"), FXSystem::now(), FALSE, FALSE); else appendIrcText(m_commandsList.rbefore(';'), FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("Ignored users:"), 7, FXSystem::now(), FALSE, FALSE); dxIgnoreUserArray users = m_engine->getUsersList(); if(!users.no()) appendIrcText(_("No ignored users"), FXSystem::now(), FALSE, FALSE); else { for(FXint i=0; i<users.no(); i++) { appendIrcText(FXStringFormat(_("%s on channel(s): %s and network: %s"), users[i].nick.text(), users[i].channel.text(), users[i].network.text()), FXSystem::now(), FALSE, FALSE); } } return TRUE; } else if(comparecase(ignorecommand, "addcmd")==0) { if(ignoretext.empty()) { appendIrcStyledText(_("/ignore addcmd <command>, adds command to ignored commands."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_ADDICOMMAND), &ignoretext); return TRUE; } else if(comparecase(ignorecommand, "rmcmd")==0) { if(ignoretext.empty()) { appendIrcStyledText(_("/ignore rmcmd <command>, removes command from ignored commands."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_RMICOMMAND), &ignoretext); return TRUE; } else if(comparecase(ignorecommand, "addusr")==0) { if(ignoretext.empty()) { appendIrcStyledText(_("/ignore addusr <user> [channel] [server], adds user to ignored users."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_ADDIUSER), &ignoretext); return TRUE; } else if(comparecase(ignorecommand, "rmusr")==0) { if(ignoretext.empty()) { appendIrcStyledText(_("/ignore rmusr <user>, removes user from ignored users."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_RMIUSER), &ignoretext); return TRUE; } else { appendIrcStyledText(FXStringFormat(_("'%s' isn't <list|addcmd|rmcmd|addusr|rmusr>"), ignorecommand.text()), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } if(command == "invite") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(params.empty()) { appendIrcStyledText(_("/invite <nick> <channel>, invites someone to a channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && params.after(' ').empty()) { appendIrcStyledText(_("/invite <nick> <channel>, invites someone to a channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else { FXString nick = params.before(' '); FXString channel = params.after(' '); return m_engine->sendInvite(nick, channel); } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "join") { if(m_engine->getConnected()) { FXString channel = commandtext.after(' '); if(!isChannel(channel)) { appendIrcStyledText(_("/join <channel>, joins a channel."), 4, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(FXStringFormat(_("'%c' isn't valid char for channel."), channel[0]), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else return m_engine->sendJoin(channel); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "kick") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) { appendIrcStyledText(_("/kick <nick>, kicks a user from a channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && params.after(' ').empty()) { appendIrcStyledText(_("/kick <channel> <nick>, kicks a user from a channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nick = params.after(' '); FXString reason = params.after(' ', 2); if(reason.length() > m_engine->getKickLen()) { appendIrcStyledText(FXStringFormat(_("Warning: reason of kick is too long. Max. reason length is %d."), m_engine->getKickLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendKick(channel, nick, reason); } else return m_engine->sendKick(channel, nick, reason); } else { FXString channel = getText(); FXString nick = params.before(' '); FXString reason = params.after(' '); if(reason.length() > m_engine->getKickLen()) { appendIrcStyledText(FXStringFormat(_("Warning: reason of kick is too long. Max. reason length is %d."), m_engine->getKickLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendKick(channel, nick, reason); } else return m_engine->sendKick(channel, nick, reason); } } else { if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nick = params.after(' '); FXString reason = params.after(' ', 2); if(reason.length() > m_engine->getKickLen()) { appendIrcStyledText(FXStringFormat(_("Warning: reason of kick is too long. Max. reason length is %d."), m_engine->getKickLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendKick(channel, nick, reason); } else return m_engine->sendKick(channel, nick, reason); } else { appendIrcStyledText(_("/kick <channel> <nick>, kicks a user from a channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "kill") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); FXString nick = params.before(' '); FXString reason = params.after(' '); if(params.empty()) { appendIrcStyledText(_("/kill <user> [reason], kills a user from the network."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(reason.length() > m_maxLen-7-nick.length()) { appendIrcStyledText(FXStringFormat(_("Warning: reason of kill is too long. Max. reason length is %d."), m_maxLen-7-nick.length()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendKill(nick, reason); } else return m_engine->sendKill(nick, reason); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "list") { if(m_engine->getConnected()) return m_engine->sendList(commandtext.after(' ')); else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "lua") { #ifdef HAVE_LUA FXString luacommand = commandtext.after(' ').before(' '); FXString luatext = commandtext.after(' ').after(' '); LuaRequest lua; if(luacommand.empty()) { appendIrcStyledText(_("/lua <help|load|unload|list> [scriptpath|scriptname]"), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } if(comparecase(luacommand, "help")==0) { appendIrcStyledText(FXStringFormat(_("For help about Lua scripting visit: %s"), LUA_HELP_PATH), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } else if(comparecase(luacommand, "load")==0) lua.type = LUA_LOAD; else if(comparecase(luacommand, "unload")==0) lua.type = LUA_UNLOAD; else if(comparecase(luacommand, "list")==0) lua.type = LUA_LIST; else { appendIrcStyledText(FXStringFormat(_("'%s' isn't <help|load|unload|list>"), luacommand.text()), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } lua.text = luatext; m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_LUA), &lua); return TRUE; #else appendIrcStyledText(_("dxirc is compiled without support for Lua scripting"), 4, FXSystem::now(), FALSE, FALSE); return FALSE; #endif } if(command == "me") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) { appendIrcStyledText(_("/me <message>, sends the action to the current channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString message = params.after(' '); if(channel == getText()) { appendIrcStyledText(getNickName()+" "+message, 2, FXSystem::now()); IrcEvent ev; ev.eventType = IRC_ACTION; ev.param1 = getNickName(); ev.param2 = channel; ev.param3 = message; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); } if(message.length() > m_maxLen-19-channel.length()) { dxStringArray messages = cutText(message, m_maxLen-19-channel.length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendMe(channel, messages[i]) &result; } return result; } else return m_engine->sendMe(channel, message); } else { appendIrcStyledText(getNickName()+" "+params, 2, FXSystem::now()); IrcEvent ev; ev.eventType = IRC_ACTION; ev.param1 = getNickName(); ev.param2 = getText(); ev.param3 = params; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); if(params.length() > m_maxLen-19-getText().length()) { dxStringArray messages = cutText(params, m_maxLen-19-getText().length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendMe(getText(), messages[i]) &result; } return result; } else return m_engine->sendMe(getText(), params); } } else if(m_type == QUERY) { if(params.empty()) { appendIrcStyledText(_("/me <message>, sends the action to the current query."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else { appendIrcStyledText(getNickName()+" "+params, 2, FXSystem::now()); IrcEvent ev; ev.eventType = IRC_ACTION; ev.param1 = getNickName(); ev.param2 = getText(); ev.param3 = params; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); if(params.length() > m_maxLen-19-getText().length()) { dxStringArray messages = cutText(params, m_maxLen-19-getText().length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendMe(getText(), messages[i]) &result; } return result; } else return m_engine->sendMe(getText(), params); } } else { if(!params.after(' ').empty()) { FXString to = params.before(' '); FXString message = params.after(' '); if(message.length() > m_maxLen-19-to.length()) { dxStringArray messages = cutText(message, m_maxLen-19-to.length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendMe(to, messages[i]) &result; } return result; } else return m_engine->sendMe(to, message); } else { appendIrcStyledText(_("/me <to> <message>, sends the action."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "mode") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(params.empty()) { appendIrcStyledText(_("/mode <channel> <modes>, sets modes for a channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else return m_engine->sendMode(params); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "msg") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); FXString to = params.before(' '); FXString message = params.after(' '); if(!to.empty() && !message.empty()) { if(to == getText()) { if(m_coloredNick) appendIrcNickText(getNickName(), message, getNickColor(getNickName()), FXSystem::now()); else appendIrcNickText(getNickName(), message, 5, FXSystem::now()); IrcEvent ev; ev.eventType = IRC_PRIVMSG; ev.param1 = getNickName(); ev.param2 = to; ev.param3 = message; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); } if(message.length() > m_maxLen-10-to.length()) { dxStringArray messages = cutText(message, m_maxLen-10-to.length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendMsg(to, messages[i]) &result; } return result; } else return m_engine->sendMsg(to, message); } else { appendIrcStyledText(_("/msg <nick/channel> <message>, sends a normal message."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "names") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) return m_engine->sendNames(getText()); else return m_engine->sendNames(params); } else { if(params.empty()) { appendIrcStyledText(_("/names <channel>, for nicks on a channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else return m_engine->sendNames(params); } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "nick") { if(m_engine->getConnected()) { FXString nick = commandtext.after(' '); if(nick.empty()) { appendIrcStyledText(_("/nick <nick>, changes nick."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(nick.length() > m_engine->getNickLen()) { appendIrcStyledText(FXStringFormat(_("Warning: nick is too long. Max. nick length is %d."), m_engine->getNickLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendNick(nick); } else { return m_engine->sendNick(nick); } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "notice") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); FXString to = params.before(' '); FXString message = params.after(' '); if(!to.empty() && !message.empty()) { appendIrcStyledText(FXStringFormat(_("NOTICE to %s: %s"), to.text(), message.text()), 2, FXSystem::now()); if(message.length() > m_maxLen-9-to.length()) { dxStringArray messages = cutText(message, m_maxLen-9-to.length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendNotice(to, messages[i]) &result; } return result; } return m_engine->sendNotice(to, message); } else { appendIrcStyledText(_("/notice <nick/channel> <message>, sends a notice."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "op") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) { appendIrcStyledText(_("/op <nicks>, gives operator status for one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && params.after(' ').empty()) { appendIrcStyledText(_("/op <channel> <nicks>, gives operator status for one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('+', 'o', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { FXString channel = getText(); FXString nicks = params; FXString modeparams = utils::instance().createModes('+', 'o', nicks); return m_engine->sendMode(channel+" "+modeparams); } } else { if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('+', 'o', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { appendIrcStyledText(_("/op <channel> <nicks>, gives operator status for one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "oper") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); FXString login = params.before(' '); FXString password = params.after(' '); if(!login.empty() && !password.empty()) return m_engine->sendOper(login, password); else { appendIrcStyledText(_("/oper <login> <password>, oper up."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "part") { if(m_engine->getConnected()) { if(m_type == CHANNEL) { if(commandtext.after(' ').empty()) return m_engine->sendPart(getText()); else return m_engine->sendPart(getText(), commandtext.after(' ')); } else { if(isChannel(commandtext.after(' '))) { FXString channel = commandtext.after(' ').before(' '); FXString reason = commandtext.after(' ', 2); if(reason.empty()) return m_engine->sendPart(channel); else return m_engine->sendPart(channel, reason); } else { appendIrcStyledText(_("/part <channel> [reason], leaves channel."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "query") { if(m_engine->getConnected()) { if(commandtext.after(' ').empty()) { appendIrcStyledText(_("/query <nick>, opens query with nick."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else { IrcEvent ev; ev.eventType = IRC_QUERY; ev.param1 = commandtext.after(' ').before(' '); ev.param2 = getNickName(); m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); return TRUE; } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "quit") { m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CQUIT), NULL); return TRUE; } if(command == "quote") { if(m_engine->getConnected()) return m_engine->sendQuote(commandtext.after(' ')); else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "say") { if(m_engine->getConnected()) { if (m_type != SERVER && !commandtext.after(' ').empty()) { if(m_coloredNick) appendIrcNickText(getNickName(), commandtext.after(' '), getNickColor(getNickName()), FXSystem::now()); else appendIrcNickText(getNickName(), commandtext.after(' '), 5, FXSystem::now()); IrcEvent ev; ev.eventType = IRC_PRIVMSG; ev.param1 = getNickName(); ev.param2 = getText(); ev.param3 = commandtext.after(' '); m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); if(commandtext.after(' ').length() > m_maxLen-10-getText().length()) { dxStringArray messages = cutText(commandtext.after(' '), m_maxLen-10-getText().length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendMsg(getText(), messages[i]) &result; } return result; } else return m_engine->sendMsg(getText(), commandtext.after(' ')); } return FALSE; } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "stats") { if(m_engine->getConnected()) return m_engine->sendStats(commandtext.after(' ')); else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "tetris") { m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_NEWTETRIS), NULL); return TRUE; } if(command == "time") { if(m_engine->getConnected()) return m_engine->sendQuote("TIME"); else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "topic") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) return m_engine->sendTopic(getText()); else if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString topic = params.after(' '); if(topic.length() > m_engine->getTopicLen()) { appendIrcStyledText(FXStringFormat(_("Warning: topic is too long. Max. topic length is %d."), m_engine->getTopicLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendTopic(channel, topic); } else return m_engine->sendTopic(channel, topic); } else { if(params.length() > m_engine->getTopicLen()) { appendIrcStyledText(FXStringFormat(_("Warning: topic is too long. Max. topic length is %d."), m_engine->getTopicLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendTopic(getText(), params); } else return m_engine->sendTopic(getText(), params); } } else { if(isChannel(params)) { FXString channel = params.before(' '); FXString topic = params.after(' '); if(topic.length() > m_engine->getTopicLen()) { appendIrcStyledText(FXStringFormat(_("Warning: topic is too long. Max. topic length is %d."), m_engine->getTopicLen()), 4, FXSystem::now(), FALSE, FALSE); return m_engine->sendTopic(channel, params); } else return m_engine->sendTopic(channel, topic); } else { appendIrcStyledText(_("/topic <channel> [topic], views or changes channel topic."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "voice") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(m_type == CHANNEL) { if(params.empty()) { appendIrcStyledText(_("/voice <nicks>, gives voice for one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && params.after(' ').empty()) { appendIrcStyledText(_("/voice <channel> <nicks>, gives voice for one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('+', 'v', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { FXString channel = getText(); FXString nicks = params; FXString modeparams = utils::instance().createModes('+', 'v', nicks); return m_engine->sendMode(channel+" "+modeparams); } } else { if(isChannel(params) && !params.after(' ').empty()) { FXString channel = params.before(' '); FXString nicks = params.after(' '); FXString modeparams = utils::instance().createModes('+', 'v', nicks); return m_engine->sendMode(channel+" "+modeparams); } else { appendIrcStyledText(_("/voice <channel> <nicks>, gives voice for one or more nicks."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "wallops") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(params.empty()) { appendIrcStyledText(_("/wallops <message>, sends wallop message."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else { if(params.length() > m_maxLen-9) { dxStringArray messages = cutText(params, m_maxLen-9); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendWallops(messages[i]) &result; } return result; } else return m_engine->sendWallops(params); } } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "who") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(params.empty()) { appendIrcStyledText(_("/who <mask> [o], searchs for mask on network, if o is supplied, only search for opers."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else return m_engine->sendWho(params); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "whoami") { if(m_engine->getConnected()) return m_engine->sendWhoami(); else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "whois") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(params.empty()) { if(m_type == QUERY) return m_engine->sendWhois(getText()); appendIrcStyledText(_("/whois <nick>, whois nick."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else return m_engine->sendWhois(params); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } if(command == "whowas") { if(m_engine->getConnected()) { FXString params = commandtext.after(' '); if(params.empty()) { appendIrcStyledText(_("/whowas <nick>, whowas nick."), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else return m_engine->sendWhowas(params); } else { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } } appendIrcStyledText(FXStringFormat(_("Unknown command '%s', type /commands for available commands"), command.text()), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } else { if (command.empty() && m_type != SERVER && !commandtext.empty() && m_engine->getConnected()) { if(m_coloredNick) appendIrcNickText(getNickName(), commandtext, getNickColor(getNickName()), FXSystem::now()); else appendIrcNickText(getNickName(), commandtext, 5, FXSystem::now()); IrcEvent ev; ev.eventType = IRC_PRIVMSG; ev.param1 = getNickName(); ev.param2 = getText(); ev.param3 = commandtext; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); if(commandtext.length() > m_maxLen-10-getText().length()) { dxStringArray messages = cutText(commandtext, m_maxLen-10-getText().length()); FXbool result = TRUE; for(FXint i=0; i<messages.no(); i++) { result = m_engine->sendMsg(getText(), messages[i]) &result; } return result; } else return m_engine->sendMsg(getText(), commandtext); } if(!m_engine->getConnected()) { appendIrcStyledText(_("You aren't connected"), 4, FXSystem::now(), FALSE, FALSE); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_CDIALOG), NULL); return TRUE; } return FALSE; } return FALSE; } FXbool IrcTabItem::showHelp(FXString command) { if(utils::instance().isScriptCommand(command)) { appendIrcStyledText(utils::instance().getHelpText(command), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "admin") { appendIrcStyledText(_("ADMIN [server], finds information about administrator for current server or [server]."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "away") { appendIrcStyledText(_("AWAY [message], sets away status."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "banlist") { appendIrcStyledText(_("BANLIST <channel>, shows banlist for channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "commands") { appendIrcStyledText(_("COMMANDS, shows available commands"), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "connect") { appendIrcStyledText(_("CONNECT <server> [port] [nick] [password] [realname] [channels], connects for given server."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "ctcp") { appendIrcStyledText(_("CTCP <nick> <message>, sends a CTCP message to a user."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "cycle") { appendIrcStyledText(_("CYCLE <channel> [message], leaves and join channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "dcc") { appendIrcStyledText(_("DCC chat <nick>, starts DCC chat."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("DCC send <nick> <filename>, sends file over DCC."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("DCC psend <nick> <filename>, sends file passive over DCC."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("More information about passive DCC on http://en.wikipedia.org/wiki/Direct_Client-to-Client#Passive_DCC"), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "deop") { appendIrcStyledText(_("DEOP <channel> <nicks>, removes operator status from one or more nicks."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "devoice") { appendIrcStyledText(_("DEVOICE <channel> <nicks>, removes voice from one or more nicks."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "disconnect") { appendIrcStyledText(_("DISCONNECT [reason], leaves server."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } #ifndef WIN32 if(command == "exec") { appendIrcStyledText(_("EXEC [-o|-c] <command>, executes command, -o sends output to channel/query, -c closes running command."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } #endif if(command == "help") { appendIrcStyledText(_("HELP <command>, shows help for command."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "ignore") { appendIrcStyledText(_("IGNORE list, shows list ignored commands and users."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("IGNORE addcmd <command>, adds command to ignored commands."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("IGNORE rmcmd <command>, removes command from ignored commands."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("IGNORE addusr <user> [channel] [server], adds user to ignored users."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("IGNORE rmusr <user>, removes user from ignored users."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "invite") { appendIrcStyledText(_("INVITE <nick> <channel>, invites someone to a channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "join") { appendIrcStyledText(_("JOIN <channel>, joins a channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "kick") { appendIrcStyledText(_("KICK <channel> <nick>, kicks a user from a channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "kill") { appendIrcStyledText(_("KILL <user> [reason], kills a user from the network."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "list") { appendIrcStyledText(_("LIST [channel], lists channels and their topics."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } #ifdef HAVE_LUA if(command == "lua") { appendIrcStyledText(_("LUA help, shows help for lua scripting."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("LUA load <path>, loads script."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("Example: /lua load /home/dvx/test.lua"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("LUA unload <name>, unloads script."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("Example: /lua unload test"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("LUA list, shows list of loaded scripts"), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } #else if(command == "lua") { appendIrcStyledText(_("dxirc is compiled without support for Lua scripting"), 4, FXSystem::now(), FALSE, FALSE); return TRUE; } #endif if(command == "me") { appendIrcStyledText(_("ME <to> <message>, sends the action."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "mode") { appendIrcStyledText(_("MODE <channel> <modes>, sets modes for a channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "msg") { appendIrcStyledText(_("MSG <nick/channel> <message>, sends a normal message."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "names") { appendIrcStyledText(_("NAMES <channel>, for nicks on a channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "nick") { appendIrcStyledText(_("NICK <nick>, changes nick."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "notice") { appendIrcStyledText(_("NOTICE <nick/channel> <message>, sends a notice."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "op") { appendIrcStyledText(_("OP <channel> <nicks>, gives operator status for one or more nicks."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "oper") { appendIrcStyledText(_("OPER <login> <password>, oper up."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "part") { appendIrcStyledText(_("PART <channel> [reason], leaves channel."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "query") { appendIrcStyledText(_("QUERY <nick>, opens query with nick."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "quit") { appendIrcStyledText(_("QUIT, closes application."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "quote") { appendIrcStyledText(_("QUOTE [text], sends text to server."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "say") { appendIrcStyledText(_("SAY [text], sends text to current tab."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "stats") { appendIrcStyledText(_("STATS <type>, shows some irc server usage statistics. Available types vary slightly per server; some common ones are:"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("c - shows C and N lines for a given server. These are the names of the servers that are allowed to connect."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("h - shows H and L lines for a given server (Hubs and Leaves)."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("k - show K lines for a server. This shows who is not allowed to connect and possibly at what time they are not allowed to connect."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("i - shows I lines. This is who CAN connect to a server."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("l - shows information about amount of information passed to servers and users."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("m - shows a count for the number of times the various commands have been used since the server was booted."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("o - shows the list of authorized operators on the server."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("p - shows online operators and their idle times."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("u - shows the uptime for a server."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("y - shows Y lines, which lists the various connection classes for a given server."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "tetris") { appendIrcStyledText(_("TETRIS, start small easteregg."), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("Keys for playing:"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("n .. new game"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("p .. pause game"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("i .. rotate piece"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("l .. move piece right"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("k .. drop piece"), 3, FXSystem::now(), FALSE, FALSE); appendIrcStyledText(_("j .. move piece left"), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "time") { appendIrcStyledText(_("TIME, displays the time of day, local to server."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "topic") { appendIrcStyledText(_("TOPIC [topic], sets or shows topic."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "voice") { appendIrcStyledText(_("VOICE <channel> <nicks>, gives voice for one or more nicks."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "wallops") { appendIrcStyledText(_("WALLOPS <message>, sends wallop message."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "who") { appendIrcStyledText(_("WHO <mask> [o], searchs for mask on network, if o is supplied, only search for opers."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "whoami") { appendIrcStyledText(_("WHOAMI, whois about you."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "whois") { appendIrcStyledText(_("WHOIS <nick>, whois nick."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command == "whowas") { appendIrcStyledText(_("WHOWAS <nick>, whowas nick."), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(!utils::instance().getAlias(command[0] == '/' ? command:"/"+command).empty()) { appendIrcStyledText(FXStringFormat("%s: %s", command.upper().text(), utils::instance().getAlias(command[0] == '/' ? command:"/"+command).text()), 3, FXSystem::now(), FALSE, FALSE); return TRUE; } if(command.empty()) appendIrcStyledText(_("Command is empty, type /commands for available commands"), 4, FXSystem::now(), FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("Unknown command '%s', type /commands for available commands"), command.text()), 4, FXSystem::now(), FALSE, FALSE); return FALSE; } long IrcTabItem::onKeyPress(FXObject *, FXSelector, void *ptr) { if (m_commandline->hasFocus()) { FXEvent* event = (FXEvent*)ptr; FXString line = m_commandline->getText(); switch(event->code){ case KEY_Tab: if(event->state&CONTROLMASK) { m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_NEXTTAB), NULL); return 1; } if(line[0] == '/' && line.after(' ').empty()) { for(FXint i = 0; i < utils::instance().commandsNo(); i++) { if(comparecase(line.after('/').before(' '), utils::instance().commandsAt(i)) == 0) { if((i+1) < utils::instance().commandsNo()) m_commandline->setText("/"+utils::instance().commandsAt(++i)+" "); else m_commandline->setText("/"+utils::instance().commandsAt(0)+" "); break; } else if(comparecase(line.after('/'), utils::instance().commandsAt(i).left(line.after('/').length())) == 0) { m_commandline->setText("/"+utils::instance().commandsAt(i)+" "); break; } } return 1; } if(line[0] != '/' && line.after(' ').empty()) { if(line.empty()) { m_commandline->setText(getNick(0)+m_nickCompletionChar+" "); return 1; } for(FXint j = 0; j < m_users->getNumItems() ; j++) { if(comparecase(line, getNick(j).left(line.length())) == 0) { m_commandline->setText(getNick(j)+m_nickCompletionChar+" "); break; } else if(comparecase(line.section(m_nickCompletionChar, 0, 1), getNick(j)) == 0) { if((j+1) < m_users->getNumItems()) m_commandline->setText(getNick(++j)+m_nickCompletionChar+" "); else m_commandline->setText(getNick(0)+m_nickCompletionChar+" "); break; } } return 1; } if(line.find(' ') != -1) { FXint curpos; line[m_commandline->getCursorPos()] == ' ' ? curpos = m_commandline->getCursorPos()-1 : curpos = m_commandline->getCursorPos(); FXint pos = line.rfind(' ', curpos)+1; FXint n = line.find(' ', curpos)>0 ? line.find(' ', curpos)-pos : line.length()-pos; FXString toCompletion = line.mid(pos, n); for(FXint j = 0; j < m_users->getNumItems(); j++) { if(comparecase(toCompletion, getNick(j)) == 0) { if((j+1) < m_users->getNumItems()) { m_commandline->setText(line.replace(pos, n, getNick(j+1))); m_commandline->setCursorPos(pos+getNick(j+1).length()); } else { m_commandline->setText(line.replace(pos, n, getNick(0))); m_commandline->setCursorPos(pos+getNick(0).length()); } break; } else if(comparecase(toCompletion, getNick(j).left(toCompletion.length())) == 0) { m_commandline->setText(line.replace(pos, n, getNick(j))); m_commandline->setCursorPos(pos+getNick(j).length()); break; } } return 1; } return 1; case KEY_Up: if(m_currentPosition!=-1 && m_currentPosition<m_commandsHistory.no()) { if(!line.empty() && line!=m_commandsHistory[m_currentPosition]) { m_commandsHistory.append(line); if(m_commandsHistory.no() > m_historyMax) m_commandsHistory.erase(0); m_currentPosition = m_commandsHistory.no()-1; } if(m_currentPosition > 0 && !line.empty()) --m_currentPosition; m_commandline->setText(m_commandsHistory[m_currentPosition]); } return 1; case KEY_Down: if(m_currentPosition!=-1 && m_currentPosition<m_commandsHistory.no()) { if(!line.empty() && line!=m_commandsHistory[m_currentPosition]) { m_commandsHistory.append(line); if(m_commandsHistory.no() > m_historyMax) m_commandsHistory.erase(0); m_currentPosition = m_commandsHistory.no()-1; } if(m_currentPosition < m_commandsHistory.no()-1) { ++m_currentPosition; m_commandline->setText(m_commandsHistory[m_currentPosition]); } else m_commandline->setText(""); } return 1; case KEY_k: case KEY_K: if(event->state&CONTROLMASK) { FXint pos = m_commandline->getCursorPos(); m_commandline->setText(line.insert(pos, "^C")); //color m_commandline->setCursorPos(pos+2); return 1; } case KEY_b: case KEY_B: if(event->state&CONTROLMASK) { FXint pos = m_commandline->getCursorPos(); m_commandline->setText(line.insert(pos, "^B")); //bold m_commandline->setCursorPos(pos+2); return 1; } case KEY_i: case KEY_I: if(event->state&CONTROLMASK) { FXint pos = m_commandline->getCursorPos(); m_commandline->setText(line.insert(pos, "^_")); //underline m_commandline->setCursorPos(pos+2); return 1; } case KEY_r: case KEY_R: if(event->state&CONTROLMASK) { FXint pos = m_commandline->getCursorPos(); m_commandline->setText(line.insert(pos, "^V")); //reverse m_commandline->setCursorPos(pos+2); return 1; } case KEY_o: case KEY_O: if(event->state&CONTROLMASK) { FXint pos = m_commandline->getCursorPos(); m_commandline->setText(line.insert(m_commandline->getCursorPos(), "^O")); //reset m_commandline->setCursorPos(pos+2); return 1; } } } return 0; } //Check is this tab right for server message (e.g. not for IRC_SERVERREPLY) FXbool IrcTabItem::isRightForServerMsg() { //Check if current tab is in server targets if(m_engine->findTarget(m_parent->childAtIndex(m_parent->getCurrent()*2))) { return m_parent->indexOfChild(this) == m_parent->getCurrent()*2; } else { FXint indexOfThis = m_parent->indexOfChild(this); for(FXint i = 0; i<m_parent->numChildren(); i+=2) { if(m_engine->findTarget(m_parent->childAtIndex(i))) { if(i == indexOfThis) return TRUE; else return FALSE; } } } return FALSE; } FXbool IrcTabItem::isCommandIgnored(const FXString &command) { if(m_commandsList.contains(command)) return TRUE; return FALSE; } void IrcTabItem::addUser(const FXString& user, UserMode mode) { if(mode == ADMIN && m_users->findItem(user) == -1) { NickListItem *item = new NickListItem(user, m_users, this, mode, ICO_IRCADMIN); m_users->appendItem(item); m_numberUsers++; m_users->sortItems(); return; } if(mode == OWNER && m_users->findItem(user) == -1) { NickListItem *item = new NickListItem(user, m_users, this, mode, ICO_IRCOWNER); m_users->appendItem(item); m_numberUsers++; m_users->sortItems(); return; } if(mode == OP && m_users->findItem(user) == -1) { NickListItem *item = new NickListItem(user, m_users, this, mode, ICO_IRCOP); m_users->appendItem(item); m_numberUsers++; m_users->sortItems(); return; } if(mode == VOICE && m_users->findItem(user) == -1) { NickListItem *item = new NickListItem(user, m_users, this, mode, ICO_IRCVOICE); m_users->appendItem(item); m_numberUsers++; m_users->sortItems(); return; } if(mode == HALFOP && m_users->findItem(user) == -1) { NickListItem *item = new NickListItem(user, m_users, this, mode, ICO_IRCHALFOP); m_users->appendItem(item); m_numberUsers++; m_users->sortItems(); return; } if(mode == NONE && m_users->findItem(user) == -1) { NickListItem *item = new NickListItem(user, m_users, this, mode, ICO_IRCNORMAL); m_users->appendItem(item); m_numberUsers++; m_users->sortItems(); return; } } void IrcTabItem::removeUser(const FXString& user) { if(m_users->findItem(user) != -1) { m_users->removeItem(m_users->findItem(user)); } m_numberUsers--; m_users->sortItems(); } void IrcTabItem::changeNickUser(const FXString& nick, const FXString& newnick) { FXint i = m_users->findItem(nick); if(i != -1) { m_users->getItem(i)->setText(newnick); m_users->sortItems(); } } void IrcTabItem::setUserMode(const FXString& nick, UserMode mode) { FXint i = m_users->findItem(nick); if(i != -1) { ((NickListItem*)m_users->getItem(i))->setUserMode(mode); } } UserMode IrcTabItem::getUserMode(const FXchar mode) { if(mode == m_engine->getAdminPrefix()) return ADMIN; if(mode == m_engine->getOwnerPrefix()) return OWNER; if(mode == m_engine->getOpPrefix()) return OP; if(mode == m_engine->getHalfopPrefix()) return HALFOP; if(mode == m_engine->getVoicePrefix()) return VOICE; return NONE; } long IrcTabItem::onIrcEvent(FXObject *, FXSelector, void *data) { IrcEvent *ev = (IrcEvent *) data; if(ev->eventType == IRC_PRIVMSG) { onIrcPrivmsg(ev); return 1; } if(ev->eventType == IRC_ACTION) { onIrcAction(ev); return 1; } if(ev->eventType == IRC_CTCPREPLY) { onIrcCtpcReply(ev); return 1; } if(ev->eventType == IRC_CTCPREQUEST) { onIrcCtcpRequest(ev); return 1; } if(ev->eventType == IRC_JOIN) { onIrcJoin(ev); return 1; } if(ev->eventType == IRC_QUIT) { onIrcQuit(ev); return 1; } if(ev->eventType == IRC_PART) { onIrcPart(ev); return 1; } if(ev->eventType == IRC_CHNOTICE) { onIrcChnotice(ev); return 1; } if(ev->eventType == IRC_NOTICE) { onIrcNotice(ev); return 1; } if(ev->eventType == IRC_NICK) { onIrcNick(ev); return 1; } if(ev->eventType == IRC_TOPIC) { onIrcTopic(ev); return 1; } if(ev->eventType == IRC_INVITE) { onIrcInvite(ev); return 1; } if(ev->eventType == IRC_KICK) { onIrcKick(ev); return 1; } if(ev->eventType == IRC_MODE) { onIrcMode(ev); return 1; } if(ev->eventType == IRC_UMODE) { onIrcUmode(ev); return 1; } if(ev->eventType == IRC_CHMODE) { onIrcChmode(ev); return 1; } if(ev->eventType == IRC_SERVERREPLY) { onIrcServerReply(ev); return 1; } if(ev->eventType == IRC_CONNECT) { onIrcConnect(ev); return 1; } if(ev->eventType == IRC_ERROR) { onIrcError(ev); return 1; } if(ev->eventType == IRC_SERVERERROR) { onIrcServerError(ev); return 1; } if(ev->eventType == IRC_DISCONNECT) { onIrcDisconnect(ev); return 1; } if(ev->eventType == IRC_RECONNECT) { onIrcReconnect(ev); return 1; } if(ev->eventType == IRC_UNKNOWN) { onIrcUnknown(ev); return 1; } if(ev->eventType == IRC_301) { onIrc301(ev); return 1; } if(ev->eventType == IRC_305) { onIrc305(ev); return 1; } if(ev->eventType == IRC_306) { onIrc306(ev); return 1; } if(ev->eventType == IRC_331 || ev->eventType == IRC_332 || ev->eventType == IRC_333) { onIrc331332333(ev); return 1; } if(ev->eventType == IRC_353) { onIrc353(ev); return 1; } if(ev->eventType == IRC_366) { onIrc366(ev); return 1; } if(ev->eventType == IRC_372) { onIrc372(ev); return 1; } if(ev->eventType == IRC_AWAY) { onIrcAway(ev); return 1; } if(ev->eventType == IRC_ENDMOTD) { onIrcEndMotd(); return 1; } return 1; } //handle IrcEvent IRC_PRIVMSG void IrcTabItem::onIrcPrivmsg(IrcEvent* ev) { if((comparecase(ev->param2, getText()) == 0 && m_type == CHANNEL) || (ev->param1 == getText() && m_type == QUERY && ev->param2 == getNickName())) { FXbool needHighlight = FALSE; if(ev->param3.contains(getNickName())) needHighlight = highlightNeeded(ev->param3); if(m_coloredNick) { if(needHighlight) appendIrcStyledText(ev->param1+": "+ev->param3, 8, ev->time); else appendIrcNickText(ev->param1, ev->param3, getNickColor(ev->param1), ev->time); } else { if(needHighlight) appendIrcStyledText(ev->param1+": "+ev->param3, 8, ev->time); else appendIrcNickText(ev->param1, ev->param3, 5, ev->time); } if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) { if(needHighlight) { this->setTextColor(m_highlightColor); if(m_type == CHANNEL) this->setIcon(ICO_CHANNELNEWMSG); } else this->setTextColor(m_unreadColor); if(m_type == QUERY) this->setIcon(ICO_QUERYNEWMSG); } if((m_type == CHANNEL && needHighlight) || m_type == QUERY) m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_NEWMSG), NULL); } } //handle IrcEvent IRC_ACTION void IrcTabItem::onIrcAction(IrcEvent* ev) { if((comparecase(ev->param2, getText()) == 0 && m_type == CHANNEL) || (ev->param1 == getText() && m_type == QUERY && ev->param2 == getNickName())) { if(!isCommandIgnored("me")) { FXbool needHighlight = FALSE; if(ev->param3.contains(getNickName())) needHighlight = highlightNeeded(ev->param3); appendIrcStyledText(ev->param1+" "+ev->param3, 2, ev->time); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) { if(needHighlight) { this->setTextColor(m_highlightColor); if(m_type == CHANNEL) this->setIcon(ICO_CHANNELNEWMSG); } else this->setTextColor(m_unreadColor); if(m_type == QUERY) this->setIcon(ICO_QUERYNEWMSG); } if((m_type == CHANNEL && needHighlight) || m_type == QUERY) m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_NEWMSG), NULL); } } } //handle IrcEvent IRC_CTCPREPLY void IrcTabItem::onIrcCtpcReply(IrcEvent* ev) { if(isRightForServerMsg()) { if(!isCommandIgnored("ctcp")) { appendIrcStyledText(FXStringFormat(_("CTCP %s reply from %s: %s"), utils::instance().getParam(ev->param2, 1, FALSE).text(), ev->param1.text(), utils::instance().getParam(ev->param2, 2, TRUE).text()), 2, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } } //handle IrcEvent IRC_CTCPREQUEST void IrcTabItem::onIrcCtcpRequest(IrcEvent* ev) { if(isRightForServerMsg()) { if(!isCommandIgnored("ctcp")) { appendIrcStyledText(FXStringFormat(_("CTCP %s request from %s"), ev->param2.text(), ev->param1.text()), 2, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } } //handle IrcEvent IRC_JOIN void IrcTabItem::onIrcJoin(IrcEvent* ev) { if(comparecase(ev->param2, getText()) == 0 && ev->param1 != getNickName()) { if(!isCommandIgnored("join") && !m_engine->isUserIgnored(ev->param1, getText())) appendIrcStyledText(FXStringFormat(_("%s has joined to %s"), ev->param1.text(), ev->param2.text()), 1, ev->time); addUser(ev->param1, NONE); } } //handle IrcEvent IRC_QUIT void IrcTabItem::onIrcQuit(IrcEvent* ev) { if(m_type == CHANNEL && m_users->findItem(ev->param1) != -1) { removeUser(ev->param1); if(ev->param2.empty()) { if(!isCommandIgnored("quit") && !m_engine->isUserIgnored(ev->param1, getText())) appendIrcStyledText(FXStringFormat(_("%s has quit"), ev->param1.text()), 1, ev->time); } else { if(!isCommandIgnored("quit") && !m_engine->isUserIgnored(ev->param1, getText()))appendIrcStyledText(FXStringFormat(_("%s has quit (%s)"), ev->param1.text(), +ev->param2.text()), 1, ev->time); } } else if(m_type == QUERY && getText() == ev->param1) { appendIrcStyledText(FXStringFormat(_("%s has quit"), ev->param1.text()), 1, ev->time, FALSE, FALSE); } } //handle IrcEvent IRC_PART void IrcTabItem::onIrcPart(IrcEvent* ev) { if(comparecase(ev->param2, getText()) == 0) { if(ev->param3.empty() && !isCommandIgnored("part") && !m_engine->isUserIgnored(ev->param1, getText())) appendIrcStyledText(FXStringFormat(_("%s has parted %s"), ev->param1.text(), ev->param2.text()), 1, ev->time); else if(!isCommandIgnored("part") && !m_engine->isUserIgnored(ev->param1, getText())) appendIrcStyledText(FXStringFormat(_("%s has parted %s (%s)"), ev->param1.text(), ev->param2.text(), ev->param3.text()), 1, ev->time); removeUser(ev->param1); } } //handle IrcEvent IRC_CHNOTICE void IrcTabItem::onIrcChnotice(IrcEvent* ev) { if(!isCommandIgnored("notice")) { FXbool tabExist = FALSE; for(FXint i = 0; i<m_parent->numChildren(); i+=2) { if(m_parent->childAtIndex(i)->getMetaClass()==&IrcTabItem::metaClass && m_engine->findTarget(static_cast<IrcTabItem*>(m_parent->childAtIndex(i)))) { if((comparecase(ev->param2, static_cast<IrcTabItem*>(m_parent->childAtIndex(i))->getText()) == 0 && static_cast<IrcTabItem*>(m_parent->childAtIndex(i))->getType() == CHANNEL) || (ev->param1 == static_cast<IrcTabItem*>(m_parent->childAtIndex(i))->getText() && static_cast<IrcTabItem*>(m_parent->childAtIndex(i))->getType() == QUERY && ev->param2 == static_cast<IrcTabItem*>(m_parent->childAtIndex(i))->getNickName())) { tabExist = TRUE; break; } } } if(tabExist) { if((comparecase(ev->param2, getText()) == 0 && m_type == CHANNEL) || (ev->param1 == getText() && m_type == QUERY && ev->param2 == getNickName())) { FXbool needHighlight = FALSE; if(ev->param3.contains(getNickName())) needHighlight = highlightNeeded(ev->param3); appendIrcStyledText(FXStringFormat(_("%s's NOTICE: %s"), ev->param1.text(), ev->param3.text()), 2, ev->time); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) { if(needHighlight) { this->setTextColor(m_highlightColor); if(m_type == CHANNEL) this->setIcon(ICO_CHANNELNEWMSG); } else this->setTextColor(m_unreadColor); if(m_type == QUERY) this->setIcon(ICO_QUERYNEWMSG); } if((m_type == CHANNEL && needHighlight) || m_type == QUERY) m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_NEWMSG), NULL); } } else { if(isRightForServerMsg()) { appendIrcStyledText(FXStringFormat(_("%s's NOTICE: %s"), ev->param1.text(), ev->param3.text()), 3, ev->time); } } } } //handle IrcEvent IRC_NOTICE void IrcTabItem::onIrcNotice(IrcEvent* ev) { if(isRightForServerMsg()) { if(ev->param1 == getNickName() && !isCommandIgnored("notice")) { appendIrcStyledText(FXStringFormat(_("NOTICE for you: %s"), ev->param2.text()), 3, ev->time); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } else if(!isCommandIgnored("notice")) { appendIrcStyledText(FXStringFormat(_("%s's NOTICE: %s"), ev->param1.text(), ev->param2.text()), 3, ev->time); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } } //handle IrcEvent IRC_NICK void IrcTabItem::onIrcNick(IrcEvent* ev) { if(m_users->findItem(ev->param1) != -1) { if(ev->param2 == getNickName() && !isCommandIgnored("nick")) appendIrcStyledText(FXStringFormat(_("You're now known as %s"), ev->param2.text()), 1, ev->time); else if(!isCommandIgnored("nick") && !m_engine->isUserIgnored(ev->param1, getText())) appendIrcStyledText(FXStringFormat(_("%s is now known as %s"), ev->param1.text(), ev->param2.text()), 1, ev->time); changeNickUser(ev->param1, ev->param2); } if(m_type == QUERY && ev->param1 == getText()) { this->setText(ev->param2); stopLogging(); } } //handle IrcEvent IRC_TOPIC void IrcTabItem::onIrcTopic(IrcEvent* ev) { if(comparecase(ev->param2, getText()) == 0) { appendIrcText(FXStringFormat(_("%s set new topic for %s: %s"), ev->param1.text(), ev->param2.text(), ev->param3.text()), ev->time); m_topic = stripColors(ev->param3, TRUE); m_topicline->setText(m_topic); m_topicline->setCursorPos(0); m_topicline->makePositionVisible(0); } } //handle IrcEvent IRC_INVITE void IrcTabItem::onIrcInvite(IrcEvent* ev) { if(isRightForServerMsg()) { appendIrcStyledText(FXStringFormat(_("%s invites you to: %s"), ev->param1.text(), ev->param3.text()), 3, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } //handle IrcEvent IRC_KICK void IrcTabItem::onIrcKick(IrcEvent* ev) { if(comparecase(ev->param3, getText()) == 0) { if(ev->param2 != getNickName()) { if(ev->param4.empty()) appendIrcStyledText(FXStringFormat(_("%s was kicked from %s by %s"), ev->param2.text(), ev->param3.text(), ev->param1.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s was kicked from %s by %s (%s)"), ev->param2.text(), ev->param3.text(), ev->param1.text(), ev->param4.text()), 1, ev->time, FALSE, FALSE); removeUser(ev->param2); } } if(ev->param2 == getNickName() && isRightForServerMsg()) { if(ev->param4.empty()) appendIrcStyledText(FXStringFormat(_("You were kicked from %s by %s"), ev->param3.text(), ev->param1.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("You were kicked from %s by %s (%s)"), ev->param3.text(), ev->param1.text(), ev->param4.text()), 1, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } //handle IrcEvent IRC_MODE void IrcTabItem::onIrcMode(IrcEvent* ev) { if(isRightForServerMsg()) { appendIrcStyledText(FXStringFormat(_("Mode change [%s] for %s"), ev->param1.text(), ev->param2.text()), 1, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } //handle IrcEvent IRC_UMODE void IrcTabItem::onIrcUmode(IrcEvent* ev) { FXString moderator = ev->param1; FXString channel = ev->param2; FXString modes = ev->param3; FXString args = ev->param4; if(comparecase(channel, getText()) == 0) { FXbool sign = FALSE; int argsiter = 1; for(int i =0; i < modes.count(); i++) { switch(modes[i]) { case '+': sign = TRUE; break; case '-': sign = FALSE; break; case 'a': //admin { FXString nick = utils::instance().getParam(args, argsiter, FALSE); setUserMode(nick, sign?ADMIN:NONE); if(sign) { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s gave you admin"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s gave %s admin"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } else { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s removed you admin"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s removed %s admin"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } argsiter++; }break; case 'o': //op { FXString nick = utils::instance().getParam(args, argsiter, FALSE); setUserMode(nick, sign?OP:NONE); if(sign) { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s gave you op"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s gave %s op"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } else { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s removed you op"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s removed %s op"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } if(getNickName() == nick) sign ? m_iamOp = TRUE : m_iamOp = FALSE; argsiter++; }break; case 'v': //voice { FXString nick = utils::instance().getParam(args, argsiter, FALSE); setUserMode(nick, sign?VOICE:NONE); if(sign) { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s gave you voice"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s gave %s voice"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } else { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s removed you voice"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s removed %s voice"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } argsiter++; }break; case 'h': //halfop { FXString nick = utils::instance().getParam(args, argsiter, FALSE); setUserMode(nick, sign?HALFOP:NONE); if(sign) { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s gave you halfop"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s gave %s halfop"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } else { if(!isCommandIgnored("mode") && !m_engine->isUserIgnored(nick, getText())) { if(nick == getNickName()) appendIrcStyledText(FXStringFormat(_("%s removed you halfop"), moderator.text()), 1, ev->time, FALSE, FALSE); else appendIrcStyledText(FXStringFormat(_("%s removed %s halfop"), moderator.text(), nick.text()), 1, ev->time, FALSE, FALSE); } } argsiter++; }break; case 'b': //ban { FXString banmask = utils::instance().getParam(args, argsiter, FALSE); onBan(banmask, sign, moderator, ev->time); argsiter++; }break; case 't': //topic settable by channel operator { sign ? m_editableTopic = FALSE : m_editableTopic = TRUE; } default: { appendIrcStyledText(FXStringFormat(_("%s set Mode: %s"), moderator.text(), FXString(modes+" "+args).text()), 1, ev->time, FALSE, FALSE); } } } } } //handle IrcEvent IRC_CHMODE void IrcTabItem::onIrcChmode(IrcEvent* ev) { FXString channel = ev->param1; FXString modes = ev->param2; if(comparecase(channel, getText()) == 0) { if(modes.contains('t')) m_editableTopic = FALSE; appendIrcStyledText(FXStringFormat(_("Mode for %s: %s"), channel.text(), modes.text()), 1, ev->time, FALSE, FALSE); } } //handle IrcEvent IRC_SERVERREPLY void IrcTabItem::onIrcServerReply(IrcEvent* ev) { if(m_ownServerWindow) { if(m_type == SERVER) { //this->setText(server->GetRealServerName()); appendIrcText(ev->param1, ev->time); if(getApp()->getForeColor() == this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } else { if(isRightForServerMsg()) { appendIrcText(ev->param1, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } } //handle IrcEvent IRC_CONNECT void IrcTabItem::onIrcConnect(IrcEvent* ev) { appendIrcStyledText(ev->param1, 3, ev->time, FALSE, FALSE); } //handle IrcEvent IRC_ERROR void IrcTabItem::onIrcError(IrcEvent* ev) { appendIrcStyledText(ev->param1, 4, ev->time, FALSE, FALSE); } //handle IrcEvent IRC_SERVERERROR void IrcTabItem::onIrcServerError(IrcEvent* ev) { if(isRightForServerMsg()) { appendIrcStyledText(ev->param1, 4, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } //handle IrcEvent IRC_DISCONNECT void IrcTabItem::onIrcDisconnect(IrcEvent* ev) { appendIrcStyledText(ev->param1, 4, ev->time, FALSE, FALSE); if(isRightForServerMsg()) { if(m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_highlightColor); } if(m_type == CHANNEL) { m_users->clearItems(); m_iamOp = FALSE; } } //handle IrcEvent IRC_RECONNECT void IrcTabItem::onIrcReconnect(IrcEvent* ev) { appendIrcStyledText(ev->param1, 4, ev->time, FALSE, FALSE); if(isRightForServerMsg()) { if(m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_highlightColor); } if(m_type == CHANNEL) { m_users->clearItems(); m_iamOp = FALSE; } } //handle IrcEvent IRC_UNKNOWN void IrcTabItem::onIrcUnknown(IrcEvent* ev) { if(isRightForServerMsg()) { appendIrcStyledText(FXStringFormat(_("Unhandled command '%s' params: %s"), ev->param1.text(), ev->param2.text()), 4, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } //handle IrcEvent IRC_301 void IrcTabItem::onIrc301(IrcEvent* ev) { if(m_parent->getCurrent()*2 == m_parent->indexOfChild(this) || getText() == ev->param1) { if(!isCommandIgnored("away") && !m_engine->isUserIgnored(ev->param1, getText())) appendIrcStyledText(FXStringFormat(_("%s is away: %s"),ev->param1.text(), ev->param2.text()), 1, ev->time); } } //handle IrcEvent IRC_305 void IrcTabItem::onIrc305(IrcEvent* ev) { FXint i = m_users->findItem(getNickName()); if(i != -1) { appendIrcStyledText(ev->param1, 1, ev->time, FALSE, FALSE); ((NickListItem*)m_users->getItem(i))->changeAway(FALSE); } } //handle IrcEvent IRC_306 void IrcTabItem::onIrc306(IrcEvent* ev) { FXint i = m_users->findItem(getNickName()); if(i != -1) { appendIrcStyledText(ev->param1, 1, ev->time, FALSE, FALSE); ((NickListItem*)m_users->getItem(i))->changeAway(TRUE); } } //handle IrcEvent IRC_331, IRC_332 and IRC_333 void IrcTabItem::onIrc331332333(IrcEvent* ev) { if(comparecase(ev->param1, getText()) == 0) { appendIrcText(ev->param2, ev->time); if(ev->eventType == IRC_331) { m_topic = stripColors(ev->param2, TRUE); m_topicline->setText(m_topic); m_topicline->setCursorPos(0); m_topicline->makePositionVisible(0); } if(ev->eventType == IRC_332) { m_topic = stripColors(utils::instance().getParam(ev->param2, 2, TRUE, ':').after(' '), TRUE); m_topicline->setText(m_topic); m_topicline->setCursorPos(0); m_topicline->makePositionVisible(0); } } } //handle IrcEvent IRC_353 void IrcTabItem::onIrc353(IrcEvent* ev) { FXString channel = ev->param1; FXString usersStr = ev->param2; FXString myNick = getNickName(); if(usersStr.right(1) != " ") usersStr.append(" "); if(comparecase(channel, getText()) == 0) { while (usersStr.contains(' ')) { FXString nick = usersStr.before(' '); UserMode mode = getUserMode(nick[0]); if(mode != NONE) nick = nick.after(nick[0]); addUser(nick, mode); if(mode == OP && nick == myNick) m_iamOp = TRUE; usersStr = usersStr.after(' '); } } else { FXbool channelOn = FALSE; for(FXint i = 0; i<m_parent->numChildren(); i+=2) { if(m_engine->findTarget(static_cast<IrcTabItem*>(m_parent->childAtIndex(i))) && comparecase(static_cast<FXTabItem*>(m_parent->childAtIndex(i))->getText(), channel) == 0) { channelOn = TRUE; break; } } if(!channelOn && !isCommandIgnored("numeric")) appendIrcText(FXStringFormat(_("Users on %s: %s"), channel.text(), usersStr.text()), ev->time, FALSE, FALSE); } } //handle IrcEvent IRC_366 void IrcTabItem::onIrc366(IrcEvent* ev) { if(comparecase(ev->param1, getText()) == 0) { m_engine->addIgnoreWho(getText()); } } //handle IrcEvent IRC_372 void IrcTabItem::onIrc372(IrcEvent* ev) { if(m_ownServerWindow) { if(m_type == SERVER) { appendIrcText(ev->param1, ev->time); if(getApp()->getForeColor() == this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } else { if(isRightForServerMsg()) { appendIrcText(ev->param1, ev->time, FALSE, FALSE); if(m_highlightColor != this->getTextColor() && m_parent->getCurrent()*2 != m_parent->indexOfChild(this)) this->setTextColor(m_unreadColor); } } } //handle IrcEvent IRC_AWAY void IrcTabItem::onIrcAway(IrcEvent* ev) { if(comparecase(ev->param1, getText()) == 0) { onAway(); } } //handle IrcEvent IRC_ENDMOTD void IrcTabItem::onIrcEndMotd() { m_text->makeLastRowVisible(TRUE); if(m_type == SERVER && !m_engine->getNetworkName().empty()) setText(m_engine->getNetworkName()); } long IrcTabItem::onPipe(FXObject*, FXSelector, void *ptr) { FXString text = *(FXString*)ptr; if(m_sendPipe && (m_type == CHANNEL || m_type == QUERY)) { if(!getApp()->hasTimeout(this, IrcTabItem_PTIME)) getApp()->addTimeout(this, IrcTabItem_PTIME); m_pipeStrings.append(text); } else appendIrcText(text, FXSystem::now()); return 1; } //checking away in channel void IrcTabItem::checkAway() { if(m_type == CHANNEL && m_engine->getConnected() && m_numberUsers < m_maxAway) { m_engine->addIgnoreWho(getText()); } } long IrcTabItem::onPipeTimeout(FXObject*, FXSelector, void*) { if(m_type == CHANNEL || m_type == QUERY) { if(m_pipeStrings.no() > 3) { if(m_pipeStrings[0].empty()) m_pipeStrings[0] = " "; if(m_pipeStrings[0].length() > m_maxLen-10-getText().length()) { dxStringArray messages = cutText(m_pipeStrings[0], m_maxLen-10-getText().length()); for(FXint i=0; i<messages.no(); i++) { if(m_coloredNick) appendIrcNickText(getNickName(), messages[i], getNickColor(getNickName()), FXSystem::now()); else appendIrcNickText(getNickName(), messages[i], 5, FXSystem::now()); m_engine->sendMsg(getText(), messages[i]); } } else { if(m_coloredNick) appendIrcNickText(getNickName(), m_pipeStrings[0], getNickColor(getNickName()), FXSystem::now()); else appendIrcNickText(getNickName(), m_pipeStrings[0], 5, FXSystem::now()); m_engine->sendMsg(getText(), m_pipeStrings[0]); } m_pipeStrings.erase(0); getApp()->addTimeout(this, IrcTabItem_PTIME, 3000); } else { while(m_pipeStrings.no()) { if(m_pipeStrings[0].empty()) m_pipeStrings[0] = " "; if(m_pipeStrings[0].length() > m_maxLen-10-getText().length()) { dxStringArray messages = cutText(m_pipeStrings[0], m_maxLen-10-getText().length()); for(FXint i=0; i<messages.no(); i++) { if(m_coloredNick) appendIrcNickText(getNickName(), messages[i], getNickColor(getNickName()), FXSystem::now()); else appendIrcNickText(getNickName(), messages[i], 5, FXSystem::now()); m_engine->sendMsg(getText(), messages[i]); } } else { if(m_coloredNick) appendIrcNickText(getNickName(), m_pipeStrings[0], getNickColor(getNickName()), FXSystem::now()); else appendIrcNickText(getNickName(), m_pipeStrings[0], 5, FXSystem::now()); m_engine->sendMsg(getText(), m_pipeStrings[0]); } m_pipeStrings.erase(0); } } } return 1; } long IrcTabItem::onEggTimeout(FXObject*, FXSelector, void*) { if(m_pics<24) { getApp()->addTimeout(this, IrcTabItem_ETIME, 222); FXString replace = "\n"; FXint max = rand()%30; for(FXint i=0; i<max; i++) replace.append(' '); FXString pic = "\n ©©©©©©\n © ©\n © ©\n © ©\n©©©©©©©©©©©©©©\n©©©©©©©©©©©©©©\n©©©©©©©©©©©©©©\n © ©\n © ©\n © ©\n ©©©©©©"; pic.substitute("\n", replace); pic.append('\n'); m_text->clearText(); max = rand()%15; for(FXint i=0; i<max; i++) pic.prepend('\n'); max = rand()%7; m_text->appendStyledText(pic, max+10); m_pics++; } return 1; } void IrcTabItem::onAway() { if(m_numberUsers < m_maxAway) { for(FXint i = 0; i < m_users->getNumItems(); i++) { FXbool away = m_engine->getNickInfo(m_users->getItemText(i)).away; ((NickListItem*)m_users->getItem(i))->changeAway(away); } } else { for(FXint i = 0; i < m_users->getNumItems(); i++) { ((NickListItem*)m_users->getItem(i))->changeAway(FALSE); } } } long IrcTabItem::onTextLink(FXObject *, FXSelector, void *data) { utils::instance().launchLink(static_cast<FXchar*>(data)); return 1; } long IrcTabItem::onRightMouse(FXObject *, FXSelector, void *ptr) { //focus(); FXEvent* event = (FXEvent*)ptr; if(event->moved) return 1; FXint index = m_users->getItemAt(event->win_x,event->win_y); if(index >= 0) { NickInfo nick = m_engine->getNickInfo(m_users->getItemText(index)); m_nickOnRight = nick; FXString flagpath = DXIRC_DATADIR PATHSEPSTRING "icons" PATHSEPSTRING "flags"; delete ICO_FLAG; ICO_FLAG = NULL; if(FXStat::exists(flagpath+PATHSEPSTRING+nick.host.rafter('.')+".png")) ICO_FLAG = makeIcon(getApp(), flagpath, nick.host.rafter('.')+".png", TRUE); else ICO_FLAG = makeIcon(getApp(), flagpath, "unknown.png", TRUE); FXMenuPane opmenu(this); new FXMenuCommand(&opmenu, _("Give op"), NULL, this, IrcTabItem_OP); new FXMenuCommand(&opmenu, _("Remove op"), NULL, this, IrcTabItem_DEOP); new FXMenuSeparator(&opmenu); new FXMenuCommand(&opmenu, _("Give voice"), NULL, this, IrcTabItem_VOICE); new FXMenuCommand(&opmenu, _("Remove voice"), NULL, this, IrcTabItem_DEVOICE); new FXMenuSeparator(&opmenu); new FXMenuCommand(&opmenu, _("Kick"), NULL, this, IrcTabItem_KICK); new FXMenuSeparator(&opmenu); new FXMenuCommand(&opmenu, _("Ban"), NULL, this, IrcTabItem_BAN); new FXMenuCommand(&opmenu, _("KickBan"), NULL, this, IrcTabItem_KICKBAN); FXMenuPane popup(this); new FXMenuCommand(&popup, FXStringFormat(_("User: %s@%s"), nick.user.text(), nick.host.text()), ICO_FLAG); new FXMenuCommand(&popup, FXStringFormat(_("Realname: %s"), nick.real.text())); if(nick.nick != getNickName()) { new FXMenuSeparator(&popup); new FXMenuCommand(&popup, _("Query"), NULL, this, IrcTabItem_NEWQUERY); new FXMenuCommand(&popup, _("User information (WHOIS)"), NULL, this, IrcTabItem_WHOIS); new FXMenuCommand(&popup, _("DCC chat"), NULL, this, IrcTabItem_DCCCHAT); new FXMenuCommand(&popup, _("Send file"), NULL, this, IrcTabItem_DCCSEND); new FXMenuCommand(&popup, _("Ignore"), NULL, this, IrcTabItem_IGNORE); if(m_iamOp) new FXMenuCascade(&popup, _("Operator actions"), NULL, &opmenu); } else { new FXMenuSeparator(&popup); if(m_engine->isAway(getNickName())) new FXMenuCommand(&popup, _("Remove Away"), NULL, this, IrcTabItem_DEAWAY); else new FXMenuCommand(&popup, _("Set Away"), NULL, this, IrcTabItem_AWAY); } popup.create(); popup.popup(NULL,event->root_x,event->root_y); getApp()->runModalWhileShown(&popup); } return 1; } long IrcTabItem::onDoubleclick(FXObject*, FXSelector, void*) { FXint index = m_users->getCursorItem(); if(index >= 0) { if(m_users->getItemText(index) == getNickName()) return 1; IrcEvent ev; ev.eventType = IRC_QUERY; ev.param1 = m_users->getItemText(index); ev.param2 = getNickName(); m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); } return 1; } long IrcTabItem::onNewQuery(FXObject *, FXSelector, void *) { IrcEvent ev; ev.eventType = IRC_QUERY; ev.param1 = m_nickOnRight.nick; ev.param2 = getNickName(); m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); return 1; } long IrcTabItem::onWhois(FXObject *, FXSelector, void *) { m_engine->sendWhois(m_nickOnRight.nick); return 1; } long IrcTabItem::onDccChat(FXObject*, FXSelector, void*) { IrcEvent ev; ev.eventType = IRC_DCCSERVER; ev.param1 = m_nickOnRight.nick; m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); return 1; } long IrcTabItem::onDccSend(FXObject*, FXSelector, void*) { DccSendDialog dialog((FXMainWindow*)m_parent->getParent()->getParent(), m_nickOnRight.nick); if(dialog.execute()) { IrcEvent ev; ev.eventType = dialog.getPassive() ? IRC_DCCPOUT: IRC_DCCOUT; ev.param1 = m_nickOnRight.nick; ev.param2 = dialog.getFilename(); m_parent->getParent()->getParent()->handle(m_engine, FXSEL(SEL_COMMAND, IrcEngine_SERVER), &ev); } return 1; } long IrcTabItem::onOp(FXObject *, FXSelector, void *) { m_engine->sendMode(getText()+" +o "+m_nickOnRight.nick); return 1; } long IrcTabItem::onDeop(FXObject *, FXSelector, void *) { m_engine->sendMode(getText()+" -o "+m_nickOnRight.nick); return 1; } long IrcTabItem::onVoice(FXObject *, FXSelector, void *) { m_engine->sendMode(getText()+" +v "+m_nickOnRight.nick); return 1; } long IrcTabItem::onDevoice(FXObject *, FXSelector, void *) { m_engine->sendMode(getText()+" -v "+m_nickOnRight.nick); return 1; } long IrcTabItem::onKick(FXObject *, FXSelector, void *) { FXDialogBox kickDialog(this, _("Kick dialog"), DECOR_TITLE|DECOR_BORDER, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); FXVerticalFrame *contents = new FXVerticalFrame(&kickDialog, LAYOUT_SIDE_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y, 0, 0, 0, 0, 10, 10, 10, 10, 0, 0); FXHorizontalFrame *kickframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y); new FXLabel(kickframe, _("Kick reason:"), 0, JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXTextField *reasonEdit = new FXTextField(kickframe, 25, NULL, 0, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); FXHorizontalFrame *buttonframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y|PACK_UNIFORM_WIDTH); new dxEXButton(buttonframe, _("&Cancel"), NULL, &kickDialog, FXDialogBox::ID_CANCEL, FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); new dxEXButton(buttonframe, _("&OK"), NULL, &kickDialog, FXDialogBox::ID_ACCEPT, BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); if(kickDialog.execute(PLACEMENT_CURSOR)) { m_engine->sendKick(getText(), m_nickOnRight.nick, reasonEdit->getText()); } return 1; } long IrcTabItem::onBan(FXObject *, FXSelector, void *) { FXDialogBox banDialog(this, _("Ban dialog"), DECOR_TITLE|DECOR_BORDER, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); FXVerticalFrame *contents = new FXVerticalFrame(&banDialog, LAYOUT_SIDE_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y, 0, 0, 0, 0, 10, 10, 10, 10, 0, 0); FXHorizontalFrame *banframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y); new FXLabel(banframe, _("Banmask:"), 0, JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXTextField *banEdit = new FXTextField(banframe, 25, NULL, 0, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); banEdit->setText(m_nickOnRight.nick+"!"+m_nickOnRight.user+"@"+m_nickOnRight.host); FXHorizontalFrame *buttonframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y|PACK_UNIFORM_WIDTH); new dxEXButton(buttonframe, _("&Cancel"), NULL, &banDialog, FXDialogBox::ID_CANCEL, FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); new dxEXButton(buttonframe, _("&OK"), NULL, &banDialog, FXDialogBox::ID_ACCEPT, BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); if(banDialog.execute(PLACEMENT_CURSOR)) { m_engine->sendMode(getText()+" +b "+banEdit->getText()); } return 1; } long IrcTabItem::onKickban(FXObject *, FXSelector, void *) { FXDialogBox banDialog(this, _("Kick/Ban dialog"), DECOR_TITLE|DECOR_BORDER, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); FXVerticalFrame *contents = new FXVerticalFrame(&banDialog, LAYOUT_SIDE_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y, 0, 0, 0, 0, 10, 10, 10, 10, 0, 0); FXHorizontalFrame *kickframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y); new FXLabel(kickframe, _("Kick reason:"), 0, JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXTextField *reasonEdit = new FXTextField(kickframe, 25, NULL, 0, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); FXHorizontalFrame *banframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y); new FXLabel(banframe, _("Banmask:"), 0, JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXTextField *banEdit = new FXTextField(banframe, 25, NULL, 0, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); banEdit->setText(m_nickOnRight.nick+"!"+m_nickOnRight.user+"@"+m_nickOnRight.host); FXHorizontalFrame *buttonframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y|PACK_UNIFORM_WIDTH); new dxEXButton(buttonframe, _("&Cancel"), NULL, &banDialog, FXDialogBox::ID_CANCEL, FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); new dxEXButton(buttonframe, _("&OK"), NULL, &banDialog, FXDialogBox::ID_ACCEPT, BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); if(banDialog.execute(PLACEMENT_CURSOR)) { m_engine->sendKick(getText(), m_nickOnRight.nick, reasonEdit->getText()); m_engine->sendMode(getText()+" +b "+banEdit->getText()); } return 1; } //handle popup Ignore long IrcTabItem::onIgnore(FXObject*, FXSelector, void*) { FXDialogBox dialog(this, _("Add ignore user"), DECOR_TITLE|DECOR_BORDER, 0,0,0,0, 0,0,0,0, 0,0); FXVerticalFrame *contents = new FXVerticalFrame(&dialog, LAYOUT_SIDE_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y, 0,0,0,0, 10,10,10,10, 0,0); FXMatrix *matrix = new FXMatrix(contents,2,MATRIX_BY_COLUMNS|LAYOUT_SIDE_TOP|LAYOUT_FILL_X|LAYOUT_FILL_Y); new FXLabel(matrix, _("Nick:"), NULL, JUSTIFY_LEFT|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); FXTextField *nick = new FXTextField(matrix, 25, NULL, 0, FRAME_THICK|FRAME_SUNKEN|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); nick->setText(m_nickOnRight.nick+"!"+m_nickOnRight.user+"@"+m_nickOnRight.host); new FXLabel(matrix, _("Channel(s):\tChannels need to be comma separated"), NULL,JUSTIFY_LEFT|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); FXTextField *channel = new FXTextField(matrix, 25, NULL, 0, FRAME_THICK|FRAME_SUNKEN|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); channel->setText(getText()); channel->setTipText(_("Channels need to be comma separated")); new FXLabel(matrix, _("Server:"), NULL,JUSTIFY_LEFT|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); FXTextField *server = new FXTextField(matrix, 25, NULL, 0, FRAME_THICK|FRAME_SUNKEN|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); server->setText(getServerName()); FXHorizontalFrame *buttonframe = new FXHorizontalFrame(contents,LAYOUT_FILL_X|LAYOUT_FILL_Y|PACK_UNIFORM_WIDTH); new dxEXButton(buttonframe, _("&Cancel"), NULL, &dialog, FXDialogBox::ID_CANCEL, FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0,0,0,0, 10,10,2,2); new dxEXButton(buttonframe, _("&OK"), NULL, &dialog, FXDialogBox::ID_ACCEPT, BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0,0,0,0, 10,10,2,2); if(dialog.execute(PLACEMENT_CURSOR)) { FXString ignoretext = nick->getText()+" "+channel->getText()+" "+server->getText(); m_parent->getParent()->getParent()->handle(this, FXSEL(SEL_COMMAND, IrcTabItem_ADDIUSER), &ignoretext); } return 1; } //handle IrcTabItem_AWAY long IrcTabItem::onSetAway(FXObject*, FXSelector, void*) { FXDialogBox awayDialog(this, _("Away dialog"), DECOR_TITLE|DECOR_BORDER, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); FXVerticalFrame *contents = new FXVerticalFrame(&awayDialog, LAYOUT_SIDE_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y, 0, 0, 0, 0, 10, 10, 10, 10, 0, 0); FXHorizontalFrame *msgframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y); new FXLabel(msgframe, _("Message:"), 0, JUSTIFY_LEFT|LAYOUT_FILL_X|LAYOUT_FILL_Y); FXTextField *msgEdit = new FXTextField(msgframe, 25, NULL, 0, FRAME_SUNKEN|FRAME_THICK|LAYOUT_FILL_COLUMN|LAYOUT_FILL_ROW); msgEdit->setText(_("away")); FXHorizontalFrame *buttonframe = new FXHorizontalFrame(contents, LAYOUT_FILL_X|LAYOUT_FILL_Y|PACK_UNIFORM_WIDTH); new dxEXButton(buttonframe, _("&Cancel"), NULL, &awayDialog, FXDialogBox::ID_CANCEL, FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); new dxEXButton(buttonframe, _("&OK"), NULL, &awayDialog, FXDialogBox::ID_ACCEPT, BUTTON_INITIAL|BUTTON_DEFAULT|FRAME_RAISED|FRAME_THICK|LAYOUT_RIGHT, 0, 0, 0, 0, 10, 10, 2, 2); if(awayDialog.execute(PLACEMENT_CURSOR)) { m_engine->sendAway(msgEdit->getText().empty() ? _("away"): msgEdit->getText()); } return 1; } //handle IrcTabItem_DEAWAY long IrcTabItem::onRemoveAway(FXObject*, FXSelector, void*) { m_engine->sendAway(""); return 1; } //handle change in spellLang combobox long IrcTabItem::onSpellLang(FXObject*, FXSelector, void*) { m_commandline->setLanguage(m_spellLangs->getItemText(m_spellLangs->getCurrentItem())); m_commandline->setTipText(FXStringFormat(_("Current spellchecking language: %s"),m_spellLangs->getItemText(m_spellLangs->getCurrentItem()).text())); return 1; } long IrcTabItem::onTopic(FXObject*, FXSelector, void*) { if(m_editableTopic || m_iamOp) { if(m_topicline->getText().length() > m_engine->getTopicLen()) { appendIrcStyledText(FXStringFormat(_("Warning: topic is too long. Max. topic length is %d."), m_engine->getTopicLen()), 4, FXSystem::now(), FALSE, FALSE); m_engine->sendTopic(getText(), m_topicline->getText()); return 1; } m_engine->sendTopic(getText(), m_topicline->getText()); } else { m_topicline->setText(m_topic); m_topicline->setCursorPos(0); m_topicline->makePositionVisible(0); } return 1; } long IrcTabItem::onTopicLink(FXObject*, FXSelector, void *data) { utils::instance().launchLink(static_cast<FXchar*>(data)); return 1; } void IrcTabItem::onBan(const FXString &banmask, const FXbool &sign, const FXString &sender, const FXTime &time) { if(sign) { FXString nicks = m_engine->getBannedNick(banmask); FXString myNick = getNickName(); while(nicks.contains(';')) { for(FXint i=m_users->getNumItems()-1; i>-1; i--) { if(nicks.before(';') == m_users->getItemText(i)) { if(m_users->getItemText(i) == myNick) appendIrcStyledText(FXStringFormat(_("You was banned by %s"), sender.text()), 1, time, FALSE, FALSE); else { if(!isCommandIgnored("ban") && !m_engine->isUserIgnored(m_users->getItemText(i), getText())) appendIrcStyledText(FXStringFormat(_("%s was banned by %s"), m_users->getItemText(i).text(), sender.text()), 1, time, FALSE, FALSE); //RemoveUser(users->getItemText(i)); } } } nicks = nicks.after(';'); } } } FXString IrcTabItem::stripColors(const FXString &text, const FXbool stripOther) { FXString newstr; FXbool color = FALSE; FXint numbers = 0; FXint i = 0; while(text[i] != '\0') { if(text[i] == '\017') //reset { color = FALSE; } else if(stripOther && text[i] == '\002') { //remove bold mark } else if(stripOther && text[i] == '\037') { //remove underline mark } else if(text[i] == '\035') { //remove italic mark } else if(text[i] == '\021') { //remove fixed mark } else if(text[i] == '\026') { //remove reverse mark } else if(text[i] == '\003') //color { color = TRUE; } else if(color && isdigit(text[i]) && numbers < 2) { numbers++; } else if(color && text[i] == ',' && numbers < 3) { numbers = 0; } else { numbers = 0; color = FALSE; newstr += text[i]; } i++; } return newstr; } FXString IrcTabItem::getNick(FXint i) { return m_users->getItemText(i); } FXint IrcTabItem::getNickColor(const FXString &nick) { //10 is first colored nick style return 10+nick.hash()%8; } FXColor IrcTabItem::getIrcColor(FXint code) { switch(code){ case 0: return fxcolorfromname("white"); case 1: return fxcolorfromname("black"); case 2: return FXRGB(0,0,128); //blue case 3: return FXRGB(0,128,0); //green case 4: return FXRGB(255,0,0); //lightred case 5: return FXRGB(128,0,64); //brown case 6: return FXRGB(128,0,128); //purple case 7: return FXRGB(255,128,64); //orange case 8: return FXRGB(255,255,0); //yellow case 9: return FXRGB(128,255,0); //lightgreen case 10: return FXRGB(0,128,128); //cyan case 11: return FXRGB(0,255,255); //lightcyan case 12: return FXRGB(0,0,255); //lightblue case 13: return FXRGB(255,0,255); //pink case 14: return FXRGB(128,128,128); //grey case 15: return FXRGB(192,192,192); //lightgrey default: return m_colors.text; } } FXint IrcTabItem::hiliteStyleExist(FXColor foreColor, FXColor backColor, FXuint style) { for(FXint i=0; i<m_textStyleList.no(); i++) { if(m_textStyleList[i].normalForeColor == foreColor && m_textStyleList[i].normalBackColor == backColor && m_textStyleList[i].style == style) return i+1; } return -1; } void IrcTabItem::createHiliteStyle(FXColor foreColor, FXColor backColor, FXuint style) { dxHiliteStyle nstyle = {foreColor,backColor,getApp()->getSelforeColor(),getApp()->getSelbackColor(),style,FALSE}; m_textStyleList.append(nstyle); m_text->setHiliteStyles(m_textStyleList.data()); } dxStringArray IrcTabItem::cutText(FXString text, FXint len) { FXint textLen = text.length(); FXint previous = 0; dxStringArray texts; while(textLen>len) { texts.append(text.mid(previous, len)); previous += len; textLen -= len; } texts.append(text.mid(previous, len)); return texts; } void IrcTabItem::setCommandFocus() { m_commandline->setFocus(); } //for "handle" checking, if script contains "all". Send from dxirc. void IrcTabItem::hasAllCommand(FXbool result) { m_scriptHasAll = result; } //for "handle" checking, if script contains "mymsg". Send from dxirc. void IrcTabItem::hasMyMsg(FXbool result) { m_scriptHasMyMsg = result; } //check need of highlight in msg FXbool IrcTabItem::highlightNeeded(const FXString &msg) { FXint pos = msg.find(getNickName()); if(pos==-1) return FALSE; FXbool before = TRUE; FXbool after = FALSE; if(pos) before = isDelimiter(msg[pos-1]); if(pos+getNickName().length() == msg.length()) after = TRUE; if(pos+getNickName().length() < msg.length()) after = isDelimiter(msg[pos+getNickName().length()]); return before && after; }
rofl0r/dxirc
src/irctabitem.cpp
C++
gpl-2.0
183,742
<?php # i think this class should go somewhere in a common PEAR-place, # because a lot of classes use options, at least PEAR::DB does # but since it is not very fancy to crowd the PEAR-namespace too much i dont know where to put it yet :-( // // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2003 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.02 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://www.php.net/license/2_02.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Authors: Wolfram Kriesing <wolfram@kriesing.de> | // +----------------------------------------------------------------------+ // // $Id: Options.php,v 1.4 2003/01/04 11:56:27 mj Exp $ require_once('PEAR.php'); /** * this class only defines commonly used methods, etc. * it is worthless without being extended * * @package Tree * @access public * @author Wolfram Kriesing <wolfram@kriesing.de> * */ class Tree_Options extends PEAR { /** * @var array $options you need to overwrite this array and give the keys, that are allowed */ var $options = array(); var $_forceSetOption = false; /** * this constructor sets the options, since i normally need this and * in case the constructor doesnt need to do anymore i already have it done :-) * * @version 02/01/08 * @access public * @author Wolfram Kriesing <wolfram@kriesing.de> * @param array the key-value pairs of the options that shall be set * @param boolean if set to true options are also set * even if no key(s) was/were found in the options property */ function Tree_Options( $options=array() , $force=false ) { $this->_forceSetOption = $force; if( is_array($options) && sizeof($options) ) foreach( $options as $key=>$value ) $this->setOption( $key , $value ); } /** * * @access public * @author Stig S. Baaken * @param * @param * @param boolean if set to true options are also set * even if no key(s) was/were found in the options property */ function setOption( $option , $value , $force=false ) { if( is_array($value) ) // if the value is an array extract the keys and apply only each value that is set { // so we dont override existing options inside an array, if an option is an array foreach( $value as $key=>$aValue ) $this->setOption( array($option , $key) , $aValue ); return true; } if( is_array($option) ) { $mainOption = $option[0]; $options = "['".implode("']['",$option)."']"; $evalCode = "\$this->options".$options." = \$value;"; } else { $evalCode = "\$this->options[\$option] = \$value;"; $mainOption = $option; } if( $this->_forceSetOption==true || $force==true || isset($this->options[$mainOption]) ) { eval($evalCode); return true; } return false; } /** * set a number of options which are simply given in an array * * @access public * @author * @param * @param boolean if set to true options are also set * even if no key(s) was/were found in the options property */ function setOptions( $options , $force=false ) { if( is_array($options) && sizeof($options) ) { foreach( $options as $key=>$value ) { $this->setOption( $key , $value , $force ); } } } /** * * @access public * @author copied from PEAR: DB/commmon.php * @param boolean true on success */ function getOption($option) { if( func_num_args() > 1 && is_array($this->options[$option])) { $args = func_get_args(); $evalCode = "\$ret = \$this->options['".implode( "']['" , $args )."'];"; eval( $evalCode ); return $ret; } if (isset($this->options[$option])) { return $this->options[$option]; } # return $this->raiseError("unknown option $option"); return false; } /** * returns all the options * * @version 02/05/20 * @access public * @author Wolfram Kriesing <wolfram@kriesing.de> * @return string all options as an array */ function getOptions() { return $this->options; } } // end of class ?>
Esleelkartea/kz-adeada-talleres-electricos-
kzadeadatallereselectricos_v1.0.0_linux32_installer/linux/lampp/lib/php/Tree/Options.php
PHP
gpl-2.0
5,542
<?php // $Id$ /*! * Dynamic display block module template: custom40-a - content template * Copyright (c) 2008 - 2009 P. Blaauw All rights reserved. * Version 1.1 (11-FEB-2009) * Licenced under GPL license * http://www.gnu.org/licenses/gpl.html */ /** * @file * Dynamic display block module template: custom40-a - content template * * Available variables: * - $origin: From which module comes the block. * - $delta: Block number of the block. * * - $custom_template: template name * - $output_type: type of content * * - $slider_items: array with slidecontent * - $slide_text_position of the text in the slider (top | right | bottom | left) * - $slide_direction: direction of the text in the slider (horizontal | vertical ) * - * - $pager_content: Themed pager content * - $pager_position: position of the pager (top | bottom) * * notes: don't change the ID names, they are used by the jQuery script. */ // add Cascading style sheet drupal_add_css($directory .'/custom/modules/ddblock/'.$custom_template. '/ddblock-cycle-'.$custom_template. '.css', 'template', 'all', FALSE); ?> <!-- dynamic display block slideshow --> <div id="ddblock-<?php print $delta ?>" class="ddblock-cycle-<?php print $custom_template ?> clear-block"> <div class="container clear-block border"> <div class="container-inner clear-block border"> <?php if ($pager_position == "top") : ?> <!-- custom pager image --> <?php print $pager_content ?> <?php endif; ?> <!-- slider content --> <div class="slider clear-block border"> <div class="slider-inner clear-block border"> <?php if ($output_type == 'view_fields') : ?> <?php foreach ($slider_items as $slider_item): ?> <div class="slide clear-block border"> <div class="slide-inner clear-block border"> <?php print $slider_item['slide_image']; ?> <div class="slide-text slide-text-<?php print $slide_direction ?> slide-text-<?php print $slide_text_position ?> clear-block border"> <div class="slide-text-inner clear-block border"> <div class="slide-title slide-title-<?php print $slide_direction ?> clear-block border"> <div class="slide-title-inner clear-block border"> <h2><?php print $slider_item['slide_title'] ?></h2> </div> <!-- slide-title-inner--> </div> <!-- slide-title--> <div class="slide-body-<?php print $slide_direction ?> clear-block border"> <div class="slide-body-inner clear-block border"> <p><?php print $slider_item['slide_text'] ?></p> </div> <!-- slide-body-inner--> </div> <!-- slide-body--> <div class="slide-read-more slide-read-more-<?php print $slide_direction ?> clear-block border"> <p><?php print $slider_item['slide_read_more'] ?></p> </div><!-- slide-read-more--> </div> <!-- slide-text-inner--> </div> <!-- slide-text--> </div> <!-- slide-inner--> </div> <!-- slide--> <?php endforeach; ?> <?php endif; ?> </div> <!-- slider-inner--> </div> <!-- slider--> <?php if ($pager_position == "bottom") : ?> <!-- custom pager image --> <?php print $pager_content ?> <?php endif; ?> </div> <!-- container-inner--> </div> <!--container--> </div> <!-- template -->
pgrayove/mcpl-site-backup
sites/all/themes/mcpl/custom/modules/ddblock/ddblock-cycle-block-content-custom40-a.tpl.php
PHP
gpl-2.0
3,422
/* * #%L * OME Metadata Editor application for exploration and editing of OME-XML and * OME-TIFF metadata. * %% * Copyright (C) 2006 - 2012 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * 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/gpl-2.0.html>. * #L% */ package loci.ome.editor; import java.awt.Component; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.TableCellEditor; /** * A class that handles editing of a cell that is defined in * the template as having no Type attribute, e.g. it is neither * of type "Ref" or type "Desc". Creates a JTextField to edit * this cell instead of something fancy. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/legacy/ome-editor/src/loci/ome/editor/VariableTextFieldEditor.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/legacy/ome-editor/src/loci/ome/editor/VariableTextFieldEditor.java;hb=HEAD">Gitweb</a></dd></dl> * * @author Christopher Peterson crpeterson2 at wisc.edu */ public class VariableTextFieldEditor extends VariableTextEditor implements TableCellEditor { /** Construct a new VariableTextFieldEditor.*/ public VariableTextFieldEditor(MetadataPane.TablePanel tp) { super(tp); } // -- TableCellEditor API methods -- /** * The method a table calls to get the editing component for a * particular cell. */ public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { JTextField text = new JTextField(new RowDoc(row), (String) value, 1); text.getDocument().addDocumentListener(this); text.addFocusListener(this); text.addMouseListener(this); text.addActionListener(this); return text; } }
mtbc/bioformats
components/legacy/ome-editor/src/loci/ome/editor/VariableTextFieldEditor.java
Java
gpl-2.0
2,545
<?php /* Plugin Name: Huge IT Portfolio Gallery Plugin URI: http://huge-it.com/portfolio-gallery Description: Portfolio Gallery is a great plugin for adding specialized portfolios or gallery to your site. There are various view options for the images to choose from. Version: 1.3.6 Author: http://huge-it.com/ License: GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ add_action('media_buttons_context', 'add_portfolio_my_custom_button'); add_action('admin_footer', 'add_portfolio_inline_popup_content'); function add_portfolio_my_custom_button($context) { $img = plugins_url( '/images/post.button.png' , __FILE__ ); $container_id = 'huge_it_portfolio'; $title = 'Select Huge IT Portfolio Gallery to insert into post.'; $context .= '<a class="button thickbox" title="Select portfolio gallery to insert into post" href="#TB_inline?width=400&inlineId='.$container_id.'"> <span class="wp-media-buttons-icon" style="background: url('.$img.'); background-repeat: no-repeat; background-position: left bottom;"></span> Add Portfolio Gallery </a>'; return $context; } function add_portfolio_inline_popup_content() { ?> <script type="text/javascript"> jQuery(document).ready(function() { jQuery('#hugeitportfolioinsert').on('click', function() { var id = jQuery('#huge_it_portfolio-select option:selected').val(); window.send_to_editor('[huge_it_portfolio id="' + id + '"]'); tb_remove(); }) }); </script> <div id="huge_it_portfolio" style="display:none;"> <h3>Select Huge IT Portfolio Gallery to insert into post</h3> <?php global $wpdb; $query="SELECT * FROM ".$wpdb->prefix."huge_itportfolio_portfolios order by id ASC"; $shortcodeportfolios=$wpdb->get_results($query); ?> <?php if (count($shortcodeportfolios)) { echo "<select id='huge_it_portfolio-select'>"; foreach ($shortcodeportfolios as $shortcodeportfolio) { echo "<option value='".$shortcodeportfolio->id."'>".$shortcodeportfolio->name."</option>"; } echo "</select>"; echo "<button class='button primary' id='hugeitportfolioinsert'>Insert portfolio gallery</button>"; } else { echo "No slideshows found", "huge_it_portfolio"; } ?> </div> <?php } ///////////////////////////////////shortcode update///////////////////////////////////////////// add_action('init', 'hugesl_portfolio_do_output_buffer'); function hugesl_portfolio_do_output_buffer() { ob_start(); } add_action('init', 'portfolio_lang_load'); function portfolio_lang_load() { load_plugin_textdomain('sp_portfolio', false, basename(dirname(__FILE__)) . '/Languages'); } function huge_it_portfolio_images_list_shotrcode($atts) { extract(shortcode_atts(array( 'id' => 'no huge_it portfolio', ), $atts)); return huge_it_portfolio_images_list($atts['id']); } /////////////// Filter portfolio gallery function portfolio_after_search_results($query) { global $wpdb; if (isset($_REQUEST['s']) && $_REQUEST['s']) { $serch_word = htmlspecialchars(($_REQUEST['s'])); $query = str_replace($wpdb->prefix . "posts.post_content", gen_string_portfolio_search($serch_word, $wpdb->prefix . 'posts.post_content') . " " . $wpdb->prefix . "posts.post_content", $query); } return $query; } add_filter('posts_request', 'portfolio_after_search_results'); function gen_string_portfolio_search($serch_word, $wordpress_query_post) { $string_search = ''; global $wpdb; if ($serch_word) { $rows_portfolio = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $wpdb->prefix . "huge_itportfolio_portfolios WHERE (description LIKE %s) OR (name LIKE %s)", '%' . $serch_word . '%', "%" . $serch_word . "%")); $count_cat_rows = count($rows_portfolio); for ($i = 0; $i < $count_cat_rows; $i++) { $string_search .= $wordpress_query_post . ' LIKE \'%[huge_it_portfolio id="' . $rows_portfolio[$i]->id . '" details="1" %\' OR ' . $wordpress_query_post . ' LIKE \'%[huge_it_portfolio id="' . $rows_portfolio[$i]->id . '" details="1"%\' OR '; } $rows_portfolio = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $wpdb->prefix . "huge_itportfolio_portfolios WHERE (name LIKE %s)","'%" . $serch_word . "%'")); $count_cat_rows = count($rows_portfolio); for ($i = 0; $i < $count_cat_rows; $i++) { $string_search .= $wordpress_query_post . ' LIKE \'%[huge_it_portfolio id="' . $rows_portfolio[$i]->id . '" details="0"%\' OR ' . $wordpress_query_post . ' LIKE \'%[huge_it_portfolio id="' . $rows_portfolio[$i]->id . '" details="0"%\' OR '; } $rows_single = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . $wpdb->prefix . "huge_itportfolio_images WHERE name LIKE %s","'%" . $serch_word . "%'")); $count_sing_rows = count($rows_single); if ($count_sing_rows) { for ($i = 0; $i < $count_sing_rows; $i++) { $string_search .= $wordpress_query_post . ' LIKE \'%[huge_it_portfolio_Product id="' . $rows_single[$i]->id . '"]%\' OR '; } } } return $string_search; } ///////////////////// end filter add_shortcode('huge_it_portfolio', 'huge_it_portfolio_images_list_shotrcode'); function huge_it_portfolio_images_list($id) { require_once("Front_end/portfolio_front_end_view.php"); require_once("Front_end/portfolio_front_end_func.php"); if (isset($_GET['product_id'])) { if (isset($_GET['view'])) { if ($_GET['view'] == 'huge_itportfolio') { return showPublishedportfolios_1($id); } else { return front_end_single_product($_GET['product_id']); } } else { return front_end_single_product($_GET['product_id']); } } else { return showPublishedportfolios_1($id); } } add_filter('admin_head', 'huge_it_portfolio_ShowTinyMCE'); function huge_it_portfolio_ShowTinyMCE() { // conditions here wp_enqueue_script('common'); wp_enqueue_script('jquery-color'); wp_print_scripts('editor'); if (function_exists('add_thickbox')) add_thickbox(); wp_print_scripts('media-upload'); if (version_compare(get_bloginfo('version'), 3.3) < 0) { if (function_exists('wp_tiny_mce')) wp_tiny_mce(); } wp_admin_css(); wp_enqueue_script('utils'); do_action("admin_print_styles-post-php"); do_action('admin_print_styles'); } function portfolio_frontend_scripts_and_styles() { wp_register_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', array('jquery'),'1.0.0',true ); wp_enqueue_script( 'jquery' ); wp_register_script( 'portfolio-all-js', plugins_url('/js/portfolio-all.js', __FILE__), array('jquery'),'1.0.0',true ); wp_enqueue_script( 'portfolio-all-js' ); wp_register_style( 'portfolio-all-css', plugins_url('/style/portfolio-all.css', __FILE__) ); wp_enqueue_style( 'portfolio-all-css' ); wp_register_script( 'jquery.colorbox-js', plugins_url('/js/jquery.colorbox.js', __FILE__), array('jquery'),'1.0.0',true ); wp_enqueue_script( 'jquery.colorbox-js' ); wp_register_script( 'hugeitmicro-min-js', plugins_url('/js/jquery.hugeitmicro.min.js', __FILE__), array('jquery'),'1.0.0',true ); wp_enqueue_script( 'hugeitmicro-min-js' ); wp_register_style( 'style2-os-css', plugins_url('/style/style2-os.css', __FILE__) ); wp_enqueue_style( 'style2-os-css' ); wp_register_style( 'lightbox-css', plugins_url('/style/lightbox.css', __FILE__) ); wp_enqueue_style( 'lightbox-css' ); } add_action('wp_enqueue_scripts', 'portfolio_frontend_scripts_and_styles'); add_action('admin_menu', 'huge_it_portfolio_options_panel'); function huge_it_portfolio_options_panel() { $page_cat = add_menu_page('Theme page title', 'Huge IT Portfolio', 'manage_options', 'portfolios_huge_it_portfolio', 'portfolios_huge_it_portfolio', plugins_url('images/huge_it_portfolioLogoHover -for_menu.png', __FILE__)); add_submenu_page('portfolios_huge_it_portfolio', 'Portfolios', 'Portfolios', 'manage_options', 'portfolios_huge_it_portfolio', 'portfolios_huge_it_portfolio'); $page_option = add_submenu_page('portfolios_huge_it_portfolio', 'General Options', 'General Options', 'manage_options', 'Options_portfolio_styles', 'Options_portfolio_styles'); $lightbox_options = add_submenu_page('portfolios_huge_it_portfolio', 'Lightbox Options', 'Lightbox Options', 'manage_options', 'Options_portfolio_lightbox_styles', 'Options_portfolio_lightbox_styles'); add_submenu_page( 'portfolios_huge_it_portfolio', 'Licensing', 'Licensing', 'manage_options', 'huge_it_portfolio_Licensing', 'huge_it_portfolio_Licensing'); add_submenu_page('portfolios_huge_it_portfolio', 'Featured Plugins', 'Featured Plugins', 'manage_options', 'huge_it__portfolio_featured_plugins', 'huge_it__portfolio_featured_plugins'); add_action('admin_print_styles-' . $page_cat, 'huge_it_portfolio_admin_script'); add_action('admin_print_styles-' . $page_option, 'huge_it_portfolio_option_admin_script'); add_action('admin_print_styles-' . $lightbox_options, 'huge_it_portfolio_option_admin_script'); } function huge_it__portfolio_featured_plugins() { include_once("admin/huge_it_featured_plugins.php"); } function huge_it_portfolio_Licensing(){ ?> <div style="width:95%"> <p> This plugin is the non-commercial version of the Huge IT Portfolio / Gallery. If you want to customize to the styles and colors of your website,than you need to buy a license. Purchasing a license will add possibility to customize the general options and lightbox of the Huge IT Portfolio / Gallery. </p> <br /><br /> <a href="http://huge-it.com/portfolio-gallery/" class="button-primary" target="_blank">Purchase a License</a> <br /><br /><br /> <p>After the purchasing the commercial version follow this steps:</p> <ol> <li>Deactivate Huge IT Portfolio / Gallery Plugin</li> <li>Delete Huge IT Portfolio / Gallery Plugin</li> <li>Install the downloaded commercial version of the plugin</li> </ol> </div> <?php } function huge_it_portfolio_admin_script() { wp_enqueue_media(); wp_enqueue_style("jquery_ui", "http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css", FALSE); wp_enqueue_style("admin_css", plugins_url("style/admin.style.css", __FILE__), FALSE); wp_enqueue_script("admin_js", plugins_url("js/admin.js", __FILE__), FALSE); } function huge_it_portfolio_option_admin_script() { wp_enqueue_script("jquery_old", "http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js", FALSE); wp_enqueue_script("simple_slider_js", plugins_url("js/simple-slider.js", __FILE__), FALSE); wp_enqueue_style("simple_slider_css", plugins_url("style/simple-slider.css", __FILE__), FALSE); wp_enqueue_style("admin_css", plugins_url("style/admin.style.css", __FILE__), FALSE); wp_enqueue_script("admin_js", plugins_url("js/admin.js", __FILE__), FALSE); wp_enqueue_script('param_block2', plugins_url("elements/jscolor/jscolor.js", __FILE__)); } function portfolios_huge_it_portfolio() { require_once("admin/portfolios_func.php"); require_once("admin/portfolios_view.php"); if (!function_exists('print_html_nav')) require_once("portfolio_function/html_portfolio_func.php"); if (isset($_GET["task"])) $task = $_GET["task"]; else $task = ''; if (isset($_GET["id"])) $id = $_GET["id"]; else $id = 0; global $wpdb; switch ($task) { case 'add_cat': add_portfolio(); break; case 'edit_cat': if ($id) editportfolio($id); else { $id = $wpdb->get_var("SELECT MAX( id ) FROM " . $wpdb->prefix . "huge_itportfolio_portfolios"); editportfolio($id); } break; case 'save': if ($id) apply_cat($id); case 'apply': if ($id) { apply_cat($id); editportfolio($id); } break; case 'remove_cat': removeportfolio($id); showportfolio(); break; default: showportfolio(); break; } } function Options_portfolio_styles() { require_once("admin/portfolio_Options_func.php"); require_once("admin/portfolio_Options_view.php"); if (isset($_GET['task'])) if ($_GET['task'] == 'save') save_styles_options(); showStyles(); } function Options_portfolio_lightbox_styles() { require_once("admin/portfolio_lightbox_func.php"); require_once("admin/portfolio_lightbox_view.php"); if (isset($_GET['task'])) if ($_GET['task'] == 'save') save_styles_options(); showStyles(); } class Huge_it_portfolio_Widget extends WP_Widget { public function __construct() { parent::__construct( 'Huge_it_portfolio_Widget', 'Huge IT Portfolio', array( 'description' => __( 'Huge IT Portfolio', 'huge_it_portfolio' ), ) ); } public function widget( $args, $instance ) { extract($args); if (isset($instance['portfolio_id'])) { $portfolio_id = $instance['portfolio_id']; $title = apply_filters( 'widget_title', $instance['title'] ); echo $before_widget; if ( ! empty( $title ) ) echo $before_title . $title . $after_title; echo do_shortcode("[huge_it_portfolio id={$portfolio_id}]"); echo $after_widget; } } public function update( $new_instance, $old_instance ) { $instance = array(); $instance['portfolio_id'] = strip_tags( $new_instance['portfolio_id'] ); $instance['title'] = strip_tags( $new_instance['title'] ); return $instance; } public function form( $instance ) { $selected_portfolio = 0; $title = ""; $portfolios = false; if (isset($instance['portfolio_id'])) { $selected_portfolio = $instance['portfolio_id']; } if (isset($instance['title'])) { $title = $instance['title']; } ?> <p> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /> </p> <label for="<?php echo $this->get_field_id('portfolio_id'); ?>"><?php _e('Select portfolio:', 'huge_it_portfolio'); ?></label> <select id="<?php echo $this->get_field_id('portfolio_id'); ?>" name="<?php echo $this->get_field_name('portfolio_id'); ?>"> <?php global $wpdb; $query="SELECT * FROM ".$wpdb->prefix."huge_itportfolio_portfolios "; $rowwidget=$wpdb->get_results($query); foreach($rowwidget as $rowwidgetecho){ ?> <option <?php if($rowwidgetecho->id == $instance['portfolio_id']){ echo 'selected'; } ?> value="<?php echo $rowwidgetecho->id; ?>"><?php echo $rowwidgetecho->name; ?></option> <?php } ?> </select> </p> <?php } } add_action('widgets_init', 'register_Huge_it_portfolio_Widget'); function register_Huge_it_portfolio_Widget() { register_widget('Huge_it_portfolio_Widget'); } ////////////////////////////////////////////////////// /////////////////////////////////////////////////////// ////////////////////////////////////////////////////// Activate portfolio gallery /////////////////////////////////////////////////////// ////////////////////////////////////////////////////// /////////////////////////////////////////////////////// function huge_it_portfolio_activate() { global $wpdb; /// creat database tables $sql_huge_itportfolio_images = " CREATE TABLE IF NOT EXISTS `" . $wpdb->prefix . "huge_itportfolio_images` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(100) DEFAULT NULL, `portfolio_id` varchar(200) DEFAULT NULL, `description` text, `image_url` text, `sl_url` varchar(128) DEFAULT NULL, `sl_type` text NOT NULL, `link_target` text NOT NULL, `ordering` int(11) NOT NULL, `published` tinyint(4) unsigned DEFAULT NULL, `published_in_sl_width` tinyint(4) unsigned DEFAULT NULL, `category` varchar(200) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5"; $sql_huge_itportfolio_portfolios = " CREATE TABLE IF NOT EXISTS `" . $wpdb->prefix . "huge_itportfolio_portfolios` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(200) NOT NULL, `sl_height` int(11) unsigned DEFAULT NULL, `sl_width` int(11) unsigned DEFAULT NULL, `pause_on_hover` text, `portfolio_list_effects_s` text, `description` text, `param` text, `sl_position` text NOT NULL, `ordering` int(11) NOT NULL, `published` text, `categories` text NOT NULL, `ht_show_sorting` text NOT NULL, `ht_show_filtering` text NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 "; $table_name = $wpdb->prefix . "huge_itportfolio_images"; $sql_2 = " INSERT INTO `" . $table_name . "` (`id`, `name`, `portfolio_id`, `description`, `image_url`, `sl_url`, `sl_type`, `link_target`, `ordering`, `published`, `published_in_sl_width`) VALUES (1, 'Cutthroat & Cavalier', '1', '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', '".plugins_url("Front_images/projects/1.jpg", __FILE__).";".plugins_url("Front_images/projects/1.1.jpg", __FILE__).";".plugins_url("Front_images/projects/1.2.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 0, 1, NULL), (2, 'Cone Music', '1', '<ul><li>lorem ipsumdolor sit amet</li><li>lorem ipsum dolor sit amet</li></ul><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', '".plugins_url("Front_images/projects/5.jpg", __FILE__).";".plugins_url("Front_images/projects/5.1.jpg", __FILE__).";".plugins_url("Front_images/projects/5.2.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 1, 1, NULL), (3, 'Nexus', '1', '<h6>Lorem Ipsum </h6><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><ul><li>lorem ipsum</li><li>dolor sit amet</li><li>lorem ipsum</li><li>dolor sit amet</li></ul>', '".plugins_url("Front_images/projects/3.jpg", __FILE__).";".plugins_url("Front_images/projects/3.1.jpg", __FILE__).";".plugins_url("Front_images/projects/3.2.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 2, 1, NULL), (4, 'De7igner', '1', '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p><h7>Dolor sit amet</h7><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', '".plugins_url("Front_images/projects/4.jpg", __FILE__).";".plugins_url("Front_images/projects/4.1.jpg", __FILE__).";".plugins_url("Front_images/projects/4.2.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 3, 1, NULL), (5, 'Autumn / Winter Collection', '1', '<h6>Lorem Ipsum</h6><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', '".plugins_url("Front_images/projects/2.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 4, 1, NULL), (6, 'Retro Headphones', '1', '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', '".plugins_url("Front_images/projects/6.jpg", __FILE__).";".plugins_url("Front_images/projects/6.1.jpg", __FILE__).";".plugins_url("Front_images/projects/6.2.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 5, 1, NULL), (7, 'Take Fight', '1', '<h6>Lorem Ipsum</h6><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>', '".plugins_url("Front_images/projects/7.jpg", __FILE__).";".plugins_url("Front_images/projects/7.2.jpg", __FILE__).";".plugins_url("Front_images/projects/7.3.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 6, 1, NULL), (8, 'The Optic', '1', '<h6>Lorem Ipsum </h6><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </p><p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p><ul><li>lorem ipsum</li><li>dolor sit amet</li><li>lorem ipsum</li><li>dolor sit amet</li></ul>', '".plugins_url("Front_images/projects/8.jpg", __FILE__).";".plugins_url("Front_images/projects/8.1.jpg", __FILE__).";".plugins_url("Front_images/projects/8.3.jpg", __FILE__).";', 'http://huge-it.com/fields/order-website-maintenance/', 'image', 'on', 7, 1, NULL)"; $table_name = $wpdb->prefix . "huge_itportfolio_portfolios"; $sql_3 = " INSERT INTO `$table_name` (`id`, `name`, `sl_height`, `sl_width`, `pause_on_hover`, `portfolio_list_effects_s`, `description`, `param`, `sl_position`, `ordering`, `published`) VALUES (1, 'My First Portfolio', 375, 600, 'on', '2', '4000', '1000', 'center', 1, '300')"; $wpdb->query($sql_huge_itportfolio_params); $wpdb->query($sql_huge_itportfolio_images); $wpdb->query($sql_huge_itportfolio_portfolios); if (!$wpdb->get_var("select count(*) from " . $wpdb->prefix . "huge_itportfolio_images")) { $wpdb->query($sql_2); } if (!$wpdb->get_var("select count(*) from " . $wpdb->prefix . "huge_itportfolio_portfolios")) { $wpdb->query($sql_3); } ///////////////////////////update//////////////////////////////////// $imagesAllFieldsInArray = $wpdb->get_results("DESCRIBE " . $wpdb->prefix . "huge_itportfolio_images", ARRAY_A); $forUpdate = 0; foreach ($imagesAllFieldsInArray as $portfoliosField) { if ($portfoliosField['Field'] == 'category') { // "ka category field.<br>"; $forUpdate = 1; $catValues = $wpdb->get_results( "SELECT category FROM ".$wpdb->prefix."huge_itportfolio_images" ); $needToUpdate=0; foreach($catValues as $catValue){ if($catValue->category !== '') { $needToUpdate=1; //echo "category field - y datark chi.<br>"; } } if($needToUpdate == 0){ $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My First Category,My Third Category,' WHERE id='1'"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Second Category,' WHERE id='2'"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Third Category,' WHERE id='3'"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My First Category,My Second Category,' WHERE id='4'"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Second Category,My Third Category,' WHERE id='5'"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Third Category,' WHERE id='6'"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Second Category,' WHERE id='7'"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My First Category,' WHERE id='8'"); } break; } } if ($forUpdate == '0') { $wpdb->query("ALTER TABLE ".$wpdb->prefix."huge_itportfolio_images ADD category text"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My First Category,My Third Category,' WHERE id='1'"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Second Category,' WHERE id='2'"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Third Category,' WHERE id='3'"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My First Category,My Second Category,' WHERE id='4'"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Second Category,My Third Category,' WHERE id='5'"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Third Category,' WHERE id='6'"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My Second Category,' WHERE id='7'"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_images SET category = 'My First Category,' WHERE id='8'"); } $productPortfolio = $wpdb->get_results("DESCRIBE " . $wpdb->prefix . "huge_itportfolio_portfolios", ARRAY_A); $isUpdate = 0; foreach ($productPortfolio as $prodPortfolio) { if ($prodPortfolio['Field'] == 'categories' && $prodPortfolio['Type'] == 'text') { $isUpdate = 1; $allCats = $wpdb->get_results( "SELECT categories FROM ".$wpdb->prefix."huge_itportfolio_portfolios" ); $needToUpdateAllCats=0; foreach($allCats as $AllCatsVal){ if($AllCatsVal->categories !== '') { $needToUpdateAllCats=1; } } if($needToUpdateAllCats == 0){ $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_portfolios SET categories = 'My First Category,My Second Category,My Third Category,' "); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_portfolios SET ht_show_sorting = 'off' "); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_portfolios SET ht_show_filtering = 'off' "); } break; } } if ($isUpdate == '0') { $wpdb->query("ALTER TABLE ".$wpdb->prefix."huge_itportfolio_portfolios ADD categories text"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_portfolios SET categories = 'My First Category,My Second Category,My Third Category,'"); $wpdb->query("ALTER TABLE ".$wpdb->prefix."huge_itportfolio_portfolios ADD ht_show_sorting text"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_portfolios SET ht_show_sorting = 'off'"); $wpdb->query("ALTER TABLE ".$wpdb->prefix."huge_itportfolio_portfolios ADD ht_show_filtering text"); $wpdb->query("UPDATE ".$wpdb->prefix."huge_itportfolio_portfolios SET ht_show_filtering = 'off'"); } } register_activation_hook(__FILE__, 'huge_it_portfolio_activate');
YeongeunHeo/wordpress
wp-content/plugins/portfolio-gallery/portfolio-gallery.php
PHP
gpl-2.0
29,406
/* * This file is part of the OpenJML project. * Author: David R. Cok */ package org.jmlspecs.openjml.proverinterface; import org.jmlspecs.openjml.proverinterface.IProverResult.ICounterexample; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree.JCExpression; /** * A prover can be used to check if a formula is satisfiable, * given a set of assumptions. The prover may need to be restarted * before being reused. * <P> * The assume calls take a JCExpression encoding the logical expression * that the prover is to assume. This is a OpenJDK AST but of restricted * form. In particular, only the following AST nodes are allowed (there is * no runtime check of this restriction): * <UL> * <LI>JCBinary - with any Java operator * <LI>JmlBinary - with any JML operator * <LI>JCUnary - with any Java operator * <LI>JCIdent - the identifier for a logical variable, with the * type field giving the Java type of the variable * <LI>JCConditional - an if-then-else (i.e. ?:) construct * <LI>JmlBBFieldAccess - encodes field access (replaces JCFieldAccess) * <LI>JmlBBArrayAccess - array access, replacing JCArrayAccess * <LI>JCParens - not needed but helps to keep pretty printed expressions less confusing * <LI>JCLiteral - for boolean, integer, null literals * <LI>JCMethodInvocation - FIXME - needs explanation * </UL> * * * * TODO add properties, like timelimit * * @author David Cok, based on previous work by rgrig */ public interface IProver { /** Returns an identifying name for the prover */ public String name(); /** * Adds {@code tree} as an assumption; the concrete IProver is * responsible to translate the AST into prover-dependent form. * @param tree the assumption * @return an integer id for the assumption (or 0 if ids are not supported) * @throws ProverException if something goes wrong */ public int assume(/*@ non_null*/JCExpression tree) throws ProverException; /** * Adds {@code tree} as an assumption; the concrete IProver is * responsible to translate the AST into prover-dependent form. * @param tree the assumption * @param weight a weight to be associated with the assertion (may be * ignored if the prover does not support weights) * @return an integer id for the assumption (or 0 if ids are not supported) * @throws ProverException if something goes wrong */ public int assume(/*@ non_null*/JCExpression tree, int weight) throws ProverException; /** Tells the prover to define a given variable as the stated type * (not all provers need this) * @param id the name of the variable * @param type the type of the variable * @throws ProverException if something goes wrong */ public void define(/*@ non_null*/String id, /*@ non_null*/Type type) throws ProverException; /** Tells the prover to define a given variable as the stated type and with the given value * (not all provers need this) * @param id the name of the variable * @param type the type of the variable * @param value the value the variable is an abbreviation for * @throws ProverException if something goes wrong */ public void define(/*@ non_null*/String id, /*@ non_null*/Type type, /*@ non_null*/ JCExpression value) throws ProverException; /** * Retract the last assumption. * @throws ProverException if something goes wrong */ public void retract() throws ProverException; /** * Retracts a specific assumption. * @param i the assertion to retract * @throws ProverException if something goes wrong */ public void retract(int i) throws ProverException; /** * Make a new frame of assumptions. * @throws ProverException if something goes wrong */ public void push() throws ProverException; /** * Removes the last frame of assumptions. * @throws ProverException if something goes wrong */ public void pop() throws ProverException; /** Checks whether the set of assertions known to the prover so far * is satisfiable or not * @return an object containing the details of the prover answer * @throws ProverException if something goes wrong */ // /*@ non_null*/ // public IProverResult check() throws ProverException; /*@ non_null*/ public IProverResult check(boolean details) throws ProverException; /** * Kills and restarts the prover process. Then it resends * all the assumptions that are on the stack. * @throws ProverException if something goes wrong */ public void restartProver() throws ProverException; /** Kills the prover * @throws ProverException if something goes wrong */ public void kill() throws ProverException; public void reassertCounterexample(ICounterexample ce); public Supports supports(); static public class Supports { public Supports() { retract = false; unsatcore = false; } public boolean retract; public boolean unsatcore; } }
shunghsiyu/OpenJML_XOR
OpenJML/src/org/jmlspecs/openjml/proverinterface/IProver.java
Java
gpl-2.0
5,173
package org.mo.logic.deploy; import org.mo.com.xml.IXmlObject; import org.mo.eng.store.IXmlConfigConsole; public interface IDeployConsole extends IXmlConfigConsole<IXmlObject> { void install(EDeploySource type); void installAll(EDeploySource type); void uninstall(EDeploySource type); void uninstallAll(EDeploySource type); }
favedit/MoPlatform
mo-3-logic/src/logic-java/org/mo/logic/deploy/IDeployConsole.java
Java
gpl-2.0
358
package com.sales.service; import java.util.List; import com.sales.model.TCurrency; public interface K3EntryService { public List getPayCondition(); public List getCurrency(); public TCurrency getCurrencyById(Integer fCurrencyID); public List getEmp(String fName); public List getDepartList(); public List getStaff(); public List getUser(); public List getEmpList(); /** * @return 销售报价单开票方式 */ public List getInvoiceTypeList(); /** * @return 销售报价单运输方式 */ public List getTransTypeList(); }
goulin2k/salesManager
salesManagerServer/src/com/sales/service/K3EntryService.java
Java
gpl-2.0
604
/* * org.openmicroscopy.shoola.agents.fsimporter.AnnotationDataLoader * *------------------------------------------------------------------------------ * Copyright (C) 2013 University of Dundee & Open Microscopy Environment. * All rights reserved. * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * *------------------------------------------------------------------------------ */ package org.openmicroscopy.shoola.agents.fsimporter; //Java imports import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import org.openmicroscopy.shoola.agents.fsimporter.view.Importer; import org.openmicroscopy.shoola.agents.treeviewer.DataBrowserLoader; import omero.gateway.SecurityContext; import org.openmicroscopy.shoola.env.data.views.CallHandle; import pojos.FileAnnotationData; import pojos.FilesetData; /** * Loads the annotations of a given type linked to the specified image. * * @author Jean-Marie Burel &nbsp;&nbsp;&nbsp;&nbsp; * <a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a> * @since 4.4 */ public class AnnotationDataLoader extends DataImporterLoader { /** Handle to the asynchronous call so that we can cancel it.*/ private CallHandle handle; /** The index of the UI element.*/ private int index; /** The identifier of the image.*/ private long fileSetID; /** * Creates a new instance. * * @param viewer The Importer this data loader is for. * Mustn't be <code>null</code>. * @param ctx The security context. * @param imageID The identifier of the image. * @param index The index of the UI element. */ public AnnotationDataLoader(Importer viewer, SecurityContext ctx, long fileSetID, int index) { super(viewer, ctx); this.fileSetID = fileSetID; this.index = index; } /** * Loads the annotations. * @see DataImporterLoader#load() */ public void load() { List<String> nsInclude = new ArrayList<String>(); nsInclude.add(FileAnnotationData.LOG_FILE_NS); handle = mhView.loadAnnotations(ctx, FilesetData.class, Arrays.asList(fileSetID), FileAnnotationData.class, nsInclude, null, this); } /** * Cancels the data loading. * @see DataImporterLoader#load() */ public void cancel() { handle.cancel(); } /** * Feeds the result back to the viewer. * @see DataBrowserLoader#handleResult(Object) */ public void handleResult(Object result) { if (viewer.getState() == Importer.DISCARDED) return; Map<Long, Collection<FileAnnotationData>> map = (Map<Long, Collection<FileAnnotationData>>) result; viewer.setImportLogFile(map.get(fileSetID), fileSetID, index); } }
stelfrich/openmicroscopy
components/insight/SRC/org/openmicroscopy/shoola/agents/fsimporter/AnnotationDataLoader.java
Java
gpl-2.0
3,360
//@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Kokkos is licensed under 3-clause BSD terms of use: // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY NTESS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NTESS OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? Contact Christian R. Trott (crtrott@sandia.gov) // // ************************************************************************ //@HEADER #define KOKKOS_IMPL_COMPILING_LIBRARY true #include <Kokkos_Core.hpp> namespace Kokkos { namespace Impl { KOKKOS_IMPL_VIEWCOPY_ETI_INST(int64_t********, LayoutRight, LayoutRight, Experimental::ROCm, int) KOKKOS_IMPL_VIEWCOPY_ETI_INST(int64_t********, LayoutRight, LayoutLeft, Experimental::ROCm, int) KOKKOS_IMPL_VIEWCOPY_ETI_INST(int64_t********, LayoutRight, LayoutStride, Experimental::ROCm, int) KOKKOS_IMPL_VIEWFILL_ETI_INST(int64_t********, LayoutRight, Experimental::ROCm, int) } // namespace Impl } // namespace Kokkos
pastewka/lammps
lib/kokkos/core/src/eti/ROCm/Kokkos_ROCm_ViewCopyETIInst_int_int64_t_LayoutRight_Rank8.cpp
C++
gpl-2.0
2,682
#include <yafray_config.h> #include <core_api/ray.h> #include <core_api/color.h> #include <core_api/volume.h> #include <core_api/bound.h> #include <core_api/surface.h> #include <core_api/texture.h> #include <core_api/environment.h> #include <utilities/mcqmc.h> #include <fstream> #include <cstdlib> __BEGIN_YAFRAY struct renderState_t; struct pSample_t; class GridVolume : public DensityVolume { public: GridVolume(color_t sa, color_t ss, color_t le, float gg, point3d_t pmin, point3d_t pmax) { bBox = bound_t(pmin, pmax); s_a = sa; s_s = ss; l_e = le; g = gg; haveS_a = (s_a.energy() > 1e-4f); haveS_s = (s_s.energy() > 1e-4f); haveL_e = (l_e.energy() > 1e-4f); std::ifstream inputStream; inputStream.open("/home/public/3dkram/cloud2_3.df3"); if(!inputStream) Y_ERROR << "GridVolume: Error opening input stream" << yendl; inputStream.seekg(0, std::ios_base::beg); std::ifstream::pos_type begin_pos = inputStream.tellg(); inputStream.seekg(0, std::ios_base::end); int fileSize = static_cast<int>(inputStream.tellg() - begin_pos); fileSize -= 6; inputStream.seekg(0, std::ios_base::beg); int dim[3]; for (int i = 0; i < 3; ++i) { short i0 = 0, i1 = 0; inputStream.read( (char*)&i0, 1 ); inputStream.read( (char*)&i1, 1 ); Y_VERBOSE << "GridVolume: " << i0 << " " << i1 << yendl; dim[i] = (((unsigned short)i0 << 8) | (unsigned short)i1); } int sizePerVoxel = fileSize / (dim[0] * dim[1] * dim[2]); Y_VERBOSE << "GridVolume: " << dim[0] << " " << dim[1] << " " << dim[2] << " " << fileSize << " " << sizePerVoxel << yendl; sizeX = dim[0]; sizeY = dim[1]; sizeZ = dim[2]; /* sizeX = 60; sizeY = 60; sizeZ = 60; */ grid = (float***)malloc(sizeX * sizeof(float)); for (int x = 0; x < sizeX; ++x) { grid[x] = (float**)malloc(sizeY * sizeof(float)); for (int y = 0; y < sizeY; ++y) { grid[x][y] = (float*)malloc(sizeZ * sizeof(float)); } } for (int z = 0; z < sizeZ; ++z) { for (int y = 0; y < sizeY; ++y) { for (int x = 0; x < sizeX; ++x) { int voxel = 0; inputStream.read( (char*)&voxel, 1 ); grid[x][y][z] = voxel / 255.f; /* float r = sizeX / 2.f; float r2 = r*r; float dist = sqrt((x-r)*(x-r) + (y-r)*(y-r) + (z-r)*(z-r)); grid[x][y][z] = (dist < r) ? 1.f-dist/r : 0.0f; */ } } } Y_VERBOSE << "GridVolume: Vol.[" << s_a << ", " << s_s << ", " << l_e << "]" << yendl; } ~GridVolume() { Y_VERBOSE << "GridVolume: Freeing grid data" << yendl; for (int x = 0; x < sizeX; ++x) { for (int y = 0; y < sizeY; ++y) { free(grid[x][y]); } free(grid[x]); } free(grid); } virtual float Density(point3d_t p); static VolumeRegion* factory(paraMap_t &params, renderEnvironment_t &render); protected: float*** grid; int sizeX, sizeY, sizeZ; }; inline float min(float a, float b) { return (a > b) ? b : a; } inline float max(float a, float b) { return (a < b) ? b : a; } float GridVolume::Density(const point3d_t p) { float x = (p.x - bBox.a.x) / bBox.longX() * sizeX - .5f; float y = (p.y - bBox.a.y) / bBox.longY() * sizeY - .5f; float z = (p.z - bBox.a.z) / bBox.longZ() * sizeZ - .5f; int x0 = max(0, floor(x)); int y0 = max(0, floor(y)); int z0 = max(0, floor(z)); int x1 = min(sizeX - 1, ceil(x)); int y1 = min(sizeY - 1, ceil(y)); int z1 = min(sizeZ - 1, ceil(z)); float xd = x - x0; float yd = y - y0; float zd = z - z0; float i1 = grid[x0][y0][z0] * (1-zd) + grid[x0][y0][z1] * zd; float i2 = grid[x0][y1][z0] * (1-zd) + grid[x0][y1][z1] * zd; float j1 = grid[x1][y0][z0] * (1-zd) + grid[x1][y0][z1] * zd; float j2 = grid[x1][y1][z0] * (1-zd) + grid[x1][y1][z1] * zd; float w1 = i1 * (1 - yd) + i2 * yd; float w2 = j1 * (1 - yd) + j2 * yd; float dens = w1 * (1 - xd) + w2 * xd; return dens; } VolumeRegion* GridVolume::factory(paraMap_t &params,renderEnvironment_t &render) { float ss = .1f; float sa = .1f; float le = .0f; float g = .0f; float min[] = {0, 0, 0}; float max[] = {0, 0, 0}; params.getParam("sigma_s", ss); params.getParam("sigma_a", sa); params.getParam("l_e", le); params.getParam("g", g); params.getParam("minX", min[0]); params.getParam("minY", min[1]); params.getParam("minZ", min[2]); params.getParam("maxX", max[0]); params.getParam("maxY", max[1]); params.getParam("maxZ", max[2]); GridVolume *vol = new GridVolume(color_t(sa), color_t(ss), color_t(le), g, point3d_t(min[0], min[1], min[2]), point3d_t(max[0], max[1], max[2])); return vol; } extern "C" { YAFRAYPLUGIN_EXPORT void registerPlugin(renderEnvironment_t &render) { render.registerFactory("GridVolume", GridVolume::factory); } } __END_YAFRAY
DavidBluecame/Core
src/volumes/GridVolume.cc
C++
gpl-2.0
4,802
/* * $RCSfile: JspFactory.java,v $ * $Revision: 1.1 $ * $Date: 2013-02-19 $ * * Copyright (C) 2008 Skin, Inc. All rights reserved. * * This software is the proprietary information of Skin, Inc. * Use is subject to license terms. */ package com.skin.ayada.runtime; import java.io.Writer; import java.util.Map; import com.skin.ayada.ExpressionContext; import com.skin.ayada.JspWriter; import com.skin.ayada.PageContext; /** * <p>Title: JspFactory</p> * <p>Description: </p> * <p>Copyright: Copyright (c) 2006</p> * @author xuesong.net * @version 1.0 */ public class JspFactory { /** * @param writer * @return PageContext */ public static PageContext getPageContext(Writer writer) { return getPageContext((Map<String, Object>)null, writer, 8192, false); } /** * @param context * @param writer * @return PageContext */ public static PageContext getPageContext(Map<String, Object> context, Writer writer) { return getPageContext(context, writer, 8192, false); } /** * @param context * @param writer * @param buffserSize * @param autoFlush * @return PageContext */ public static PageContext getPageContext(Map<String, Object> context, Writer writer, int buffserSize, boolean autoFlush) { JspWriter out = null; if(writer instanceof JspWriter) { out = (JspWriter)writer; } else { out = new JspWriter(writer, buffserSize, autoFlush); } DefaultPageContext pageContext = new DefaultPageContext(out); ExpressionContext expressionContext = DefaultExpressionFactory.getDefaultExpressionContext(pageContext); pageContext.setTemplateContext(null); pageContext.setExpressionContext(expressionContext); pageContext.setContext(context); return pageContext; } }
xuesong123/jsp-jstl-engine
src/main/java/com/skin/ayada/runtime/JspFactory.java
Java
gpl-2.0
1,893
#!/usr/bin/env python ############################################################################### # $Id: rasterize.py 32165 2015-12-13 19:01:22Z goatbar $ # # Project: GDAL/OGR Test Suite # Purpose: Test RasterizeLayer() and related calls. # Author: Frank Warmerdam <warmerdam@pobox.com> # ############################################################################### # Copyright (c) 2008, Frank Warmerdam <warmerdam@pobox.com> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. ############################################################################### import sys sys.path.append( '../pymod' ) import gdaltest import ogrtest from osgeo import gdal, ogr, osr ############################################################################### # Simple polygon rasterization. def rasterize_1(): # Setup working spatial reference sr_wkt = 'LOCAL_CS["arbitrary"]' sr = osr.SpatialReference( sr_wkt ) # Create a memory raster to rasterize into. target_ds = gdal.GetDriverByName('MEM').Create( '', 100, 100, 3, gdal.GDT_Byte ) target_ds.SetGeoTransform( (1000,1,0,1100,0,-1) ) target_ds.SetProjection( sr_wkt ) # Create a memory layer to rasterize from. rast_ogr_ds = \ ogr.GetDriverByName('Memory').CreateDataSource( 'wrk' ) rast_mem_lyr = rast_ogr_ds.CreateLayer( 'poly', srs=sr ) # Add a polygon. wkt_geom = 'POLYGON((1020 1030,1020 1045,1050 1045,1050 1030,1020 1030))' feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() ) feat.SetGeometryDirectly( ogr.Geometry(wkt = wkt_geom) ) rast_mem_lyr.CreateFeature( feat ) # Add a linestring. wkt_geom = 'LINESTRING(1000 1000, 1100 1050)' feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() ) feat.SetGeometryDirectly( ogr.Geometry(wkt = wkt_geom) ) rast_mem_lyr.CreateFeature( feat ) # Run the algorithm. err = gdal.RasterizeLayer( target_ds, [3,2,1], rast_mem_lyr, burn_values = [200,220,240] ) if err != 0: print(err) gdaltest.post_reason( 'got non-zero result code from RasterizeLayer' ) return 'fail' # Check results. expected = 6452 checksum = target_ds.GetRasterBand(2).Checksum() if checksum != expected: print(checksum) gdaltest.post_reason( 'Did not get expected image checksum' ) gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_1.tif',target_ds) return 'fail' return 'success' ############################################################################### # Test rasterization with ALL_TOUCHED. def rasterize_2(): # Setup working spatial reference sr_wkt = 'LOCAL_CS["arbitrary"]' # Create a memory raster to rasterize into. target_ds = gdal.GetDriverByName('MEM').Create( '', 12, 12, 3, gdal.GDT_Byte ) target_ds.SetGeoTransform( (0,1,0,12,0,-1) ) target_ds.SetProjection( sr_wkt ) # Create a memory layer to rasterize from. cutline_ds = ogr.Open( 'data/cutline.csv' ) # Run the algorithm. gdal.PushErrorHandler( 'CPLQuietErrorHandler' ) err = gdal.RasterizeLayer( target_ds, [3,2,1], cutline_ds.GetLayer(0), burn_values = [200,220,240], options = ["ALL_TOUCHED=TRUE"] ) gdal.PopErrorHandler() if err != 0: print(err) gdaltest.post_reason( 'got non-zero result code from RasterizeLayer' ) return 'fail' # Check results. expected = 121 checksum = target_ds.GetRasterBand(2).Checksum() if checksum != expected: print(checksum) gdaltest.post_reason( 'Did not get expected image checksum' ) gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_2.tif',target_ds) return 'fail' return 'success' ############################################################################### # Rasterization with BURN_VALUE_FROM. def rasterize_3(): # Setup working spatial reference sr_wkt = 'LOCAL_CS["arbitrary"]' sr = osr.SpatialReference( sr_wkt ) # Create a memory raster to rasterize into. target_ds = gdal.GetDriverByName('MEM').Create( '', 100, 100, 3, gdal.GDT_Byte ) target_ds.SetGeoTransform( (1000,1,0,1100,0,-1) ) target_ds.SetProjection( sr_wkt ) # Create a memory layer to rasterize from. rast_ogr_ds = \ ogr.GetDriverByName('Memory').CreateDataSource( 'wrk' ) rast_mem_lyr = rast_ogr_ds.CreateLayer( 'poly', srs=sr ) # Add polygons and linestrings. wkt_geom = ['POLYGON((1020 1030 40,1020 1045 30,1050 1045 20,1050 1030 35,1020 1030 40))', 'POLYGON((1010 1046 85,1015 1055 35,1055 1060 26,1054 1048 35,1010 1046 85))', 'POLYGON((1020 1076 190,1025 1085 35,1065 1090 26,1064 1078 35,1020 1076 190),(1023 1079 5,1061 1081 35,1062 1087 26,1028 1082 35,1023 1079 85))', 'LINESTRING(1005 1000 10, 1100 1050 120)', 'LINESTRING(1000 1000 150, 1095 1050 -5, 1080 1080 200)'] for g in wkt_geom: feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() ) feat.SetGeometryDirectly( ogr.Geometry(wkt = g) ) rast_mem_lyr.CreateFeature( feat ) # Run the algorithm. err = gdal.RasterizeLayer( target_ds, [3,2,1], rast_mem_lyr, burn_values = [10,10,55], options = ["BURN_VALUE_FROM=Z"] ) if err != 0: print(err) gdaltest.post_reason( 'got non-zero result code from RasterizeLayer' ) return 'fail' # Check results. expected = 15006 checksum = target_ds.GetRasterBand(2).Checksum() if checksum != expected: print(checksum) gdaltest.post_reason( 'Did not get expected image checksum' ) gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_3.tif',target_ds) return 'fail' return 'success' ############################################################################### # Rasterization with ATTRIBUTE. def rasterize_4(): # Setup working spatial reference sr_wkt = 'LOCAL_CS["arbitrary"]' sr = osr.SpatialReference( sr_wkt ) # Create a memory raster to rasterize into. target_ds = gdal.GetDriverByName('MEM').Create( '', 100, 100, 3, gdal.GDT_Byte ) target_ds.SetGeoTransform( (1000,1,0,1100,0,-1) ) target_ds.SetProjection( sr_wkt ) # Create a memory layer to rasterize from. rast_ogr_ds = ogr.GetDriverByName('Memory').CreateDataSource( 'wrk' ) rast_mem_lyr = rast_ogr_ds.CreateLayer( 'poly', srs=sr ) # Setup Schema ogrtest.quick_create_layer_def( rast_mem_lyr, [ ('CELSIUS', ogr.OFTReal) ] ) # Add polygons and linestrings and a field named CELSIUS. wkt_geom = ['POLYGON((1020 1030 40,1020 1045 30,1050 1045 20,1050 1030 35,1020 1030 40))', 'POLYGON((1010 1046 85,1015 1055 35,1055 1060 26,1054 1048 35,1010 1046 85))', 'POLYGON((1020 1076 190,1025 1085 35,1065 1090 26,1064 1078 35,1020 1076 190),(1023 1079 5,1061 1081 35,1062 1087 26,1028 1082 35,1023 1079 85))', 'LINESTRING(1005 1000 10, 1100 1050 120)', 'LINESTRING(1000 1000 150, 1095 1050 -5, 1080 1080 200)'] celsius_field_values = [50,255,60,100,180] i = 0 for g in wkt_geom: feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() ) feat.SetGeometryDirectly( ogr.Geometry(wkt = g) ) feat.SetField( 'CELSIUS', celsius_field_values[i] ) rast_mem_lyr.CreateFeature( feat ) i = i + 1 # Run the algorithm. err = gdal.RasterizeLayer( target_ds, [1,2,3], rast_mem_lyr, options = ["ATTRIBUTE=CELSIUS"] ) if err != 0: print(err) gdaltest.post_reason( 'got non-zero result code from RasterizeLayer' ) return 'fail' # Check results. expected = 16265 checksum = target_ds.GetRasterBand(2).Checksum() if checksum != expected: print(checksum) gdaltest.post_reason( 'Did not get expected image checksum' ) gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_4.tif',target_ds) return 'fail' return 'success' ############################################################################### # Rasterization with MERGE_ALG=ADD. def rasterize_5(): # Setup working spatial reference sr_wkt = 'LOCAL_CS["arbitrary"]' sr = osr.SpatialReference( sr_wkt ) # Create a memory raster to rasterize into. target_ds = gdal.GetDriverByName('MEM').Create( '', 100, 100, 3, gdal.GDT_Byte ) target_ds.SetGeoTransform( (1000,1,0,1100,0,-1) ) target_ds.SetProjection( sr_wkt ) # Create a memory layer to rasterize from. rast_ogr_ds = \ ogr.GetDriverByName('Memory').CreateDataSource( 'wrk' ) rast_mem_lyr = rast_ogr_ds.CreateLayer( 'poly', srs=sr ) # Add polygons. wkt_geom = 'POLYGON((1020 1030,1020 1045,1050 1045,1050 1030,1020 1030))' feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() ) feat.SetGeometryDirectly( ogr.Geometry(wkt = wkt_geom) ) rast_mem_lyr.CreateFeature( feat ) wkt_geom = 'POLYGON((1045 1050,1055 1050,1055 1020,1045 1020,1045 1050))' feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() ) feat.SetGeometryDirectly( ogr.Geometry(wkt = wkt_geom) ) rast_mem_lyr.CreateFeature( feat ) # Add linestrings. wkt_geom = 'LINESTRING(1000 1000, 1100 1050)' feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() ) feat.SetGeometryDirectly( ogr.Geometry(wkt = wkt_geom) ) rast_mem_lyr.CreateFeature( feat ) wkt_geom = 'LINESTRING(1005 1000, 1000 1050)' feat = ogr.Feature( rast_mem_lyr.GetLayerDefn() ) feat.SetGeometryDirectly( ogr.Geometry(wkt = wkt_geom) ) rast_mem_lyr.CreateFeature( feat ) # Run the algorithm. err = gdal.RasterizeLayer( target_ds, [1, 2, 3], rast_mem_lyr, burn_values = [100,110,120], options = ["MERGE_ALG=ADD"]) if err != 0: print(err) gdaltest.post_reason( 'got non-zero result code from RasterizeLayer' ) return 'fail' # Check results. expected = 13022 checksum = target_ds.GetRasterBand(2).Checksum() if checksum != expected: print(checksum) gdaltest.post_reason( 'Did not get expected image checksum' ) gdal.GetDriverByName('GTiff').CreateCopy('tmp/rasterize_5.tif',target_ds) return 'fail' return 'success' gdaltest_list = [ rasterize_1, rasterize_2, rasterize_3, rasterize_4, rasterize_5, ] if __name__ == '__main__': gdaltest.setup_run( 'rasterize' ) gdaltest.run_tests( gdaltest_list ) gdaltest.summarize()
nextgis-extra/tests
lib_gdal/alg/rasterize.py
Python
gpl-2.0
11,966
/* Copyright (c) 2000, 2016, Oracle and/or its affiliates. Copyright (c) 2012, 2020, MariaDB Corporation. 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, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file This file is the net layer API for the MySQL client/server protocol. Write and read of logical packets to/from socket. Writes are cached into net_buffer_length big packets. Read packets are reallocated dynamicly when reading big packets. Each logical packet has the following pre-info: 3 byte length & 1 byte package-number. This file needs to be written in C as it's used by the libmysql client as a C file. */ /* HFTODO this must be hidden if we don't want client capabilities in embedded library */ #include "mariadb.h" #include <mysql.h> #include <mysql_com.h> #include <mysqld_error.h> #include <my_sys.h> #include <m_string.h> #include <my_net.h> #include <violite.h> #include <signal.h> #include "probes_mysql.h" #include <debug_sync.h> #include "proxy_protocol.h" PSI_memory_key key_memory_NET_buff; PSI_memory_key key_memory_NET_compress_packet; #ifdef EMBEDDED_LIBRARY #undef MYSQL_SERVER #undef MYSQL_CLIENT #define MYSQL_CLIENT #endif /*EMBEDDED_LIBRARY */ /* to reduce the number of ifdef's in the code */ #ifdef EXTRA_DEBUG #define EXTRA_DEBUG_fprintf fprintf #define EXTRA_DEBUG_fflush fflush #define EXTRA_DEBUG_ASSERT DBUG_ASSERT #else static void inline EXTRA_DEBUG_fprintf(...) {} #ifndef MYSQL_SERVER static int inline EXTRA_DEBUG_fflush(...) { return 0; } #endif #endif /* EXTRA_DEBUG */ #ifdef MYSQL_SERVER #include <sql_class.h> #include <sql_connect.h> #define MYSQL_SERVER_my_error my_error #else static void inline MYSQL_SERVER_my_error(...) {} #endif #ifndef EXTRA_DEBUG_ASSERT # define EXTRA_DEBUG_ASSERT(X) do {} while(0) #endif /* The following handles the differences when this is linked between the client and the server. This gives an error if a too big packet is found. The server can change this, but because the client can't normally do this the client should have a bigger max_allowed_packet. */ #if defined(_WIN32) || !defined(MYSQL_SERVER) /* The following is because alarms doesn't work on windows. */ #ifndef NO_ALARM #define NO_ALARM #endif #endif #ifndef NO_ALARM #include "my_pthread.h" void sql_print_error(const char *format,...); #else #define DONT_USE_THR_ALARM #endif /* NO_ALARM */ #include "thr_alarm.h" #ifdef MYSQL_SERVER /* The following variables/functions should really not be declared extern, but as it's hard to include sql_priv.h here, we have to live with this for a while. */ extern ulonglong test_flags; extern ulong bytes_sent, bytes_received, net_big_packet_count; #ifdef HAVE_QUERY_CACHE #define USE_QUERY_CACHE extern void query_cache_insert(void *thd, const char *packet, size_t length, unsigned pkt_nr); #endif // HAVE_QUERY_CACHE #define update_statistics(A) A extern my_bool thd_net_is_killed(THD *thd); /* Additional instrumentation hooks for the server */ #include "mysql_com_server.h" #else #define update_statistics(A) #define thd_net_is_killed(A) 0 #endif static my_bool net_write_buff(NET *, const uchar *, size_t len); my_bool net_allocate_new_packet(NET *net, void *thd, uint my_flags); /** Init with packet info. */ my_bool my_net_init(NET *net, Vio *vio, void *thd, uint my_flags) { DBUG_ENTER("my_net_init"); DBUG_PRINT("enter", ("my_flags: %u", my_flags)); net->vio = vio; net->read_timeout= 0; net->write_timeout= 0; my_net_local_init(net); /* Set some limits */ if (net_allocate_new_packet(net, thd, my_flags)) DBUG_RETURN(1); net->error=0; net->return_status=0; net->pkt_nr=net->compress_pkt_nr=0; net->last_error[0]=0; net->compress=0; net->reading_or_writing=0; net->where_b = net->remain_in_buf=0; net->net_skip_rest_factor= 0; net->last_errno=0; net->thread_specific_malloc= MY_TEST(my_flags & MY_THREAD_SPECIFIC); net->thd= 0; #ifdef MYSQL_SERVER net->extension= NULL; net->thd= thd; #endif if (vio) { /* For perl DBI/DBD. */ net->fd= vio_fd(vio); #if defined(MYSQL_SERVER) && !defined(_WIN32) if (!(test_flags & TEST_BLOCKING)) { my_bool old_mode; vio_blocking(vio, FALSE, &old_mode); } #endif vio_fastsend(vio); } DBUG_RETURN(0); } /** Allocate and assign new net buffer @note In case of error the old buffer left @retval TRUE error @retval FALSE success */ my_bool net_allocate_new_packet(NET *net, void *thd, uint my_flags) { uchar *tmp; DBUG_ENTER("net_allocate_new_packet"); if (!(tmp= (uchar*) my_malloc(key_memory_NET_buff, (size_t) net->max_packet + NET_HEADER_SIZE + COMP_HEADER_SIZE + 1, MYF(MY_WME | my_flags)))) DBUG_RETURN(1); net->buff= tmp; net->buff_end=net->buff+net->max_packet; net->write_pos=net->read_pos = net->buff; DBUG_RETURN(0); } void net_end(NET *net) { DBUG_ENTER("net_end"); my_free(net->buff); net->buff=0; DBUG_VOID_RETURN; } /** Realloc the packet buffer. */ my_bool net_realloc(NET *net, size_t length) { uchar *buff; size_t pkt_length; DBUG_ENTER("net_realloc"); DBUG_PRINT("enter",("length: %lu", (ulong) length)); if (length >= net->max_packet_size) { DBUG_PRINT("error", ("Packet too large. Max size: %lu", net->max_packet_size)); /* @todo: 1 and 2 codes are identical. */ net->error= 1; net->last_errno= ER_NET_PACKET_TOO_LARGE; MYSQL_SERVER_my_error(ER_NET_PACKET_TOO_LARGE, MYF(0)); DBUG_RETURN(1); } pkt_length = (length+IO_SIZE-1) & ~(IO_SIZE-1); /* We must allocate some extra bytes for the end 0 and to be able to read big compressed blocks + 1 safety byte since uint3korr() in my_real_read() may actually read 4 bytes depending on build flags and platform. */ if (!(buff= (uchar*) my_realloc(key_memory_NET_buff, (char*) net->buff, pkt_length + NET_HEADER_SIZE + COMP_HEADER_SIZE + 1, MYF(MY_WME | (net->thread_specific_malloc ? MY_THREAD_SPECIFIC : 0))))) { /* @todo: 1 and 2 codes are identical. */ net->error= 1; net->last_errno= ER_OUT_OF_RESOURCES; /* In the server the error is reported by MY_WME flag. */ DBUG_RETURN(1); } net->buff=net->write_pos=buff; net->buff_end=buff+(net->max_packet= (ulong) pkt_length); DBUG_RETURN(0); } /** Check if there is any data to be read from the socket. @param sd socket descriptor @retval 0 No data to read @retval 1 Data or EOF to read @retval -1 Don't know if data is ready or not */ #if !defined(EMBEDDED_LIBRARY) && defined(DBUG_OFF) static int net_data_is_ready(my_socket sd) { #ifdef HAVE_POLL struct pollfd ufds; int res; ufds.fd= sd; ufds.events= POLLIN | POLLPRI; if (!(res= poll(&ufds, 1, 0))) return 0; if (res < 0 || !(ufds.revents & (POLLIN | POLLPRI))) return 0; return 1; #else fd_set sfds; struct timeval tv; int res; #ifndef _WIN32 /* Windows uses an _array_ of 64 fd's as default, so it's safe */ if (sd >= FD_SETSIZE) return -1; #define NET_DATA_IS_READY_CAN_RETURN_MINUS_ONE #endif FD_ZERO(&sfds); FD_SET(sd, &sfds); tv.tv_sec= tv.tv_usec= 0; if ((res= select((int) (sd + 1), &sfds, NULL, NULL, &tv)) < 0) return 0; else return MY_TEST(res ? FD_ISSET(sd, &sfds) : 0); #endif /* HAVE_POLL */ } #endif /* EMBEDDED_LIBRARY */ /** Clear (reinitialize) the NET structure for a new command. @remark Performs debug checking of the socket buffer to ensure that the protocol sequence is correct. - Read from socket until there is nothing more to read. Discard what is read. - Initialize net for new net_read/net_write calls. If there is anything when to read 'net_clear' is called this normally indicates an error in the protocol. Normally one should not need to do clear the communication buffer. If one compiles without -DUSE_NET_CLEAR then one wins one read call / query. When connection is properly closed (for TCP it means with a FIN packet), then select() considers a socket "ready to read", in the sense that there's EOF to read, but read() returns 0. @param net NET handler @param clear_buffer if <> 0, then clear all data from comm buff */ void net_clear(NET *net, my_bool clear_buffer __attribute__((unused))) { DBUG_ENTER("net_clear"); /* We don't do a clear in case of not DBUG_OFF to catch bugs in the protocol handling. */ #if (!defined(EMBEDDED_LIBRARY) && defined(DBUG_OFF)) || defined(USE_NET_CLEAR) if (clear_buffer) { size_t count; int ready; while ((ready= net_data_is_ready(vio_fd(net->vio))) > 0) { /* The socket is ready */ if ((long) (count= vio_read(net->vio, net->buff, (size_t) net->max_packet)) > 0) { DBUG_PRINT("info",("skipped %ld bytes from file: %s", (long) count, vio_description(net->vio))); EXTRA_DEBUG_fprintf(stderr,"Note: net_clear() skipped %ld bytes from file: %s\n", (long) count, vio_description(net->vio)); } else { DBUG_PRINT("info",("socket ready but only EOF to read - disconnected")); net->error= 2; break; } } #ifdef NET_DATA_IS_READY_CAN_RETURN_MINUS_ONE /* 'net_data_is_ready' returned "don't know" */ if (ready == -1) { /* Read unblocking to clear net */ my_bool old_mode; if (!vio_blocking(net->vio, FALSE, &old_mode)) { while ((long) (count= vio_read(net->vio, net->buff, (size_t) net->max_packet)) > 0) DBUG_PRINT("info",("skipped %ld bytes from file: %s", (long) count, vio_description(net->vio))); vio_blocking(net->vio, TRUE, &old_mode); } } #endif /* NET_DATA_IS_READY_CAN_RETURN_MINUS_ONE */ } #endif /* EMBEDDED_LIBRARY */ net->pkt_nr=net->compress_pkt_nr=0; /* Ready for new command */ net->write_pos=net->buff; DBUG_VOID_RETURN; } /** Flush write_buffer if not empty. */ my_bool net_flush(NET *net) { my_bool error= 0; DBUG_ENTER("net_flush"); if (net->buff != net->write_pos) { error= MY_TEST(net_real_write(net, net->buff, (size_t) (net->write_pos - net->buff))); net->write_pos= net->buff; } /* Sync packet number if using compression */ if (net->compress) net->pkt_nr=net->compress_pkt_nr; DBUG_RETURN(error); } /***************************************************************************** ** Write something to server/client buffer *****************************************************************************/ /** Write a logical packet with packet header. Format: Packet length (3 bytes), packet number (1 byte) When compression is used, a 3 byte compression length is added. @note If compression is used, the original packet is modified! */ my_bool my_net_write(NET *net, const uchar *packet, size_t len) { uchar buff[NET_HEADER_SIZE]; if (unlikely(!net->vio)) /* nowhere to write */ return 0; MYSQL_NET_WRITE_START(len); /* Big packets are handled by splitting them in packets of MAX_PACKET_LENGTH length. The last packet is always a packet that is < MAX_PACKET_LENGTH. (The last packet may even have a length of 0) */ while (len >= MAX_PACKET_LENGTH) { const ulong z_size = MAX_PACKET_LENGTH; int3store(buff, z_size); buff[3]= (uchar) net->pkt_nr++; if (net_write_buff(net, buff, NET_HEADER_SIZE) || net_write_buff(net, packet, z_size)) { MYSQL_NET_WRITE_DONE(1); return 1; } packet += z_size; len-= z_size; } /* Write last packet */ int3store(buff,len); buff[3]= (uchar) net->pkt_nr++; if (net_write_buff(net, buff, NET_HEADER_SIZE)) { MYSQL_NET_WRITE_DONE(1); return 1; } #ifndef DEBUG_DATA_PACKETS DBUG_DUMP("packet_header", buff, NET_HEADER_SIZE); #endif my_bool rc= MY_TEST(net_write_buff(net, packet, len)); MYSQL_NET_WRITE_DONE(rc); return rc; } /** Send a command to the server. The reason for having both header and packet is so that libmysql can easy add a header to a special command (like prepared statements) without having to re-alloc the string. As the command is part of the first data packet, we have to do some data juggling to put the command in there, without having to create a new packet. This function will split big packets into sub-packets if needed. (Each sub packet can only be 2^24 bytes) @param net NET handler @param command Command in MySQL server (enum enum_server_command) @param header Header to write after command @param head_len Length of header @param packet Query or parameter to query @param len Length of packet @retval 0 ok @retval 1 error */ my_bool net_write_command(NET *net,uchar command, const uchar *header, size_t head_len, const uchar *packet, size_t len) { size_t length=len+1+head_len; /* 1 extra byte for command */ uchar buff[NET_HEADER_SIZE+1]; uint header_size=NET_HEADER_SIZE+1; my_bool rc; DBUG_ENTER("net_write_command"); DBUG_PRINT("enter",("length: %lu", (ulong) len)); DBUG_EXECUTE_IF("simulate_error_on_packet_write", { if (command == COM_BINLOG_DUMP) { net->last_errno = ER_NET_ERROR_ON_WRITE; DBUG_ASSERT(!debug_sync_set_action( (THD *)net->thd, STRING_WITH_LEN("now SIGNAL parked WAIT_FOR continue"))); DBUG_RETURN(true); } };); MYSQL_NET_WRITE_START(length); buff[4]=command; /* For first packet */ if (length >= MAX_PACKET_LENGTH) { /* Take into account that we have the command in the first header */ len= MAX_PACKET_LENGTH - 1 - head_len; do { int3store(buff, MAX_PACKET_LENGTH); buff[3]= (uchar) net->pkt_nr++; if (net_write_buff(net, buff, header_size) || net_write_buff(net, header, head_len) || net_write_buff(net, packet, len)) { MYSQL_NET_WRITE_DONE(1); DBUG_RETURN(1); } packet+= len; length-= MAX_PACKET_LENGTH; len= MAX_PACKET_LENGTH; head_len= 0; header_size= NET_HEADER_SIZE; } while (length >= MAX_PACKET_LENGTH); len=length; /* Data left to be written */ } int3store(buff,length); buff[3]= (uchar) net->pkt_nr++; rc= MY_TEST(net_write_buff(net, buff, header_size) || (head_len && net_write_buff(net, header, head_len)) || net_write_buff(net, packet, len) || net_flush(net)); MYSQL_NET_WRITE_DONE(rc); DBUG_RETURN(rc); } /** Caching the data in a local buffer before sending it. Fill up net->buffer and send it to the client when full. If the rest of the to-be-sent-packet is bigger than buffer, send it in one big block (to avoid copying to internal buffer). If not, copy the rest of the data to the buffer and return without sending data. @param net Network handler @param packet Packet to send @param len Length of packet @note The cached buffer can be sent as it is with 'net_flush()'. In this code we have to be careful to not send a packet longer than MAX_PACKET_LENGTH to net_real_write() if we are using the compressed protocol as we store the length of the compressed packet in 3 bytes. @retval 0 ok @retval 1 */ static my_bool net_write_buff(NET *net, const uchar *packet, size_t len) { size_t left_length; if (net->compress && net->max_packet > MAX_PACKET_LENGTH) left_length= (MAX_PACKET_LENGTH - (net->write_pos - net->buff)); else left_length= (net->buff_end - net->write_pos); #ifdef DEBUG_DATA_PACKETS DBUG_DUMP("data_written", packet, len); #endif if (len > left_length) { if (net->write_pos != net->buff) { /* Fill up already used packet and write it */ memcpy((char*) net->write_pos,packet,left_length); if (net_real_write(net, net->buff, (size_t) (net->write_pos - net->buff) + left_length)) return 1; net->write_pos= net->buff; packet+= left_length; len-= left_length; } if (net->compress) { /* We can't have bigger packets than 16M with compression Because the uncompressed length is stored in 3 bytes */ left_length= MAX_PACKET_LENGTH; while (len > left_length) { if (net_real_write(net, packet, left_length)) return 1; packet+= left_length; len-= left_length; } } if (len > net->max_packet) return net_real_write(net, packet, len) ? 1 : 0; /* Send out rest of the blocks as full sized blocks */ } if (len) memcpy((char*) net->write_pos,packet,len); net->write_pos+= len; return 0; } /** Read and write one packet using timeouts. If needed, the packet is compressed before sending. @todo - TODO is it needed to set this variable if we have no socket */ int net_real_write(NET *net,const uchar *packet, size_t len) { size_t length; const uchar *pos,*end; thr_alarm_t alarmed; #ifndef NO_ALARM ALARM alarm_buff; #endif uint retry_count=0; my_bool net_blocking = vio_is_blocking(net->vio); DBUG_ENTER("net_real_write"); #if defined(MYSQL_SERVER) THD *thd= (THD *)net->thd; #if defined(USE_QUERY_CACHE) query_cache_insert(thd, (char*) packet, len, net->pkt_nr); #endif if (likely(thd)) { /* Wait until pending operations (currently it is engine asynchronous group commit) are finished before replying to the client, to keep durability promise. */ thd->async_state.wait_for_pending_ops(); } #endif if (unlikely(net->error == 2)) DBUG_RETURN(-1); /* socket can't be used */ net->reading_or_writing=2; #ifdef HAVE_COMPRESS if (net->compress) { size_t complen; uchar *b; uint header_length=NET_HEADER_SIZE+COMP_HEADER_SIZE; if (!(b= (uchar*) my_malloc(key_memory_NET_compress_packet, len + NET_HEADER_SIZE + COMP_HEADER_SIZE + 1, MYF(MY_WME | (net->thread_specific_malloc ? MY_THREAD_SPECIFIC : 0))))) { net->error= 2; net->last_errno= ER_OUT_OF_RESOURCES; /* In the server, the error is reported by MY_WME flag. */ net->reading_or_writing= 0; DBUG_RETURN(1); } memcpy(b+header_length,packet,len); /* Don't compress error packets (compress == 2) */ if (net->compress == 2 || my_compress(b+header_length, &len, &complen)) complen=0; int3store(&b[NET_HEADER_SIZE],complen); int3store(b,len); b[3]=(uchar) (net->compress_pkt_nr++); len+= header_length; packet= b; } #endif /* HAVE_COMPRESS */ #ifdef DEBUG_DATA_PACKETS DBUG_DUMP("data_written", packet, len); #endif #ifndef NO_ALARM thr_alarm_init(&alarmed); if (net_blocking) thr_alarm(&alarmed, net->write_timeout, &alarm_buff); #else alarmed=0; /* Write timeout is set in my_net_set_write_timeout */ #endif /* NO_ALARM */ pos= packet; end=pos+len; while (pos != end) { if ((long) (length= vio_write(net->vio,pos,(size_t) (end-pos))) <= 0) { my_bool interrupted = vio_should_retry(net->vio); #if !defined(_WIN32) if ((interrupted || length == 0) && !thr_alarm_in_use(&alarmed)) { if (!thr_alarm(&alarmed, net->write_timeout, &alarm_buff)) { /* Always true for client */ my_bool old_mode; while (vio_blocking(net->vio, TRUE, &old_mode) < 0) { if (vio_should_retry(net->vio) && retry_count++ < net->retry_count) continue; EXTRA_DEBUG_fprintf(stderr, "%s: my_net_write: fcntl returned error %d, aborting thread\n", my_progname,vio_errno(net->vio)); net->error= 2; /* Close socket */ net->last_errno= ER_NET_PACKET_TOO_LARGE; MYSQL_SERVER_my_error(ER_NET_PACKET_TOO_LARGE, MYF(0)); goto end; } retry_count=0; continue; } } else #endif /* !defined(_WIN32) */ if (thr_alarm_in_use(&alarmed) && !thr_got_alarm(&alarmed) && interrupted) { if (retry_count++ < net->retry_count) continue; EXTRA_DEBUG_fprintf(stderr, "%s: write looped, aborting thread\n", my_progname); } #ifndef MYSQL_SERVER if (vio_errno(net->vio) == SOCKET_EINTR) { DBUG_PRINT("warning",("Interrupted write. Retrying...")); continue; } #endif /* !defined(MYSQL_SERVER) */ net->error= 2; /* Close socket */ net->last_errno= (interrupted ? ER_NET_WRITE_INTERRUPTED : ER_NET_ERROR_ON_WRITE); MYSQL_SERVER_my_error(net->last_errno, MYF(0)); break; } pos+=length; update_statistics(thd_increment_bytes_sent(net->thd, length)); } #ifndef _WIN32 end: #endif #ifdef HAVE_COMPRESS if (net->compress) my_free((void*) packet); #endif if (thr_alarm_in_use(&alarmed)) { my_bool old_mode; thr_end_alarm(&alarmed); if (!net_blocking) vio_blocking(net->vio, net_blocking, &old_mode); } net->reading_or_writing=0; DBUG_RETURN(((int) (pos != end))); } /***************************************************************************** ** Read something from server/clinet *****************************************************************************/ #ifndef NO_ALARM static my_bool net_safe_read(NET *net, uchar *buff, size_t length, thr_alarm_t *alarmed) { uint retry_count=0; while (length > 0) { size_t tmp; if ((long) (tmp= vio_read(net->vio, buff, length)) <= 0) { my_bool interrupted = vio_should_retry(net->vio); if (!thr_got_alarm(alarmed) && interrupted) { /* Probably in MIT threads */ if (retry_count++ < net->retry_count) continue; } return 1; } length-= tmp; buff+= tmp; } return 0; } /** Help function to clear the commuication buffer when we get a too big packet. @param net Communication handle @param remain Bytes to read @param alarmed Parameter for thr_alarm() @param alarm_buff Parameter for thr_alarm() @retval 0 Was able to read the whole packet @retval 1 Got mailformed packet from client */ static my_bool my_net_skip_rest(NET *net, uint32 remain, thr_alarm_t *alarmed, ALARM *alarm_buff) { longlong limit= net->max_packet_size*net->net_skip_rest_factor; uint32 old=remain; DBUG_ENTER("my_net_skip_rest"); DBUG_PRINT("enter",("bytes_to_skip: %u", (uint) remain)); /* The following is good for debugging */ update_statistics(thd_increment_net_big_packet_count(net->thd, 1)); if (!thr_alarm_in_use(alarmed)) { my_bool old_mode; if (thr_alarm(alarmed,net->read_timeout, alarm_buff) || vio_blocking(net->vio, TRUE, &old_mode) < 0) DBUG_RETURN(1); /* Can't setup, abort */ } for (;;) { while (remain > 0) { size_t length= MY_MIN(remain, net->max_packet); if (net_safe_read(net, net->buff, length, alarmed)) DBUG_RETURN(1); update_statistics(thd_increment_bytes_received(net->thd, length)); remain -= (uint32) length; limit-= length; if (limit < 0) DBUG_RETURN(1); } if (old != MAX_PACKET_LENGTH) break; if (net_safe_read(net, net->buff, NET_HEADER_SIZE, alarmed)) DBUG_RETURN(1); limit-= NET_HEADER_SIZE; old=remain= uint3korr(net->buff); net->pkt_nr++; } DBUG_RETURN(0); } #endif /* NO_ALARM */ /** Try to parse and process proxy protocol header. This function is called in case MySQL packet header cannot be parsed. It checks if proxy header was sent, and that it was send from allowed remote host, as defined by proxy-protocol-networks parameter. If proxy header is parsed, then THD and ACL structures and changed to indicate the new peer address and port. Note, that proxy header can only be sent either when the connection is established, or as the client reply packet to */ #undef IGNORE /* for Windows */ typedef enum { RETRY, ABORT, IGNORE} handle_proxy_header_result; static handle_proxy_header_result handle_proxy_header(NET *net) { #if !defined(MYSQL_SERVER) || defined(EMBEDDED_LIBRARY) return IGNORE; #else THD *thd= (THD *)net->thd; if (!has_proxy_protocol_header(net) || !thd || thd->get_command() != COM_CONNECT) return IGNORE; /* Proxy information found in the first 4 bytes received so far. Read and parse proxy header , change peer ip address and port in THD. */ proxy_peer_info peer_info; if (!thd->net.vio) { DBUG_ASSERT(0); return ABORT; } if (!is_proxy_protocol_allowed((sockaddr *)&(thd->net.vio->remote))) { /* proxy-protocol-networks variable needs to be set to allow this remote address */ my_printf_error(ER_HOST_NOT_PRIVILEGED, "Proxy header is not accepted from %s", MYF(0), thd->main_security_ctx.ip); return ABORT; } if (parse_proxy_protocol_header(net, &peer_info)) { /* Failed to parse proxy header*/ my_printf_error(ER_UNKNOWN_ERROR, "Failed to parse proxy header", MYF(0)); return ABORT; } if (peer_info.is_local_command) /* proxy header indicates LOCAL connection, no action necessary */ return RETRY; /* Change peer address in THD and ACL structures.*/ uint host_errors; return (handle_proxy_header_result)thd_set_peer_addr(thd, &(peer_info.peer_addr), NULL, peer_info.port, false, &host_errors); #endif } /** Reads one packet to net->buff + net->where_b. Long packets are handled by my_net_read(). This function reallocates the net->buff buffer if necessary. @return Returns length of packet. */ static ulong my_real_read(NET *net, size_t *complen, my_bool header __attribute__((unused))) { uchar *pos; size_t length; uint i,retry_count=0; ulong len=packet_error; my_bool expect_error_packet __attribute__((unused))= 0; thr_alarm_t alarmed; #ifndef NO_ALARM ALARM alarm_buff; #endif retry: my_bool net_blocking=vio_is_blocking(net->vio); uint32 remain= (net->compress ? NET_HEADER_SIZE+COMP_HEADER_SIZE : NET_HEADER_SIZE); #ifdef MYSQL_SERVER size_t count= remain; struct st_net_server *server_extension= 0; if (header) { server_extension= static_cast<st_net_server*> (net->extension); if (server_extension != NULL) { void *user_data= server_extension->m_user_data; server_extension->m_before_header(net, user_data, count); } } #endif *complen = 0; net->reading_or_writing=1; thr_alarm_init(&alarmed); #ifndef NO_ALARM if (net_blocking) thr_alarm(&alarmed,net->read_timeout,&alarm_buff); #else /* Read timeout is set in my_net_set_read_timeout */ #endif /* NO_ALARM */ pos = net->buff + net->where_b; /* net->packet -4 */ for (i=0 ; i < 2 ; i++) { while (remain > 0) { /* First read is done with non blocking mode */ if ((long) (length= vio_read(net->vio, pos, remain)) <= 0L) { my_bool interrupted = vio_should_retry(net->vio); DBUG_PRINT("info",("vio_read returned %ld errno: %d", (long) length, vio_errno(net->vio))); if (i== 0 && unlikely(thd_net_is_killed((THD*) net->thd))) { DBUG_PRINT("info", ("thd is killed")); len= packet_error; net->error= 0; net->last_errno= ER_CONNECTION_KILLED; MYSQL_SERVER_my_error(net->last_errno, MYF(0)); goto end; } #if !defined(_WIN32) && defined(MYSQL_SERVER) /* We got an error that there was no data on the socket. We now set up an alarm to not 'read forever', change the socket to the blocking mode and try again */ if ((interrupted || length == 0) && !thr_alarm_in_use(&alarmed)) { if (!thr_alarm(&alarmed,net->read_timeout,&alarm_buff)) /* Don't wait too long */ { my_bool old_mode; while (vio_blocking(net->vio, TRUE, &old_mode) < 0) { if (vio_should_retry(net->vio) && retry_count++ < net->retry_count) continue; DBUG_PRINT("error", ("fcntl returned error %d, aborting thread", vio_errno(net->vio))); EXTRA_DEBUG_fprintf(stderr, "%s: read: fcntl returned error %d, aborting thread\n", my_progname,vio_errno(net->vio)); len= packet_error; net->error= 2; /* Close socket */ net->last_errno= ER_NET_FCNTL_ERROR; MYSQL_SERVER_my_error(ER_NET_FCNTL_ERROR, MYF(0)); goto end; } retry_count=0; continue; } } #endif /* (!defined(_WIN32) && defined(MYSQL_SERVER) */ if (thr_alarm_in_use(&alarmed) && !thr_got_alarm(&alarmed) && interrupted) { /* Probably in MIT threads */ if (retry_count++ < net->retry_count) continue; EXTRA_DEBUG_fprintf(stderr, "%s: read looped with error %d, aborting thread\n", my_progname,vio_errno(net->vio)); } #ifndef MYSQL_SERVER if (length != 0 && vio_errno(net->vio) == SOCKET_EINTR) { DBUG_PRINT("warning",("Interrupted read. Retrying...")); continue; } #endif DBUG_PRINT("error",("Couldn't read packet: remain: %u errno: %d length: %ld", remain, vio_errno(net->vio), (long) length)); len= packet_error; net->error= 2; /* Close socket */ net->last_errno= (vio_was_timeout(net->vio) ? ER_NET_READ_INTERRUPTED : ER_NET_READ_ERROR); MYSQL_SERVER_my_error(net->last_errno, MYF(0)); goto end; } remain -= (uint32) length; pos+= length; update_statistics(thd_increment_bytes_received(net->thd, length)); } #ifdef DEBUG_DATA_PACKETS DBUG_DUMP("data_read", net->buff+net->where_b, length); #endif if (i == 0) { /* First parts is packet length */ size_t helping; #ifndef DEBUG_DATA_PACKETS DBUG_DUMP("packet_header", net->buff+net->where_b, NET_HEADER_SIZE); #endif if (net->buff[net->where_b + 3] != (uchar) net->pkt_nr) { #ifndef MYSQL_SERVER if (net->buff[net->where_b + 3] == (uchar) (net->pkt_nr -1)) { /* If the server was killed then the server may have missed the last sent client packet and the packet numbering may be one off. */ DBUG_PRINT("warning", ("Found possible out of order packets")); expect_error_packet= 1; } else #endif goto packets_out_of_order; } net->compress_pkt_nr= ++net->pkt_nr; #ifdef HAVE_COMPRESS if (net->compress) { /* The following uint3korr() may read 4 bytes, so make sure we don't read unallocated or uninitialized memory. The right-hand expression must match the size of the buffer allocated in net_realloc(). */ DBUG_ASSERT(net->where_b + NET_HEADER_SIZE + sizeof(uint32) <= net->max_packet + NET_HEADER_SIZE + COMP_HEADER_SIZE + 1); /* If the packet is compressed then complen > 0 and contains the number of bytes in the uncompressed packet */ *complen=uint3korr(&(net->buff[net->where_b + NET_HEADER_SIZE])); } #endif len=uint3korr(net->buff+net->where_b); if (!len) /* End of big multi-packet */ goto end; helping = MY_MAX(len,*complen) + net->where_b; /* The necessary size of net->buff */ if (helping >= net->max_packet) { if (net_realloc(net,helping)) { #if defined(MYSQL_SERVER) && !defined(NO_ALARM) if (!net->compress && !my_net_skip_rest(net, (uint32) len, &alarmed, &alarm_buff)) net->error= 3; /* Successfully skiped packet */ #endif len= packet_error; /* Return error and close connection */ goto end; } } pos=net->buff + net->where_b; remain = (uint32) len; #ifdef MYSQL_SERVER if (server_extension != NULL) { void *user_data= server_extension->m_user_data; server_extension->m_after_header(net, user_data, count, 0); server_extension= NULL; } #endif } #ifndef MYSQL_SERVER else if (expect_error_packet) { /* This check is safe both for compressed and not compressed protocol as for the compressed protocol errors are not compressed anymore. */ if (net->buff[net->where_b] != (uchar) 255) { /* Restore pkt_nr to original value */ net->pkt_nr--; goto packets_out_of_order; } } #endif } end: if (thr_alarm_in_use(&alarmed)) { my_bool old_mode; thr_end_alarm(&alarmed); if (!net_blocking) vio_blocking(net->vio, net_blocking, &old_mode); } net->reading_or_writing=0; #ifdef DEBUG_DATA_PACKETS if (len != packet_error) DBUG_DUMP("data_read", net->buff+net->where_b, len); #endif #ifdef MYSQL_SERVER if (server_extension != NULL) { void *user_data= server_extension->m_user_data; server_extension->m_after_header(net, user_data, count, 1); DBUG_ASSERT(len == packet_error || len == 0); } #endif return(len); packets_out_of_order: { switch (handle_proxy_header(net)) { case ABORT: /* error happened, message is already written. */ len= packet_error; goto end; case RETRY: goto retry; case IGNORE: break; } DBUG_PRINT("error", ("Packets out of order (Found: %d, expected %u)", (int) net->buff[net->where_b + 3], net->pkt_nr)); EXTRA_DEBUG_ASSERT(0); /* We don't make noise server side, since the client is expected to break the protocol for e.g. --send LOAD DATA .. LOCAL where the server expects the client to send a file, but the client may reply with a new command instead. */ #ifndef MYSQL_SERVER EXTRA_DEBUG_fflush(stdout); EXTRA_DEBUG_fprintf(stderr,"Error: Packets out of order (Found: %d, expected %d)\n", (int) net->buff[net->where_b + 3], (uint) (uchar) net->pkt_nr); EXTRA_DEBUG_fflush(stderr); #endif len= packet_error; MYSQL_SERVER_my_error(ER_NET_PACKETS_OUT_OF_ORDER, MYF(0)); goto end; } } /* Old interface. See my_net_read_packet() for function description */ #undef my_net_read ulong my_net_read(NET *net) { return my_net_read_packet(net, 0); } /** Read a packet from the client/server and return it without the internal package header. If the packet is the first packet of a multi-packet packet (which is indicated by the length of the packet = 0xffffff) then all sub packets are read and concatenated. If the packet was compressed, its uncompressed and the length of the uncompressed packet is returned. read_from_server is set when the server is reading a new command from the client. @return The function returns the length of the found packet or packet_error. net->read_pos points to the read data. */ ulong my_net_read_packet(NET *net, my_bool read_from_server) { ulong reallen = 0; return my_net_read_packet_reallen(net, read_from_server, &reallen); } ulong my_net_read_packet_reallen(NET *net, my_bool read_from_server, ulong* reallen) { size_t len, complen; MYSQL_NET_READ_START(); *reallen = 0; #ifdef HAVE_COMPRESS if (!net->compress) { #endif len = my_real_read(net,&complen, read_from_server); if (len == MAX_PACKET_LENGTH) { /* First packet of a multi-packet. Concatenate the packets */ ulong save_pos = net->where_b; size_t total_length= 0; do { net->where_b += (ulong)len; total_length += len; len = my_real_read(net,&complen, 0); } while (len == MAX_PACKET_LENGTH); if (likely(len != packet_error)) len+= total_length; net->where_b = save_pos; } net->read_pos = net->buff + net->where_b; if (likely(len != packet_error)) { net->read_pos[len]=0; /* Safeguard for mysql_use_result */ *reallen = (ulong)len; } MYSQL_NET_READ_DONE(0, len); return (ulong)len; #ifdef HAVE_COMPRESS } else { /* We are using the compressed protocol */ ulong buf_length; ulong start_of_packet; ulong first_packet_offset; uint read_length, multi_byte_packet=0; if (net->remain_in_buf) { buf_length= net->buf_length; /* Data left in old packet */ first_packet_offset= start_of_packet= (net->buf_length - net->remain_in_buf); /* Restore the character that was overwritten by the end 0 */ net->buff[start_of_packet]= net->save_char; } else { /* reuse buffer, as there is nothing in it that we need */ buf_length= start_of_packet= first_packet_offset= 0; } for (;;) { ulong packet_len; if (buf_length - start_of_packet >= NET_HEADER_SIZE) { read_length = uint3korr(net->buff+start_of_packet); if (!read_length) { /* End of multi-byte packet */ start_of_packet += NET_HEADER_SIZE; break; } if (read_length + NET_HEADER_SIZE <= buf_length - start_of_packet) { if (multi_byte_packet) { /* Remove packet header for second packet */ memmove(net->buff + first_packet_offset + start_of_packet, net->buff + first_packet_offset + start_of_packet + NET_HEADER_SIZE, buf_length - start_of_packet); start_of_packet += read_length; buf_length -= NET_HEADER_SIZE; } else start_of_packet+= read_length + NET_HEADER_SIZE; if (read_length != MAX_PACKET_LENGTH) /* last package */ { multi_byte_packet= 0; /* No last zero len packet */ break; } multi_byte_packet= NET_HEADER_SIZE; /* Move data down to read next data packet after current one */ if (first_packet_offset) { memmove(net->buff,net->buff+first_packet_offset, buf_length-first_packet_offset); buf_length-=first_packet_offset; start_of_packet -= first_packet_offset; first_packet_offset=0; } continue; } } /* Move data down to read next data packet after current one */ if (first_packet_offset) { memmove(net->buff,net->buff+first_packet_offset, buf_length-first_packet_offset); buf_length-=first_packet_offset; start_of_packet -= first_packet_offset; first_packet_offset=0; } net->where_b=buf_length; if ((packet_len = my_real_read(net,&complen, read_from_server)) == packet_error) { MYSQL_NET_READ_DONE(1, 0); return packet_error; } read_from_server= 0; if (my_uncompress(net->buff + net->where_b, packet_len, &complen)) { net->error= 2; /* caller will close socket */ net->last_errno= ER_NET_UNCOMPRESS_ERROR; MYSQL_SERVER_my_error(ER_NET_UNCOMPRESS_ERROR, MYF(0)); MYSQL_NET_READ_DONE(1, 0); return packet_error; } buf_length+= (ulong)complen; *reallen += packet_len; } net->read_pos= net->buff+ first_packet_offset + NET_HEADER_SIZE; net->buf_length= buf_length; net->remain_in_buf= (ulong) (buf_length - start_of_packet); len = ((ulong) (start_of_packet - first_packet_offset) - NET_HEADER_SIZE - multi_byte_packet); net->save_char= net->read_pos[len]; /* Must be saved */ net->read_pos[len]=0; /* Safeguard for mysql_use_result */ } #endif /* HAVE_COMPRESS */ MYSQL_NET_READ_DONE(0, len); return (ulong)len; } void my_net_set_read_timeout(NET *net, uint timeout) { DBUG_ENTER("my_net_set_read_timeout"); DBUG_PRINT("enter", ("timeout: %d", timeout)); if (net->read_timeout != timeout) { net->read_timeout= timeout; if (net->vio) vio_timeout(net->vio, 0, timeout); } DBUG_VOID_RETURN; } void my_net_set_write_timeout(NET *net, uint timeout) { DBUG_ENTER("my_net_set_write_timeout"); DBUG_PRINT("enter", ("timeout: %d", timeout)); if (net->write_timeout != timeout) { net->write_timeout= timeout; if (net->vio) vio_timeout(net->vio, 1, timeout); } DBUG_VOID_RETURN; }
MariaDB/server
sql/net_serv.cc
C++
gpl-2.0
40,989
<?php namespace UsingTraits; /** * A controller. */ class ProductController { use DeleteEntity; /** * @OA\Get( * tags={"Products"}, * path="/products/{product_id}", * @OA\Parameter( * description="ID of product to return", * in="path", * name="product_id", * required=true, * @OA\Schema( * type="string" * ) * ), * @OA\Response( * response="default", * description="successful operation" * ) * ) */ public function getProduct($id) { } }
egbot/Symbiota
api/vendor/zircote/swagger-php/Examples/using-traits/ProductController.php
PHP
gpl-2.0
606
<?php /** * @group scripts */ class Tests_Scripts extends EDD_UnitTestCase { /** * Test if all the file hooks are working. * * @since 2.3.6 */ public function test_file_hooks() { $this->assertNotFalse( has_action( 'wp_enqueue_scripts', 'edd_load_scripts' ) ); $this->assertNotFalse( has_action( 'wp_enqueue_scripts', 'edd_register_styles' ) ); $this->assertNotFalse( has_action( 'admin_enqueue_scripts', 'edd_load_admin_scripts' ) ); $this->assertNotFalse( has_action( 'admin_head', 'edd_admin_downloads_icon' ) ); } /** * Test that all the scripts are loaded at the checkout page. * * @since 2.3.6 */ public function test_load_scripts_checkout() { global $edd_options; // Prepare test $this->go_to( get_permalink( $edd_options['purchase_page'] ) ); edd_load_scripts(); $this->assertTrue( wp_script_is( 'creditCardValidator', 'enqueued' ) ); $this->assertTrue( wp_script_is( 'edd-checkout-global', 'enqueued' ) ); $this->assertTrue( wp_script_is( 'edd-ajax', 'enqueued' ) ); $this->go_to( '/' ); } /** * Test that the edd_register_styles() function will bail when the 'disable_styles' * option is set to true. * * @since 2.3.6 */ public function test_register_styles_bail_option() { // Prepare test $origin_disable_styles = edd_get_option( 'disable_styles', false ); edd_update_option( 'disable_styles', true ); // Assert $this->assertNull( edd_register_styles() ); // Reset to origin edd_update_option( 'disable_styles', $origin_disable_styles ); } /** * Test that the edd_register_styles() function will enqueue the styles. * * @since 2.3.6 */ public function test_register_styles() { edd_update_option( 'disable_styles', false ); edd_register_styles(); $this->assertTrue( wp_style_is( 'edd-styles', 'enqueued' ) ); } /** * Test that the edd_register_styles() function will enqueue the proper styles * when page is checkout + ssl. * * @since 2.3.6 */ public function test_register_styles_checkout_ssl() { // Prepare test $_SERVER['HTTPS'] = 'ON'; // Fake SSL $this->go_to( get_permalink( edd_get_option( 'purchase_page' ) ) ); edd_update_option( 'disable_styles', false ); edd_register_styles(); $this->go_to( '/' ); unset( $_SERVER['HTTPS'] ); } /** * Test that the edd_load_admin_scripts() function will bail when not a EDD admin page. * * @since 2.3.6 */ public function test_load_admin_scripts_bail() { // Prepare test global $pagenow; $origin_pagenow = $pagenow; $pagenow = 'dashboard'; if ( ! function_exists( 'edd_is_admin_page' ) ) { include EDD_PLUGIN_DIR . 'includes/admin/admin-pages.php'; } // Assert $this->assertNull( edd_load_admin_scripts( 'dashboard' ) ); // Reset to origin $pagenow = $origin_pagenow; } /** * Test that the edd_load_admin_scripts() function will enqueue the proper styles. * * @since 2.3.6 */ public function test_load_admin_scripts() { if ( ! function_exists( 'edd_is_admin_page' ) ) { include EDD_PLUGIN_DIR . 'includes/admin/admin-pages.php'; } edd_load_admin_scripts( 'settings.php' ); $this->assertTrue( wp_style_is( 'jquery-chosen', 'enqueued' ) ); $this->assertTrue( wp_style_is( 'wp-color-picker', 'enqueued' ) ); $this->assertTrue( wp_style_is( 'jquery-ui-css', 'enqueued' ) ); $this->assertTrue( wp_style_is( 'thickbox', 'enqueued' ) ); $this->assertTrue( wp_style_is( 'edd-admin', 'enqueued' ) ); $this->assertTrue( wp_script_is( 'jquery-chosen', 'enqueued' ) ); $this->assertTrue( wp_script_is( 'edd-admin-scripts', 'enqueued' ) ); // $this->assertTrue( wp_script_is( 'wp-color-picker', 'enqueued' ) ); $this->assertTrue( wp_script_is( 'jquery-ui-datepicker', 'enqueued' ) ); $this->assertTrue( wp_script_is( 'jquery-ui-dialog', 'enqueued' ) ); $this->assertTrue( wp_script_is( 'jquery-flot', 'enqueued' ) ); $this->assertTrue( wp_script_is( 'media-upload', 'enqueued' ) ); $this->assertTrue( wp_script_is( 'thickbox', 'enqueued' ) ); } }
easydigitaldownloads/Easy-Digital-Downloads
tests/tests-scripts.php
PHP
gpl-2.0
4,022
/* * Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Assembly of Iron Author: SD%Complete: 100% SDComment: EndScriptData */ #include "ScriptPCH.h" #include "ulduar.h" enum Spells { // Any boss SPELL_SUPERCHARGE = 61920, SPELL_BERSERK = 47008, // Hard enrage, don't know the correct ID. // Steelbreaker SPELL_HIGH_VOLTAGE = 61890, SPELL_FUSION_PUNCH = 61903, SPELL_STATIC_DISRUPTION = 44008, //63494 SPELL_OVERWHELMING_POWER = 64637, SPELL_ELECTRICAL_CHARGE = 61902, // Runemaster Molgeim SPELL_SHIELD_OF_RUNES = 62274, SPELL_RUNE_OF_POWER = 61973, SPELL_RUNE_OF_POWER_VISUAL = 61974, SPELL_RUNE_OF_DEATH = 62269, SPELL_RUNE_OF_SUMMONING = 62273, SPELL_RUNE_OF_SUMMONING_VISUAL = 62019, SPELL_RUNE_OF_SUMMONING_SUMMON = 62020, SPELL_LIGHTNING_BLAST = 62054, // Stormcaller Brundir SPELL_CHAIN_LIGHTNING = 61879, SPELL_OVERLOAD = 61869, SPELL_LIGHTNING_WHIRL = 61915, SPELL_LIGHTNING_TENDRILS = 61887, SPELL_LIGHTNING_TENDRILS_SELF_VISUAL = 61883, SPELL_STORMSHIELD = 64187 }; enum eEnums { EVENT_ENRAGE, // Steelbreaker EVENT_FUSION_PUNCH, EVENT_STATIC_DISRUPTION, EVENT_OVERWHELMING_POWER, // Molgeim EVENT_RUNE_OF_POWER, EVENT_SHIELD_OF_RUNES, EVENT_RUNE_OF_DEATH, EVENT_RUNE_OF_SUMMONING, EVENT_LIGHTNING_BLAST, // Brundir EVENT_CHAIN_LIGHTNING, EVENT_OVERLOAD, EVENT_LIGHTNING_WHIRL, EVENT_LIGHTNING_TENDRILS, EVENT_FLIGHT, EVENT_ENDFLIGHT, EVENT_GROUND, EVENT_LAND, EVENT_MOVE_POS }; enum Actions { ACTION_STEELBREAKER, ACTION_MOLGEIM, ACTION_BRUNDIR }; // Achievements #define ACHIEVEMENT_ON_YOUR_SIDE RAID_MODE(2945, 2946) // TODO #define ACHIEVEMENT_CANT_WHILE_STUNNED RAID_MODE(2947, 2948) // TODO #define ACHIEVEMENT_CHOOSE_STEELBREAKER RAID_MODE(2941, 2944) #define ACHIEVEMENT_CHOOSE_MOLGEIM RAID_MODE(2939, 2942) #define ACHIEVEMENT_CHOOSE_BRUNDIR RAID_MODE(2940, 2943) #define EMOTE_OVERLOAD "Stormcaller Brundir begins to Overload!" enum Yells { SAY_STEELBREAKER_AGGRO = -1603020, SAY_STEELBREAKER_SLAY_1 = -1603021, SAY_STEELBREAKER_SLAY_2 = -1603022, SAY_STEELBREAKER_POWER = -1603023, SAY_STEELBREAKER_DEATH_1 = -1603024, SAY_STEELBREAKER_DEATH_2 = -1603025, SAY_STEELBREAKER_BERSERK = -1603026, SAY_MOLGEIM_AGGRO = -1603030, SAY_MOLGEIM_SLAY_1 = -1603031, SAY_MOLGEIM_SLAY_2 = -1603032, SAY_MOLGEIM_RUNE_DEATH = -1603033, SAY_MOLGEIM_SUMMON = -1603034, SAY_MOLGEIM_DEATH_1 = -1603035, SAY_MOLGEIM_DEATH_2 = -1603036, SAY_MOLGEIM_BERSERK = -1603037, SAY_BRUNDIR_AGGRO = -1603040, SAY_BRUNDIR_SLAY_1 = -1603041, SAY_BRUNDIR_SLAY_2 = -1603042, SAY_BRUNDIR_SPECIAL = -1603043, SAY_BRUNDIR_FLIGHT = -1603044, SAY_BRUNDIR_DEATH_1 = -1603045, SAY_BRUNDIR_DEATH_2 = -1603046, SAY_BRUNDIR_BERSERK = -1603047, }; bool IsEncounterComplete(InstanceScript* pInstance, Creature* me) { if (!pInstance || !me) return false; for (uint8 i = 0; i < 3; ++i) { uint64 guid = pInstance->GetData64(DATA_STEELBREAKER+i); if (!guid) return false; if (Creature *boss = Unit::GetCreature(*me, guid)) { if (boss->isAlive()) return false; } else return false; } return true; } // Avoid killing bosses one to one void CallBosses(InstanceScript* pInstance, uint32 caller, Unit *who) { // Respawn if dead if (Creature* Steelbreaker = who->GetCreature(*who, pInstance->GetData64(DATA_STEELBREAKER))) if (Steelbreaker->isDead()) { Steelbreaker->Respawn(true); Steelbreaker->GetMotionMaster()->MoveTargetedHome(); } if (Creature* Brundir = who->GetCreature(*who, pInstance->GetData64(DATA_BRUNDIR))) if (Brundir->isDead()) { Brundir->Respawn(true); Brundir->GetMotionMaster()->MoveTargetedHome(); } if (Creature* Molgeim = who->GetCreature(*who, pInstance->GetData64(DATA_MOLGEIM))) if (Molgeim->isDead()) { Molgeim->Respawn(true); Molgeim->GetMotionMaster()->MoveTargetedHome(); } for (uint8 i = 0; i < 3; ++i) { if (caller == DATA_STEELBREAKER+i) continue; uint64 guid = pInstance->GetData64(DATA_STEELBREAKER+i); if (!guid) return; if (Creature* m_boss = pInstance->instance->GetCreature(guid)) { if (m_boss->isAlive()) { m_boss->AddThreat(who, 100.0f); m_boss->AI()->AttackStart(who); } } } } class boss_steelbreaker : public CreatureScript { public: boss_steelbreaker() : CreatureScript("boss_steelbreaker") { } CreatureAI* GetAI(Creature* pCreature) const { return new boss_steelbreakerAI (pCreature); } struct boss_steelbreakerAI : public ScriptedAI { boss_steelbreakerAI(Creature *c) : ScriptedAI(c) { pInstance = c->GetInstanceScript(); me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true); } EventMap events; InstanceScript* pInstance; uint32 phase; void Reset() { events.Reset(); phase = 0; me->RemoveAllAuras(); me->ResetLootMode(); if (pInstance) pInstance->SetBossState(BOSS_ASSEMBLY, NOT_STARTED); // Respawn if (Creature* Brundir = me->GetCreature(*me, pInstance->GetData64(DATA_BRUNDIR))) if (Brundir->isDead()) { Brundir->Respawn(true); Brundir->GetMotionMaster()->MoveTargetedHome(); } if (Creature* Molgeim = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM))) if (Molgeim->isDead()) { Molgeim->Respawn(true); Molgeim->GetMotionMaster()->MoveTargetedHome(); } } void EnterCombat(Unit* who) { DoScriptText(SAY_STEELBREAKER_AGGRO, me); DoZoneInCombat(); CallBosses(pInstance, DATA_STEELBREAKER, who); DoCast(me, SPELL_HIGH_VOLTAGE); phase = 1; events.SetPhase(phase); events.ScheduleEvent(EVENT_ENRAGE, 900000); events.ScheduleEvent(EVENT_FUSION_PUNCH, 15000); } void JustDied(Unit* /*Killer*/) { DoScriptText(RAND(SAY_STEELBREAKER_DEATH_1, SAY_STEELBREAKER_DEATH_2), me); if (IsEncounterComplete(pInstance, me) && pInstance) { pInstance->SetBossState(BOSS_ASSEMBLY, DONE); pInstance->DoCompleteAchievement(ACHIEVEMENT_CHOOSE_STEELBREAKER); pInstance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, 65195); } else me->SetLootRecipient(NULL); if (Creature* Brundir = me->GetCreature(*me, pInstance->GetData64(DATA_BRUNDIR))) if (Brundir->isAlive()) Brundir->AI()->DoAction(ACTION_BRUNDIR); if (Creature* Molgeim = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM))) if (Molgeim->isAlive()) Molgeim->AI()->DoAction(ACTION_MOLGEIM); } void KilledUnit(Unit * /*who*/) { DoScriptText(RAND(SAY_STEELBREAKER_SLAY_1,SAY_STEELBREAKER_SLAY_2), me); if (phase == 3) DoCast(me, SPELL_ELECTRICAL_CHARGE); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch(eventId) { case EVENT_ENRAGE: DoScriptText(SAY_STEELBREAKER_BERSERK, me); DoCast(SPELL_BERSERK); break; case EVENT_FUSION_PUNCH: if (me->IsWithinMeleeRange(me->getVictim())) DoCastVictim(SPELL_FUSION_PUNCH); events.ScheduleEvent(EVENT_FUSION_PUNCH, urand(15000, 20000)); break; case EVENT_STATIC_DISRUPTION: if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(pTarget, SPELL_STATIC_DISRUPTION); events.ScheduleEvent(EVENT_STATIC_DISRUPTION, 20000 + (rand()%20)*1000); break; case EVENT_OVERWHELMING_POWER: DoScriptText(SAY_STEELBREAKER_POWER, me); DoCastVictim(SPELL_OVERWHELMING_POWER); events.ScheduleEvent(EVENT_OVERWHELMING_POWER, RAID_MODE(60000, 35000)); break; } } DoMeleeAttackIfReady(); } void DoAction(const int32 action) { switch (action) { case ACTION_STEELBREAKER: me->SetFullHealth(); me->AddAura(SPELL_SUPERCHARGE, me); ++phase; events.SetPhase(phase); if (phase >= 2) events.RescheduleEvent(EVENT_STATIC_DISRUPTION, 30000); if (phase >= 3) { events.RescheduleEvent(EVENT_OVERWHELMING_POWER, urand(2000, 5000)); // Add HardMode Loot me->AddLootMode(LOOT_MODE_HARD_MODE_2); } break; } } }; }; class boss_runemaster_molgeim : public CreatureScript { public: boss_runemaster_molgeim() : CreatureScript("boss_runemaster_molgeim") { } CreatureAI* GetAI(Creature* pCreature) const { return new boss_runemaster_molgeimAI (pCreature); } struct boss_runemaster_molgeimAI : public ScriptedAI { boss_runemaster_molgeimAI(Creature *c) : ScriptedAI(c) { pInstance = c->GetInstanceScript(); me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true); } InstanceScript* pInstance; EventMap events; uint32 phase; void Reset() { if (pInstance) pInstance->SetBossState(BOSS_ASSEMBLY, NOT_STARTED); events.Reset(); me->ResetLootMode(); me->RemoveAllAuras(); phase = 0; // Respawn if (Creature* Brundir = me->GetCreature(*me, pInstance->GetData64(DATA_BRUNDIR))) if (Brundir->isDead()) { Brundir->Respawn(true); Brundir->GetMotionMaster()->MoveTargetedHome(); } if (Creature* Steelbreaker = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER))) if (Steelbreaker->isDead()) { Steelbreaker->Respawn(true); Steelbreaker->GetMotionMaster()->MoveTargetedHome(); } } void EnterCombat(Unit* who) { DoScriptText(SAY_MOLGEIM_AGGRO, me); DoZoneInCombat(); CallBosses(pInstance, DATA_MOLGEIM, who); phase = 1; pInstance->SetBossState(BOSS_ASSEMBLY, IN_PROGRESS); events.ScheduleEvent(EVENT_ENRAGE, 900000); events.ScheduleEvent(EVENT_SHIELD_OF_RUNES, 30000); events.ScheduleEvent(EVENT_RUNE_OF_POWER, 20000); } void JustDied(Unit* /*Killer*/) { DoScriptText(RAND(SAY_MOLGEIM_DEATH_1, SAY_MOLGEIM_DEATH_2), me); if (IsEncounterComplete(pInstance, me) && pInstance) { pInstance->SetBossState(BOSS_ASSEMBLY, DONE); pInstance->DoCompleteAchievement(ACHIEVEMENT_CHOOSE_MOLGEIM); pInstance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, 65195); } else me->SetLootRecipient(NULL); if (Creature* Brundir = me->GetCreature(*me, pInstance->GetData64(DATA_BRUNDIR))) if (Brundir->isAlive()) Brundir->AI()->DoAction(ACTION_BRUNDIR); if (Creature* Steelbreaker = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER))) if (Steelbreaker->isAlive()) Steelbreaker->AI()->DoAction(ACTION_STEELBREAKER); } void KilledUnit(Unit * /*who*/) { DoScriptText(RAND(SAY_MOLGEIM_SLAY_1,SAY_MOLGEIM_SLAY_2), me); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch(eventId) { case EVENT_ENRAGE: DoScriptText(SAY_MOLGEIM_BERSERK, me); DoCast(SPELL_BERSERK); break; case EVENT_RUNE_OF_POWER: // random alive friendly { Creature* bosschoosed; uint32 choice = urand(0,2); if (!pInstance) break; bosschoosed = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER+choice)); if (!bosschoosed || !bosschoosed->isAlive()) { choice = ((choice == 2) ? 0 : choice++); bosschoosed = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER+choice)); if (!bosschoosed || !bosschoosed->isAlive()) { choice = ((choice == 2) ? 0 : choice++); bosschoosed = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER+choice)); } } if (!bosschoosed || !bosschoosed->isAlive()) bosschoosed = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM)); DoCast(bosschoosed, SPELL_RUNE_OF_POWER); events.ScheduleEvent(EVENT_RUNE_OF_POWER, 35000); break; } case EVENT_SHIELD_OF_RUNES: DoCast(me, SPELL_SHIELD_OF_RUNES); events.ScheduleEvent(EVENT_SHIELD_OF_RUNES, urand(60000, 80000)); break; case EVENT_RUNE_OF_DEATH: DoScriptText(SAY_MOLGEIM_RUNE_DEATH, me); if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(pTarget, SPELL_RUNE_OF_DEATH); events.ScheduleEvent(EVENT_RUNE_OF_DEATH, 30000); break; case EVENT_RUNE_OF_SUMMONING: DoScriptText(SAY_MOLGEIM_SUMMON, me); if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(pTarget, SPELL_RUNE_OF_SUMMONING); events.ScheduleEvent(EVENT_RUNE_OF_SUMMONING, urand(40000, 50000)); break; } } DoMeleeAttackIfReady(); } void DoAction(const int32 action) { switch (action) { case ACTION_MOLGEIM: me->SetFullHealth(); me->AddAura(SPELL_SUPERCHARGE, me); ++phase; events.SetPhase(phase); events.RescheduleEvent(EVENT_SHIELD_OF_RUNES, 30000); events.RescheduleEvent(EVENT_RUNE_OF_POWER, 20000); if (phase >= 2) events.RescheduleEvent(EVENT_RUNE_OF_DEATH, 35000); if (phase >= 3) { events.RescheduleEvent(EVENT_RUNE_OF_SUMMONING, 40000); me->AddLootMode(LOOT_MODE_HARD_MODE_1); } break; } } }; }; class npc_lightning_elemental : public CreatureScript { public: npc_lightning_elemental() : CreatureScript("npc_lightning_elemental") { } CreatureAI* GetAI(Creature* pCreature) const { return new npc_lightning_elementalAI (pCreature); } struct npc_lightning_elementalAI : public ScriptedAI { npc_lightning_elementalAI(Creature *c) : ScriptedAI(c) { Charge(); Casted = false; } bool Casted; void Charge() { Unit* pTarget = me->SelectNearestTarget(); me->AddThreat(pTarget, 5000000.0f); AttackStart(pTarget); } void UpdateAI(const uint32 /*diff*/) { if (!UpdateVictim()) return; if (me->IsWithinMeleeRange(me->getVictim()) && !Casted) { me->CastSpell(me, SPELL_LIGHTNING_BLAST, true); me->ForcedDespawn(500); Casted = true; } } }; }; class npc_rune_of_summoning : public CreatureScript { public: npc_rune_of_summoning() : CreatureScript("npc_rune_of_summoning") { } CreatureAI* GetAI(Creature* pCreature) const { return new npc_rune_of_summoningAI (pCreature); } struct npc_rune_of_summoningAI : public Scripted_NoMovementAI { npc_rune_of_summoningAI(Creature *c) : Scripted_NoMovementAI(c) { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_PACIFIED); } uint32 SummonTimer; void Reset() { SummonTimer = 1500; me->ForcedDespawn(12500); DoCast(me, SPELL_RUNE_OF_SUMMONING_VISUAL); } void UpdateAI(const uint32 uiDiff) { if (SummonTimer <= uiDiff) { DoCast(me, SPELL_RUNE_OF_SUMMONING_SUMMON); SummonTimer = 1500; } else SummonTimer -= uiDiff; } }; }; class npc_rune_of_power : public CreatureScript { public: npc_rune_of_power() : CreatureScript("npc_rune_of_power") { } CreatureAI* GetAI(Creature* pCreature) const { return new npc_rune_of_powerAI (pCreature); } struct npc_rune_of_powerAI : public Scripted_NoMovementAI { npc_rune_of_powerAI(Creature *c) : Scripted_NoMovementAI(c) { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_PACIFIED); me->setFaction(16); } void Reset() { DoCast(me, SPELL_RUNE_OF_POWER_VISUAL, true); me->ForcedDespawn(35000); } }; }; class boss_stormcaller_brundir : public CreatureScript { public: boss_stormcaller_brundir() : CreatureScript("boss_stormcaller_brundir") { } CreatureAI* GetAI(Creature* pCreature) const { return new boss_stormcaller_brundirAI (pCreature); } struct boss_stormcaller_brundirAI : public ScriptedAI { boss_stormcaller_brundirAI(Creature *c) : ScriptedAI(c) { pInstance = c->GetInstanceScript(); me->SetReactState(REACT_PASSIVE); me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true); } EventMap events; InstanceScript* pInstance; uint32 phase; uint32 Position; void Reset() { if (pInstance) pInstance->SetBossState(BOSS_ASSEMBLY, NOT_STARTED); me->RemoveAllAuras(); me->ResetLootMode(); me->RemoveUnitMovementFlag(MOVEMENTFLAG_LEVITATING | MOVEMENTFLAG_WALKING); events.Reset(); phase = 0; // Respawn if (Creature* Molgeim = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM))) if (Molgeim->isDead()) { Molgeim->Respawn(true); Molgeim->GetMotionMaster()->MoveTargetedHome(); } if (Creature* Steelbreaker = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER))) if (Steelbreaker->isDead()) { Steelbreaker->Respawn(true); Steelbreaker->GetMotionMaster()->MoveTargetedHome(); } } void EnterCombat(Unit* who) { DoScriptText(SAY_BRUNDIR_AGGRO, me); DoZoneInCombat(); CallBosses(pInstance, DATA_BRUNDIR, who); phase = 1; events.ScheduleEvent(EVENT_MOVE_POS, 1000); events.ScheduleEvent(EVENT_ENRAGE, 900000); events.ScheduleEvent(EVENT_CHAIN_LIGHTNING, 2000); events.ScheduleEvent(EVENT_OVERLOAD, urand(60000, 120000)); } void JustDied(Unit* /*Killer*/) { DoScriptText(RAND(SAY_BRUNDIR_DEATH_1, SAY_BRUNDIR_DEATH_2), me); if (IsEncounterComplete(pInstance, me) && pInstance) { pInstance->SetBossState(BOSS_ASSEMBLY, DONE); pInstance->DoCompleteAchievement(ACHIEVEMENT_CHOOSE_BRUNDIR); pInstance->DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, 65195); if (me->GetPositionZ() > 428) me->GetMotionMaster()->MoveFall(427.28f); } else me->SetLootRecipient(NULL); if (Creature* Molgeim = me->GetCreature(*me, pInstance->GetData64(DATA_MOLGEIM))) if (Molgeim->isAlive()) Molgeim->AI()->DoAction(ACTION_MOLGEIM); if (Creature* Steelbreaker = me->GetCreature(*me, pInstance->GetData64(DATA_STEELBREAKER))) if (Steelbreaker->isAlive()) Steelbreaker->AI()->DoAction(ACTION_STEELBREAKER); } void KilledUnit(Unit* /*who*/) { DoScriptText(RAND(SAY_BRUNDIR_SLAY_1,SAY_BRUNDIR_SLAY_2), me); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STAT_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch(eventId) { case EVENT_MOVE_POS: MovePos(); events.RescheduleEvent(EVENT_MOVE_POS, 10000); break; case EVENT_ENRAGE: DoScriptText(SAY_BRUNDIR_BERSERK, me); DoCast(SPELL_BERSERK); break; case EVENT_CHAIN_LIGHTNING: if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(pTarget, SPELL_CHAIN_LIGHTNING); events.ScheduleEvent(EVENT_CHAIN_LIGHTNING, urand(4000, 6000)); break; case EVENT_OVERLOAD: me->MonsterTextEmote(EMOTE_OVERLOAD, 0, true); DoScriptText(SAY_BRUNDIR_SPECIAL, me); me->GetMotionMaster()->Initialize(); DoCast(SPELL_OVERLOAD); events.ScheduleEvent(EVENT_OVERLOAD, urand(60000, 120000)); break; case EVENT_LIGHTNING_WHIRL: me->GetMotionMaster()->Initialize(); DoCast(SPELL_LIGHTNING_WHIRL); events.ScheduleEvent(EVENT_LIGHTNING_WHIRL, urand(15000, 20000)); break; case EVENT_LIGHTNING_TENDRILS: DoScriptText(SAY_BRUNDIR_FLIGHT, me); DoCast(SPELL_LIGHTNING_TENDRILS); DoCast(SPELL_LIGHTNING_TENDRILS_SELF_VISUAL); me->AddUnitMovementFlag(MOVEMENTFLAG_LEVITATING); me->GetMotionMaster()->MovePoint(0, me->GetPositionX(), me->GetPositionY(), 435); events.DelayEvents(34000); events.ScheduleEvent(EVENT_FLIGHT, 2500); events.ScheduleEvent(EVENT_ENDFLIGHT, 28000); events.ScheduleEvent(EVENT_LIGHTNING_TENDRILS, 90000); break; case EVENT_FLIGHT: if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0)) me->GetMotionMaster()->MovePoint(0, pTarget->GetPositionX(), pTarget->GetPositionY(), 435); events.ScheduleEvent(EVENT_FLIGHT, 6000); break; case EVENT_ENDFLIGHT: me->GetMotionMaster()->MovePoint(0, 1586.920f, 119.849f, 435); events.CancelEvent(EVENT_FLIGHT); events.ScheduleEvent(EVENT_LAND, 4000); break; case EVENT_LAND: me->GetMotionMaster()->MovePoint(0, me->GetPositionX(), me->GetPositionY(), 427.28f); events.ScheduleEvent(EVENT_GROUND, 1500); break; case EVENT_GROUND: me->RemoveAurasDueToSpell(SPELL_LIGHTNING_TENDRILS); me->RemoveAurasDueToSpell(SPELL_LIGHTNING_TENDRILS_SELF_VISUAL); me->RemoveUnitMovementFlag(MOVEMENTFLAG_LEVITATING); me->SendMovementFlagUpdate(); break; } } } void DoAction(const int32 action) { switch (action) { case ACTION_BRUNDIR: me->SetFullHealth(); me->AddAura(SPELL_SUPERCHARGE, me); ++phase; events.SetPhase(phase); events.RescheduleEvent(EVENT_CHAIN_LIGHTNING, urand(6000, 12000)); events.RescheduleEvent(EVENT_OVERLOAD, 40000); if (phase >= 2) events.RescheduleEvent(EVENT_LIGHTNING_WHIRL, urand(15000, 20000)); if (phase >= 3) { me->AddAura(SPELL_STORMSHIELD, me); events.RescheduleEvent(EVENT_LIGHTNING_TENDRILS, 60000); me->AddLootMode(LOOT_MODE_HARD_MODE_1); } break; } } void MovePos() { switch(Position) { case 0: me->GetMotionMaster()->MovePoint(0, 1587.28f, 97.030f, 427.28f); break; case 1: me->GetMotionMaster()->MovePoint(0, 1587.18f, 121.03f, 427.28f); break; case 2: me->GetMotionMaster()->MovePoint(0, 1587.34f, 142.58f, 427.28f); break; case 3: me->GetMotionMaster()->MovePoint(0, 1587.18f, 121.03f, 427.28f); break; } Position++; if (Position > 3) { Position = 0; } } }; }; void AddSC_boss_assembly_of_iron() { new boss_steelbreaker(); new boss_runemaster_molgeim(); new boss_stormcaller_brundir(); new npc_lightning_elemental(); new npc_rune_of_summoning(); new npc_rune_of_power(); }
proofrepo/MadboxpcWOW_3.0
src/server/scripts/Northrend/Ulduar/ulduar/boss_assembly_of_iron.cpp
C++
gpl-2.0
30,497
/** * @file * @author Witek902 (witek902@gmail.com) */ #include "PCH.hpp" #include "Event_Input.hpp" #include "Engine/Common/Reflection/ReflectionClassDefine.hpp" NFE_DEFINE_POLYMORPHIC_CLASS(NFE::Scene::Event_Input) NFE_CLASS_PARENT(NFE::Scene::Event) NFE_END_DEFINE_CLASS() namespace NFE { namespace Scene { Event_Input::Event_Input(const Input::EventData& data) : mData(data) { } } // namespace Scene } // namespace NFE
nfprojects/nfengine
Src/Engine/Core/Scene/Events/Event_Input.cpp
C++
gpl-2.0
441
// // GPActionDeclFloat.cs // // Author(s): // Baptiste Dupy <baptiste.dupy@gmail.com> // // Copyright (c) 2014 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using UnityEngine; using System.Collections; using System.Collections.Generic; namespace ActionTool { [GPActionNoInput] [GPActionAlias("Variable/Float/Declaration")] public class GPActionDeclFloat : GPActionVariable { #region Public Members public float _value; #endregion #region GPActionVariable Override public override object GetValue () { return _value; } public override void SetValue(System.Object value) { _value = (float) value; } #endregion } }
trfd/Unity-ActionTool
Actions/Variables/Decl/GPActionDeclFloat.cs
C#
gpl-2.0
1,729
//$(document).ready(function() { /* Range Slider Function */ (function($) { $.fn.rkmd_rangeSlider = function() { var self, slider_width, slider_offset, curnt, sliderContinuous, sliderDiscrete, range, slider; self = $(this); slider_width = self.outerWidth(); slider_offset = self.offset().left; sliderContinuous = $('.slider-continuous'); sliderDiscrete = $('.slider-discrete'); if(self.hasClass('slider-continuous') === true) { sliderContinuous.each(function(i, v) { curnt = $(this); curnt.append(sliderContinuous_tmplt()); range = curnt.find('input[type="range"]'); slider = curnt.find('.slider'); slider_fill = slider.find('.slider-fill'); slider_handle = slider.find('.slider-handle'); var range_val = range.val(); slider_fill.css('width', range_val +'%'); slider_handle.css('left', range_val +'%'); }); } if(self.hasClass('slider-discrete') === true) { sliderDiscrete.each(function(i, v) { curnt = $(this); curnt.append(sliderDiscrete_tmplt()); range = curnt.find('input[type="range"]'); slider = curnt.find('.slider'); slider_fill = slider.find('.slider-fill'); slider_handle = slider.find('.slider-handle'); slider_label = slider.find('.slider-label'); var range_val = parseInt(range.val()); slider_fill.css('width', range_val +'%'); slider_handle.css('left', range_val +'%'); slider_label.find('span').text(range_val); }); } self.on('mousedown', '.slider-handle', function(e) { if(e.button === 2) { return false; } var parents = $(this).parents('.rkmd-slider'); var slider_width = parents.outerWidth(); var slider_offset = parents.offset().left; var check_range = parents.find('input[type="range"]').is(':disabled'); if(check_range === true) { return false; } if(parents.hasClass('slider-discrete') === true) { $(this).addClass('is-active'); } var handlers = { mousemove: function(e) { var slider_new_width = e.pageX - slider_offset; if(slider_new_width <= slider_width && !(slider_new_width < '0')) { slider_move(parents, slider_new_width, slider_width); } }, mouseup: function(e) { $(this).off(handlers); if(parents.hasClass('slider-discrete') === true) { parents.find('.is-active').removeClass('is-active'); } } }; $(document).on(handlers); }); self.on('mousedown', '.slider', function(e) { if(e.button === 2) { return false; } var parents = $(this).parents('.rkmd-slider'); var slider_width = parents.outerWidth(); var slider_offset = parents.offset().left; var check_range = parents.find('input[type="range"]').is(':disabled'); if(check_range === true) { return false; } var slider_new_width = e.pageX - slider_offset; if(slider_new_width <= slider_width && !(slider_new_width < '0')) { slider_move(parents, slider_new_width, slider_width); } var handlers = { mouseup: function(e) { $(this).off(handlers); } }; $(document).on(handlers); }); }; function sliderContinuous_tmplt() { var tmplt = '<div class="slider">' + '<div class="slider-fill"></div>' + '<div class="slider-handle"></div>' + '</div>'; return tmplt; } function sliderDiscrete_tmplt() { var tmplt = '<div class="slider">' + '<div class="slider-fill"></div>' + '<div class="slider-handle"><div class="slider-label"><span>0</span></div></div>' + '</div>'; return tmplt; } function slider_move(parents, newW, sliderW) { var slider_new_val = parseInt(Math.round(newW / sliderW * 100)); var slider_fill = parents.find('.slider-fill'); var slider_handle = parents.find('.slider-handle'); var range = parents.find('input[type="range"]'); slider_fill.css('width', slider_new_val +'%'); slider_handle.css({ 'left': slider_new_val +'%', 'transition': 'none', '-webkit-transition': 'none', '-moz-transition': 'none' }); range.val(slider_new_val); if(parents.hasClass('slider-discrete') === true) { parents.find('.slider-handle span').text(slider_new_val); } } }(jQuery)); /* Change Slider Color */ function change_slider_color() { $('.color-box .show-box').on('click', function() { $(".color-box").toggleClass("open"); }); $('.colors-list a').on('click', function() { var curr_color = $('main').data('slider-color'); var color = $(this).data('slider-color'); var new_colot = 'slider-' + color; $('.rkmd-slider').each(function(i, v) { var findColor = $(this).hasClass(curr_color); if(findColor) { $(this).removeClass(curr_color); $(this).addClass(new_colot); } $('main').data('slider-color', new_colot); }); }); } $('.rkmd-slider').rkmd_rangeSlider(); //window.setInterval(function(){ //$('.rkmd-slider').rkmd_rangeSlider(); //change_slider_color(); //console.log("range.js ran"); //}, 5000); //});
johnfrancisgit/Chromaticity
js/range.js
JavaScript
gpl-2.0
5,426
/* * Copyright (C) 2002-2015 XimpleWare, info@ximpleware.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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /*VTD-XML is protected by US patent 7133857, 7260652, an 7761459*/ package com.ximpleware.extended; /** * This class iterates through all text nodes of an element. * VTDNavHuge has getText() which is inadequate for mixed content style of XML. * text nodes include character_data and CDATA. * This version is adapted to support extended VTD (256GB max file size) */ public class TextIterHuge { private int prevLocation; //previous location of text node protected int depth; protected int index; // this is index for the element protected VTDNavHuge vn; private int lcIndex; private int lcLower; private int lcUpper; /** * TextIter constructor comment. */ public TextIterHuge() { super(); vn = null; /*sel_char_data = true; sel_comment = true; sel_cdata = true;*/ } /** * Get the index vals for the text nodes in document order. * Creation date: (12/5/03 6:11:50 PM) * @return int (-1 if no more left) */ public int getNext() { if (vn == null) throw new IllegalArgumentException(" VTDNav instance can't be null"); int vtdSize = vn.vtdBuffer.size(); switch (depth) { case -1: return -1; case 0 : // scan forward, if none found, jump to level 1 element and scan backward until one is found // if there isn't a level-one element, jump to the end of vtd buffer and scan backward int sp = (prevLocation != -1) ? increment(prevLocation): index + 1; if (vn.l1Buffer.size() != 0) { int temp1 = vn.l1Buffer.upper32At(0); int temp2 = vn.l1Buffer.upper32At(vn.l1Buffer.size() - 1); lcIndex = (lcIndex != -1) ? lcIndex : 0; while (sp < vtdSize) { if (sp >= temp1 && sp < temp2) { int s = vn.l1Buffer.upper32At(lcIndex); if (sp == s) { // get to the next l1 element then do a rewind lcIndex++; sp = vn.l1Buffer.upper32At(lcIndex)-1; while (vn.getTokenDepth(sp) == 0 && vn.getTokenType(sp) != VTDNavHuge.TOKEN_STARTING_TAG) { //probe depth in here sp--; } sp++; // point to the first possible node } if (isText(sp) == true && vn.getTokenDepth(sp)==0) { prevLocation = sp; return sp; } sp++; } else if (sp < temp1) { if (isText(sp) == true && vn.getTokenDepth(sp)==0) { prevLocation = sp; return sp; } sp++; } else { if (sp == temp2) { // get to the end of the document and do a rewind sp = vn.vtdBuffer.size() - 1; while (vn.getTokenDepth(sp) <= 0) { sp--; } sp++; //continue; } if (sp>=vtdSize) return -1; else if (isText(sp) == true && vn.getTokenDepth(sp)==0) { prevLocation = sp; return sp; } else if (vn.getTokenDepth(sp)>1) { break; } sp++; } } //prevLocation = vtdSize-1; return -1; // found nothing } else { // no child element for root, just scan right forward while (sp < vtdSize) { if (isText(sp) == true && vn.getTokenDepth(sp)==0) { prevLocation = sp; return sp; } sp++; } return -1; } case 1 : if (prevLocation != -1) { sp = increment(prevLocation) ; } else { // fetch lclower and lcupper lcLower = vn.l1Buffer.lower32At(vn.l1index); if (lcLower != -1) { lcUpper = vn.l2Buffer.size() - 1; int size = vn.l1Buffer.size(); for (int i = vn.l1index + 1; i < size ; i++) { int temp = vn.l1Buffer.lower32At(i); if (temp != 0xffffffff) { lcUpper = temp - 1; break; } } } sp = index + 1; } // check for l2lower and l2upper if (lcLower != -1) { // have at least one child element int temp1 = vn.l2Buffer.upper32At(lcLower); int temp2 = vn.l2Buffer.upper32At(lcUpper); lcIndex = (lcIndex != -1) ? lcIndex : lcLower; while (sp < vtdSize) { int s = vn.l2Buffer.upper32At(lcIndex); if (sp >= temp1 && sp < temp2) { if (sp == s) { lcIndex++; sp = vn.l2Buffer.upper32At(lcIndex) - 1; while (vn.getTokenDepth(sp) == 1) { sp--; } sp++; //continue; } if (isText(sp) == true && vn.getTokenDepth(sp)==1 ) { prevLocation = sp; return sp; } sp++; } else if (sp < temp1) { if (isText(sp) == true) { prevLocation = sp; return sp; } sp++; } else { //if (sp == temp2) { // last child element //} else if (isText(sp) == true && vn.getTokenDepth(sp) == 1){ //System.out.println("depth ->"+vn.getTokenDepth(sp)); prevLocation = sp; return sp; } else if ((vn.getTokenType(sp)==VTDNavHuge.TOKEN_STARTING_TAG && vn.getTokenDepth(sp) < 2 ) || vn.getTokenDepth(sp)<1) { break; } sp++; } } //prevLocation = vtdSize-1; return -1; } else { // no child element if (sp>=vtdSize) return -1; int d = vn.getTokenDepth(sp); int type = vn.getTokenType(sp); while (sp < vtdSize && d >= 1 && !(d == 1 && type == VTDNavHuge.TOKEN_STARTING_TAG)) { if (isText(sp) == true) { prevLocation = sp; return sp; } sp++; d = vn.getTokenDepth(sp); type = vn.getTokenType(sp); } //prevLocation = vtdSize-1; return -1; } case 2 : if (prevLocation != -1) { sp = increment(prevLocation); } else { // fetch lclower and lcupper lcLower = vn.l2Buffer.lower32At(vn.l2index); if (lcLower != -1) { lcUpper = vn.l3Buffer.size() - 1; int size = vn.l2Buffer.size(); for (int i = vn.l2index + 1; i < size ; i++) { int temp = vn.l2Buffer.lower32At(i); if (temp != 0xffffffff) { lcUpper = temp - 1; break; } } } sp = index + 1; } // check for l3lower and l3upper if (lcLower != -1) { // at least one child element int temp1 = vn.l3Buffer.intAt(lcLower); int temp2 = vn.l3Buffer.intAt(lcUpper); lcIndex = (lcIndex != -1) ? lcIndex : lcLower; while (sp < vtdSize) { int s = vn.l3Buffer.intAt(lcIndex); //int s = vn.l2Buffer.upper32At(lcIndex); if (sp >= temp1 && sp < temp2) { if (sp == s) { lcIndex++; sp = vn.l3Buffer.intAt(lcIndex) - 1; while (vn.getTokenDepth(sp) == 2) { sp--; } sp++; //continue; } if (isText(sp) == true && vn.getTokenDepth(sp)==2) { prevLocation = sp; return sp; } sp++; } else if (sp < temp1) { if (isText(sp) == true && vn.getTokenDepth(sp)==2) { prevLocation = sp; return sp; } sp++; } else { //if (sp == temp2) { // last child element //} else if ( isText(sp) == true && vn.getTokenDepth(sp) == 2) { prevLocation = sp; return sp; } else if ((vn.getTokenType(sp)==VTDNavHuge.TOKEN_STARTING_TAG && vn.getTokenDepth(sp) < 3 ) || vn.getTokenDepth(sp)<2) { break; } sp++; } } //prevLocation = vtdSize-1; return -1; } else { // no child elements if (sp>=vtdSize) return -1; int d = vn.getTokenDepth(sp); int type = vn.getTokenType(sp); while (sp < vtdSize && d >= 2 && !(d == 2 && type == VTDNavHuge.TOKEN_STARTING_TAG)) { // the last condition indicates the start of the next sibling element if (isText(sp) == true && vn.getTokenDepth(sp)==2) { prevLocation = sp; return sp; } sp++; d = vn.getTokenDepth(sp); type = vn.getTokenType(sp); } //prevLocation = vtdSize-1; return -1; } default : //int curDepth = vn.context[0]; sp = (prevLocation != -1) ? increment(prevLocation): index + 1; if (sp>=vtdSize) return -1; int d = vn.getTokenDepth(sp); int type = vn.getTokenType(sp); while (d >= depth && !(d == depth && type == VTDNavHuge.TOKEN_STARTING_TAG)) { if (isText(sp) == true && d == depth) { prevLocation = sp; return sp; } sp++; if(sp >= vtdSize) return -1; d = vn.getTokenDepth(sp); type = vn.getTokenType(sp); } } //prevLocation = vtdSize-1; return -1; } /** * Test whether a give token type is a TEXT. * Creation date: (12/11/03 3:46:10 PM) * @return boolean * @param type int */ final private boolean isText(int index) { int type = vn.getTokenType(index); return (type == VTDNavHuge.TOKEN_CHARACTER_DATA //|| type == vn.TOKEN_COMMENT || type == VTDNavHuge.TOKEN_CDATA_VAL); } /** * Obtain the current navigation position and element info from VTDNav. * So one can instantiate it once and use it for many different elements * Creation date: (12/5/03 6:20:44 PM) * @param v com.ximpleware.VTDNav */ public void touch(VTDNavHuge v) { if (v == null) throw new IllegalArgumentException(" VTDNav instance can't be null"); depth = v.context[0]; if (depth == -1) index = 0; else index = (depth != 0) ? v.context[depth] : v.rootIndex; vn = v; prevLocation = -1; lcIndex = -1; lcUpper = -1; lcLower = -1; } private int increment(int sp){ int type = vn.getTokenType(sp); int vtdSize = vn.vtdBuffer.size(); int i=sp+1; while(i<vtdSize && depth == vn.getTokenDepth(i) && type == vn.getTokenType(i)&& (vn.getTokenOffset(i-1)+ (int)((vn.vtdBuffer.longAt(i-1) & VTDNavHuge.MASK_TOKEN_FULL_LEN)>>32) == vn.getTokenOffset(i)) ){ i++; } return i; } }
CoolBalance/vtd-xml
src/main/java/com/ximpleware/extended/TextIterHuge.java
Java
gpl-2.0
14,440
<?php include_once('admin/class-emma-settings.php'); include_once('widget/class-widget.php'); include_once('shortcode/class-shortcode.php'); include_once('class-emma-api.php'); include_once('class-form.php'); /** * Main Class for the Emma Emarketing Plugin * * long desc * @package Emma_Emarketing * @author ah so * @version 1.0 * @abstract * @copyright 2012 */ class Emma_Emarketing { /* * the constructor * Fired during plugins_loaded (very very early), * only actions and filters, * */ function __construct() { $emma_settings = new Emma_Settings(); // Add shortcode support for widgets add_filter('widget_text', 'do_shortcode'); } } // end Class Emma_Emarketing
samanthavandapuye/tease
wp-content/plugins/emma-emarketing-plugin/class-emma-emarketing.php
PHP
gpl-2.0
737
/** * OWASP Benchmark Project v1.1 * * 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 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 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 Nick Sanidas <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("/BenchmarkTest05161") public class BenchmarkTest05161 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 { org.owasp.benchmark.helpers.SeparateClassRequest scr = new org.owasp.benchmark.helpers.SeparateClassRequest( request ); String param = scr.getTheParameter("foo"); String bar; // Simple if statement that assigns param to bar on true condition int i = 196; if ( (500/42) + i > 200 ) bar = param; else bar = "This should never happen"; String cmd = org.owasp.benchmark.helpers.Utils.getOSCommandString("echo") + bar; String[] argsEnv = { "Foo=bar" }; Runtime r = Runtime.getRuntime(); try { Process p = r.exec(cmd, argsEnv, new java.io.File(System.getProperty("user.dir"))); org.owasp.benchmark.helpers.Utils.printOSCommandResults(p); } catch (IOException e) { System.out.println("Problem executing cmdi - TestCase"); throw new ServletException(e); } } }
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest05161.java
Java
gpl-2.0
2,337
package com.numhero.client.mvp.document; import com.google.gwt.resources.client.ResourcePrototype; import com.google.gwt.core.client.GWT; public class com_numhero_client_mvp_document_InvoicePanel_InvoiceUiBinderImpl_GenBundle_en_InlineClientBundleGenerator implements com.numhero.client.mvp.document.InvoicePanel_InvoiceUiBinderImpl_GenBundle { public ResourcePrototype[] getResources() { return new ResourcePrototype[] { }; } public native ResourcePrototype getResource(String name) /*-{ switch (name) { } return null; }-*/; }
midaboghetich/netnumero
gen/com/numhero/client/mvp/document/com_numhero_client_mvp_document_InvoicePanel_InvoiceUiBinderImpl_GenBundle_en_InlineClientBundleGenerator.java
Java
gpl-2.0
561
<?php global $user; ?> <article<?php print $attributes; ?>> <?php print render($title_prefix); ?> <?php if (!$page && $title): ?> <header> <h2<?php print $title_attributes; ?>><a href="<?php print $node_url ?>" title="<?php print $title ?>"><?php print $title ?></a></h2> </header> <?php endif; ?> <?php print render($title_suffix); ?> <div<?php print $content_attributes; ?>> <div class="row"> <div class="col-sm-6"> <div class="panel panel-notitle"> <div class="panel-body"> <?php print render($content['stato_bene']); ?> <div class="row"> <div class="col-sm-4"> <?php print render($content['field_fotografia']) ?> </div> <div class="col-sm-8"> <div class="profile-title"> <h1><?php print $title ; ?></h1> </div> <div class="row"> <div class="col-sm-12"> <?php print render($content['field_tipologia']); print render($content['field_progetto_collegato']); print render($content['og_group_ref']); ?> </div> </div> </div> </div> </div> <?php if(count(array_intersect(array('redazione', 'administrator'), array_values($user->roles))) > 0): ?> <div class="panel-footer"> <h3>Azioni redazione</h3> <div class="action-links"> <?php print l('Aggiungi patto di collaborazione', 'node/add/patto-di-collaborazione', array('query' => array('field_contenuto_collegato' => $node->nid))); ?> </div> </div> <?php endif; ?> </div> <?php if(isset($content['body'])): ?> <div class="panel"> <div class="panel-heading"> <h2 class="panel-title"><?php print t('Descrizione'); ?></h2> </div> <div class="panel-body"> <?php print render($content['body']); ?> </div> </div> <?php endif; ?> <?php if(isset($content['field_motivazione_bene'])): ?> <div class="panel"> <div class="panel-heading"> <h2 class="panel-title"><?php print t('Motivazione dell\'individuazione come Bene Comune'); ?></h2> </div> <div class="panel-body"> <?php print render($content['field_motivazione_bene']); ?> </div> </div> <?php endif; ?> </div> <div class="col-sm-6"> <?php print render($content['field_geo']); ?> <?php $view = views_get_view('patti_di_collaborazione'); $view->set_display('block'); $view->set_arguments(array($node->nid)); $view->pre_execute(); $view->execute(); if (!empty($view->result)) : ?> <div class="panel"> <div class="panel-heading"> <h2 class="panel-title"><?php print $view->get_title() ?></h2> </div> <div class="panel-body"> <?php print $view->preview(); ?> </div> </div> <?php endif; $view->destroy();?> <?php if(!empty($field_link_a_risorse_online_di_i)): ?> <div class="panel"> <div class="panel-heading"> <h2 class="panel-title"><?php print t('Link a risorse online di interesse specifico'); ?></h2> </div> <div class="panel-body"> <?php print render($content['field_link_a_risorse_online_di_i']); ?> </div> </div> <?php endif; ?> </div> </div> </div> </article>
ComuneBologna/comunita
sites/comunita/themes/comunita_theme/templates/node--bene-comune.tpl.php
PHP
gpl-2.0
3,768
<?php /* Simple class to let themes add dependencies on plugins in ways they might find useful Example usage: $test = new Theme_Plugin_Dependency( 'simple-facebook-connect', 'http://ottopress.com/wordpress-plugins/simple-facebook-connect/' ); if ( $test->check_active() ) echo 'SFC is installed and activated!'; else if ( $test->check() ) echo 'SFC is installed, but not activated. <a href="'.$test->activate_link().'">Click here to activate the plugin.</a>'; else if ( $install_link = $test->install_link() ) echo 'SFC is not installed. <a href="'.$install_link.'">Click here to install the plugin.</a>'; else echo 'SFC is not installed and could not be found in the Plugin Directory. Please install this plugin manually.'; */ if (!class_exists('Theme_Plugin_Dependency')) { class Theme_Plugin_Dependency { // input information from the theme var $slug; var $uri; // installed plugins and uris of them private $plugins; // holds the list of plugins and their info private $uris; // holds just the URIs for quick and easy searching // both slug and PluginURI are required for checking things function __construct( $slug, $uri ) { $this->slug = $slug; $this->uri = $uri; if ( empty( $this->plugins ) ) $this->plugins = get_plugins(); if ( empty( $this->uris ) ) $this->uris = wp_list_pluck($this->plugins, 'PluginURI'); // echo '<pre>'; // print_r($this->uris); // echo '</pre>'; } // return true if installed, false if not function check() { return in_array($this->uri, $this->uris); } // return true if installed and activated, false if not function check_active() { $plugin_file = $this->get_plugin_file(); if ($plugin_file) return is_plugin_active($plugin_file); return false; } // gives a link to activate the plugin function activate_link() { $plugin_file = $this->get_plugin_file(); if ($plugin_file) return wp_nonce_url(self_admin_url('plugins.php?action=activate&plugin='.$plugin_file), 'activate-plugin_'.$plugin_file); return false; } // return a nonced installation link for the plugin. checks wordpress.org to make sure it's there first. function install_link() { include_once ABSPATH . 'wp-admin/includes/plugin-install.php'; $info = plugins_api('plugin_information', array('slug' => $this->slug )); if ( is_wp_error( $info ) ) return false; // plugin not available from wordpress.org return wp_nonce_url(self_admin_url('update.php?action=install-plugin&plugin=' . $this->slug), 'install-plugin_' . $this->slug); } // return array key of plugin if installed, false if not, private because this isn't needed for themes, generally private function get_plugin_file() { return array_search($this->uri, $this->uris); } } } /** + * options "Add scripts to head" and "add scripts to footer" + * + * @package X2 + * @since 1.5 + */ // add to head function - hooks the stuff to bp_head function x2_cap_add_to_head() { global $cap; echo $cap->add_to_head; } add_action('bp_head', 'x2_cap_add_to_head', 20); // add to footer function - hooks the stuff to wp_footer function x2_cap_add_to_footer() { global $cap; echo $cap->add_to_footer; } add_action('wp_footer', 'x2_cap_add_to_footer', 20); function back_to_top(){ global $cap; //if($cap->menu_waypoints == true) { ?> <footer> <nav> <ul> <li><a class="top" href="#" title="Back to top">Top</a></li> </ul> </nav> </footer> <?php } //} function waypoints_js(){ global $cap; if($cap->menu_waypoints == true) { ?> <script type="text/javascript"> jQuery(document).ready(function() { jQuery('.top').addClass('hidden'); jQuery.waypoints.settings.scrollThrottle = 300; jQuery('#outerrim').waypoint(function(event, direction) { jQuery('.top').toggleClass('hidden', direction === "up"); }, { offset: '-100%' }).find('#access').waypoint(function(event, direction) { jQuery('#access').toggleClass('sticky', direction === "down"); if(direction == 'up'){ jQuery('#nav-logo').animate({ opacity: 1},0, function() { jQuery(this).hide('200'); }); jQuery(".wrapcheck").removeClass("inner"); } if(direction == 'down'){ jQuery('#nav-logo').animate({ opacity: 1},0, function() { jQuery(this).show('200'); }); jQuery(".wrapcheck").addClass("inner"); } event.stopPropagation(); }); }); </script> <?php } else { ?> <script type="text/javascript"> jQuery(document).ready(function() { jQuery('.top').addClass('hidden'); jQuery.waypoints.settings.scrollThrottle = 300; jQuery('#outerrim').waypoint(function(event, direction) { jQuery('.top').toggleClass('hidden', direction === "up"); }, { offset: '-100%' }) }); </script> <?php } } // this function adds the needed class "icon-white" if color scheme is dark or black.. function white_icon_class() { if ( x2_get_color_scheme() == 'dark' || x2_get_color_scheme() == 'black' ) { echo 'icon-white'; } } function add_home_to_nav(){ ?> <div id="nav-logo"> <ul> <li id="nav-home"<?php if ( is_home() ) : ?> class="page_item current-menu-item"<?php endif; ?>> <a href="<?php echo site_url() ?>" title="<?php _e( 'Home', 'x2' ) ?>"><i class="icon-home <?php white_icon_class() ?>"></i></a> </li> </ul> </div> <?php } // opens the inner wrap in the top menu - if needed function open_inner_wrap_in_menu_top() { global $cap; if( $cap->header_width == "full-width" || $cap->menu_top_stay_on_top == true ) echo "<div class=\"inner\">"; } // closes the inner wrap in the top menu - if needed function close_inner_wrap_in_menu_top() { global $cap; if( $cap->header_width == "full-width" || $cap->menu_top_stay_on_top == true ) echo "</div>"; } // the flying widget! function out_of_site_widget(){ global $cap; if($cap->out_of_content_widget == false) { ?> <script> var name = "#out_of_site_widget"; var menuYloc = null; jQuery(document).ready(function(){ menuYloc = parseInt(jQuery(name).css("top").substring(0,jQuery(name).css("top").indexOf("px"))) jQuery(window).scroll(function () { offset = menuYloc+jQuery(document).scrollTop()+"px"; jQuery(name).animate({top:offset},{duration:1000,queue:false}); }); }); </script> <?php } ?> <div id="out_of_site_widget" class=".visible-desktop"> <?php dynamic_sidebar( 'out_of_content' )?> </div> <?php } // body badge function, if the option is set function body_badge(){ global $cap; if ( $cap->body_badge_show != "hide" ) { // add a link around if a url is set if ( $cap->body_badge_link != "" ) { ?><a class="body_badge_link" href="<?php echo $cap->body_badge_link; ?>"><?php } // only the badge body will be added anyway ?><div class="badge_body"><?php // add the text only if something != "just my image" is set if ( $cap->body_badge_show != "just my image" ) { ?><div class="badge_text"><?php echo $cap->body_badge_text; ?></div><?php } // close the badge body anyway ?></div><?php // close the link around if a url was set if ( $cap->body_badge_link != "" ) { ?></a><?php } } } function get_the_post_thumbnail_src($img) { return (preg_match('~\bsrc="([^"]++)"~', $img, $matches)) ? $matches[1] : ''; } /** * check if it's a child theme or parent theme and return the correct path * * @package x2 * @since 1.0 */ function x2_require_path($path){ x2::require_path($path); } /** * get the right img for the slideshow shadow * * @package x2 * @since 1.0 */ function x2_slider_shadow() { global $cap; if ($cap->slideshow_shadow == "shadow") { return "slider-shadow.png"; } else { return "slider-shadow-sharp.png"; } } /** * define new excerpt length * * @package x2 * @since 1.0 */ function x2_excerpt_length() { global $cap; $excerpt_length = 30; if($cap->excerpt_length){ $excerpt_length = $cap->excerpt_length; } return $excerpt_length; } /** * change the profile tab order * * @package x2 * @since 1.0 */ add_action( 'bp_init', 'x2_change_profile_tab_order' ); function x2_change_profile_tab_order() { global $bp, $cap; if($cap->bp_profiles_nav_order == ''){ $cap->bp_default_navigation = true; return; } $order = $cap->bp_profiles_nav_order; $order = str_replace(' ','',trim($order)); $order = explode(",", $order); $i = 1; $bp->bp_nav = x2_filter_custom_menu($bp->bp_nav, $order); foreach($order as $item) { // check this such component actually exists if(!bp_is_active($item)){ continue; } $bp->bp_nav[$item]['position'] = $i; $i ++; } } /** * change the groups tab order * * @package x2 * @since 1.0 */ add_action('bp_init', 'x2_change_groups_tab_order'); function x2_change_groups_tab_order() { global $bp, $cap; // In BP 1.3, bp_options_nav for groups is keyed by group slug instead of by 'groups', to // differentiate it from the top-level groups directories and the groups subtab of member // profiles $group_slug = isset( $bp->groups->current_group->slug ) ? $bp->groups->current_group->slug : false; if($cap->bp_groups_nav_order == ''){ $cap->bp_default_navigation = true; return; } $order = $cap->bp_groups_nav_order; $order = str_replace(' ','',$order); $order = explode(",", $order); $i = 1; $bp->bp_options_nav[$group_slug] = x2_filter_custom_menu($bp->bp_options_nav[$group_slug], $order); if(!empty($bp->bp_options_nav[$group_slug])){ foreach($order as $item) { if(!array_key_exists($item, $bp->bp_options_nav[$group_slug])){ continue; } $bp->bp_options_nav[$group_slug][$item]['position'] = $i; $i ++; } } } /** * Remove menu items wihich not included to custom list * @param array $menu default menu * @param array $custom_items list of items * @return array new menu items */ function x2_filter_custom_menu($menu, $custom_items){ if(is_array($custom_items) && is_array($menu)){ return array_intersect_key($menu, array_flip($custom_items)); } return $menu; } /** * This function here defines the defaults for the main theme colors - if no other specific color is set ;) * It's used only one time - in the beginning of style.php. * * @package x2 * @since 0.1 */ function x2_switch_css(){ global $cap; if(isset( $_GET['show_style'])) $cap->style_css = $_GET['show_style']; switch ($cap->style_css){ case 'dark': if( $cap->bg_body_color == '' ) $cap->bg_body_color = '393939'; if( $cap->bg_container_color == '' ) $cap->bg_container_color = '393939'; if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = '232323'; if( $cap->bg_details_color == '' ) $cap->bg_details_color = '282828'; if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = '333333'; if( $cap->font_color == '' ) $cap->font_color = 'aaaaaa'; if( $cap->font_alt_color == '' ) $cap->font_alt_color = '777777'; if( $cap->link_color == '' ) $cap->link_color = 'b7c366'; break; case 'white': if( $cap->bg_body_color == '' ) $cap->bg_body_color = 'ffffff'; if( $cap->bg_container_color == '' ) $cap->bg_container_color = 'ffffff'; if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = 'e3e3e3'; if( $cap->bg_details_color == '' ) $cap->bg_details_color = 'f1f1f1'; if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = 'f9f9f9'; if( $cap->font_color == '' ) $cap->font_color = '777777'; if( $cap->font_alt_color == '' ) $cap->font_alt_color = 'aaaaaa'; if( $cap->link_color == '' ) $cap->link_color = '6ba090'; break; case 'black': if( $cap->bg_body_color == '' ) $cap->bg_body_color = '040404'; if( $cap->bg_container_color == '' ) $cap->bg_container_color = '040404'; if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = '222222'; if( $cap->bg_details_color == '' ) $cap->bg_details_color = '121212'; if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = '181818'; if( $cap->font_color == '' ) $cap->font_color = '696969'; if( $cap->font_alt_color == '' ) $cap->font_alt_color = '444444'; if( $cap->link_color == '' ) $cap->link_color = '2b9c83'; break; case 'light': if( $cap->bg_body_color == '' ) $cap->bg_body_color = 'f9f9f9'; if( $cap->bg_container_color == '' ) $cap->bg_container_color = 'f9f9f9'; if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = 'dedede'; if( $cap->bg_details_color == '' ) $cap->bg_details_color = 'e7e7e7'; if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = 'f1f1f1'; if( $cap->font_color == '' ) $cap->font_color = '777777'; if( $cap->font_alt_color == '' ) $cap->font_alt_color = 'aaaaaa'; if( $cap->link_color == '' ) $cap->link_color = '74a4a3'; break; case 'natural': if( $cap->bg_body_color == '' ) $cap->bg_body_color = 'e9e6d8'; if( $cap->bg_container_color == '' ) $cap->bg_container_color = 'e9e6d8'; if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = 'cec7ab'; if( $cap->bg_details_color == '' ) $cap->bg_details_color = 'dcd6bd'; if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = 'e3dec8'; if( $cap->font_color == '' ) $cap->font_color = '79735d'; if( $cap->font_alt_color == '' ) $cap->font_alt_color = '999177'; if( $cap->link_color == '' ) $cap->link_color = 'c3874a'; break; default: if( $cap->bg_body_color == '' ) $cap->bg_body_color = 'f9f9f9'; if( $cap->bg_container_color == '' ) $cap->bg_container_color = 'f9f9f9'; if( $cap->bg_container_alt_color == '' ) $cap->bg_container_alt_color = 'dedede'; if( $cap->bg_details_color == '' ) $cap->bg_details_color = 'e7e7e7'; if( $cap->bg_details_hover_color == '' ) $cap->bg_details_hover_color = 'f1f1f1'; if( $cap->font_color == '' ) $cap->font_color = '777777'; if( $cap->font_alt_color == '' ) $cap->font_alt_color = 'aaaaaa'; if( $cap->link_color == '' ) $cap->link_color = '74a4a3'; break; } return TRUE; } /** * find out the right color scheme and create the array of css elements with the hex codes * * @package x2 * @since 1.0 */ function x2_color_scheme(){ echo x2_get_color_scheme(); } function x2_get_color_scheme(){ global $cap; if(isset( $_GET['show_style'])) $cap->style_css = $_GET['show_style']; switch ($cap->style_css){ case 'dark': $color = 'dark'; break; case 'light': $color = 'light'; break; case 'white': $color = 'white'; break; case 'black': $color = 'black'; break; case 'natural': $color = 'natural'; break; default: $color = 'white'; break; } return $color; } function x2_the_loop( $template, $tk_query_id, $show_pagination){ switch ($template) { case 'default': get_template_part( 'loop-default' ); break; case 'bubble': get_template_part( 'loop-bubbles' ); break; case 'image_caption': get_template_part( 'loop-featured-image-caption' ); break; default: if(function_exists('tk_loop_designer_the_loop')){ tk_loop_designer_the_loop( $template, $tk_query_id, $show_pagination ); } else { get_template_part( 'loop-default' ); } break; } } ?>
jubjunior/Wordpress
wp-content/themes/x2/core/includes/helper-functions.php
PHP
gpl-2.0
16,806
<?php get_header(); ?> <?php $options = get_option('sf_dante_options'); $default_show_page_heading = $options['default_show_page_heading']; $default_page_heading_bg_alt = $options['default_page_heading_bg_alt']; $default_sidebar_config = $options['default_sidebar_config']; $default_left_sidebar = $options['default_left_sidebar']; $default_right_sidebar = $options['default_right_sidebar']; $pb_active = get_post_meta($post->ID, '_spb_js_status', true); $show_page_title = get_post_meta($post->ID, 'sf_page_title', true); $page_title_style = get_post_meta($post->ID, 'sf_page_title_style', true); $page_title = get_post_meta($post->ID, 'sf_page_title_one', true); $page_subtitle = get_post_meta($post->ID, 'sf_page_subtitle', true); $page_title_bg = get_post_meta($post->ID, 'sf_page_title_bg', true); $fancy_title_image = rwmb_meta('sf_page_title_image', 'type=image&size=full'); $page_title_text_style = get_post_meta($post->ID, 'sf_page_title_text_style', true); $fancy_title_image_url = ""; if ($show_page_title == "") { $show_page_title = $default_show_page_heading; } if ($page_title_bg == "") { $page_title_bg = $default_page_heading_bg_alt; } if ($page_title == "") { $page_title = get_the_title(); } foreach ($fancy_title_image as $detail_image) { $fancy_title_image_url = $detail_image['url']; break; } if (!$fancy_title_image) { $fancy_title_image = get_post_thumbnail_id(); $fancy_title_image_url = wp_get_attachment_url( $fancy_title_image, 'full' ); } $sidebar_config = get_post_meta($post->ID, 'sf_sidebar_config', true); $left_sidebar = get_post_meta($post->ID, 'sf_left_sidebar', true); $right_sidebar = get_post_meta($post->ID, 'sf_right_sidebar', true); if ($sidebar_config == "") { $sidebar_config = $default_sidebar_config; } if ($left_sidebar == "") { $left_sidebar = $default_left_sidebar; } if ($right_sidebar == "") { $right_sidebar = $default_right_sidebar; } sf_set_sidebar_global($sidebar_config); $page_wrap_class = $post_class_extra = ''; if ($sidebar_config == "left-sidebar") { $page_wrap_class = 'has-left-sidebar has-one-sidebar row'; $post_class_extra = 'col-sm-8'; } else if ($sidebar_config == "right-sidebar") { $page_wrap_class = 'has-right-sidebar has-one-sidebar row'; $post_class_extra = 'col-sm-8'; } else if ($sidebar_config == "both-sidebars") { $page_wrap_class = 'has-both-sidebars row'; $post_class_extra = 'col-sm-9'; } else { $page_wrap_class = 'has-no-sidebar'; } $remove_breadcrumbs = get_post_meta($post->ID, 'sf_no_breadcrumbs', true); $remove_bottom_spacing = get_post_meta($post->ID, 'sf_no_bottom_spacing', true); $remove_top_spacing = get_post_meta($post->ID, 'sf_no_top_spacing', true); if ($remove_bottom_spacing) { $page_wrap_class .= ' no-bottom-spacing'; } if ($remove_top_spacing) { $page_wrap_class .= ' no-top-spacing'; } $options = get_option('sf_dante_options'); $disable_pagecomments = false; if (isset($options['disable_pagecomments']) && $options['disable_pagecomments'] == 1) { $disable_pagecomments = true; } ?> <?php if ($show_page_title) { ?> <div class="container"> <div class="row"> <?php if ($page_title_style == "fancy") { ?> <?php if ($fancy_title_image_url != "") { ?> <div class="page-heading fancy-heading col-sm-12 clearfix alt-bg <?php echo $page_title_text_style; ?>-style fancy-image" style="background-image: url(<?php echo $fancy_title_image_url; ?>);"> <?php } else { ?> <div class="page-heading fancy-heading col-sm-12 clearfix alt-bg <?php echo $page_title_bg; ?>"> <?php } ?> <div class="heading-text"> <h1 class="entry-title"><?php echo $page_title; ?></h1> <?php if ($page_subtitle) { ?> <h3><?php echo $page_subtitle; ?></h3> <?php } ?> </div> </div> <?php } else { ?> <div class="page-heading col-sm-12 clearfix alt-bg <?php echo $page_title_bg; ?>"> <div class="heading-text"> <h1 class="entry-title"><?php echo $page_title; ?></h1> </div> <?php // BREADCRUMBS if (!$remove_breadcrumbs) { echo sf_breadcrumbs(); } ?> </div> <?php } ?> </div> </div> <?php } ?> <?php if ($sidebar_config != "no-sidebars" || $pb_active != "true") { ?> <div class="container"> <?php } ?> <div class="inner-page-wrap <?php echo $page_wrap_class; ?> clearfix"> <?php if (have_posts()) : the_post(); ?> <!-- OPEN page --> <div <?php post_class('clearfix ' . $post_class_extra); ?> id="<?php the_ID(); ?>"> <?php if ($sidebar_config == "both-sidebars") { ?> <div class="row"> <div class="page-content col-sm-8"> <?php the_content(); ?> <div class="link-pages"><?php wp_link_pages(); ?></div> <?php if ( comments_open() && !$disable_pagecomments ) { ?> <div id="comment-area"> <?php comments_template('', true); ?> </div> <?php } ?> </div> <aside class="sidebar left-sidebar col-sm-4"> <?php dynamic_sidebar($left_sidebar); ?> </aside> </div> <?php } else { ?> <div class="page-content clearfix"> <?php the_content(); ?> <div class="link-pages"><?php wp_link_pages(); ?></div> <?php if ( comments_open() && !$disable_pagecomments ) { ?> <?php if ($sidebar_config == "no-sidebars" && $pb_active == "true") { ?> <div id="comment-area" class="container"> <?php } else { ?> <div id="comment-area"> <?php } ?> <?php comments_template('', true); ?> </div> <?php } ?> </div> <?php } ?> <!-- CLOSE page --> </div> <?php endif; ?> <?php if ($sidebar_config == "left-sidebar") { ?> <aside class="sidebar left-sidebar col-sm-4"> <?php dynamic_sidebar($left_sidebar); ?> </aside> <?php } else if ($sidebar_config == "right-sidebar") { ?> <aside class="sidebar right-sidebar col-sm-4"> <?php dynamic_sidebar($right_sidebar); ?> </aside> <?php } else if ($sidebar_config == "both-sidebars") { ?> <aside class="sidebar right-sidebar col-sm-3"> <?php dynamic_sidebar($right_sidebar); ?> </aside> <?php } ?> </div> <?php if ($sidebar_config != "no-sidebars" || $pb_active != "true") { ?> </div> <?php } ?> <!--// WordPress Hook //--> <?php get_footer(); ?>
roycocup/enclothed
wp-content/themes/dante/page.php
PHP
gpl-2.0
6,214
<?php /** * TOP API: taobao.traderates.search request * * @author auto create * @since 1.0, 2012-03-21 12:35:10 */ class TraderatesSearchRequest { /** * 商品的数字id **/ private $numIid; /** * 当前页 **/ private $pageNo; /** * 每页显示的条数,允许值:5、10、20、40 **/ private $pageSize; /** * 商品所属的卖家nick **/ private $sellerNick; private $apiParas = array(); public function setNumIid($numIid) { $this->numIid = $numIid; $this->apiParas["num_iid"] = $numIid; } public function getNumIid() { return $this->numIid; } public function setPageNo($pageNo) { $this->pageNo = $pageNo; $this->apiParas["page_no"] = $pageNo; } public function getPageNo() { return $this->pageNo; } public function setPageSize($pageSize) { $this->pageSize = $pageSize; $this->apiParas["page_size"] = $pageSize; } public function getPageSize() { return $this->pageSize; } public function setSellerNick($sellerNick) { $this->sellerNick = $sellerNick; $this->apiParas["seller_nick"] = $sellerNick; } public function getSellerNick() { return $this->sellerNick; } public function getApiMethodName() { return "taobao.traderates.search"; } public function getApiParas() { return $this->apiParas; } public function check() { RequestCheckUtil::checkNotNull($this->numIid,"numIid"); RequestCheckUtil::checkMinValue($this->pageNo,1,"pageNo"); RequestCheckUtil::checkMaxValue($this->pageSize,40,"pageSize"); RequestCheckUtil::checkMinValue($this->pageSize,1,"pageSize"); RequestCheckUtil::checkNotNull($this->sellerNick,"sellerNick"); RequestCheckUtil::checkMaxLength($this->sellerNick,32,"sellerNick"); } }
gxk9933/guoxk-blog
html/test_taobaoke/sdk/top/request/TraderatesSearchRequest.php
PHP
gpl-2.0
1,739
// // FrameSpec.cpp // Messaging // // Created by Dave Meehan on 21/04/2014. // Copyright (c) 2014 Replicated Solutions Limited. All rights reserved. // #include <ZingBDD/ZingBDD.h> #include "Frame.h" #include <string.h> namespace Messaging { namespace Specs { describe(Frame, { context("default constructor", { Frame frame; context("size", { it("has size of zero", { expect(frame.size()).should.equal(0); }); }); }); context("size constructor", { size_t expectedSize = 64; Frame frame(expectedSize); it("has expected size", { expect(frame.size()).should.equal(expectedSize); }); }); context("string constructor", { char expectedData[] = "this is a test"; Frame frame(expectedData); it("has expected size", { expect(strlen(frame.data<char>())).should.equal(strlen(expectedData)); }); it("has expected data", { expect(strcmp(frame.data<char>(), expectedData)).should.equal(0); }); }); context("transmission", { Context ctx; Socket client(ctx, Socket::Type::request); Socket server(ctx, Socket::Type::reply); server.bind("inproc://test"); client.connect("inproc://test"); it("can send and receive", { char expectedData[] = "this is a test"; Frame outbound(expectedData); outbound.send(client, Frame::block::none, Frame::more::none); Frame inbound; inbound.receive(server, Frame::block::none); expect(strcmp(inbound.data<char>(), expectedData)).should.equal(0); }); }); }); } }
dmeehan1968/Playground
Messaging/Tests/FrameSpec.cpp
C++
gpl-2.0
2,391
<hr> <footer> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <ul class="list-inline text-center"> <li> <a href="#"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-twitter fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a href="#"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-facebook fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a href="#"> <span class="fa-stack fa-lg"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-github fa-stack-1x fa-inverse"></i> </span> </a> </li> </ul> <p class="copyright text-muted">Copyright &copy; Your Website 2014</p> </div> </div> </div> </footer>
manishkiozen/WebCms
resources/views/blog/includes/footer.blade.php
PHP
gpl-2.0
1,468
# These are some tools I am creating to help me build the map for the game. They are a work in progress. # I am also learning python, so I apologize in advance if I do dumb things. # Right now this consists of just two classes: locations and coordinate systems. # As I have it implemented here, a coordinate system is simply a group of locations. # I'm sure there is more I could do, for instance linking a coordinate system to a location so that # you could, for example, enter a house (a location on a larger map) and get a coordinate system # for more detailed movement inside the house. Right now this is very possible to do, # but it has to be implemented outside of the class. import array import os import sys class location: farDesc = "" # For Descriptions of locations from far away nearDesc = "" # For descriptions of locations from close-up name = "" items = [] # I am investigating this, but apparently you can't use the "append" function with items and characters # when there is an array of locations, i.e. a coordSystem locationArray. Don't know why this is. characters = [] has_nEntrance = True has_eEntrance = True has_sEntrance = True has_wEntrance = True has_uEntrance = True has_dEntrance = True isCoordSys = False def __init__(self): self.farDesc = "" self.nearDesc = "" self.name = "" self.items = [] self.characters = [] self.isCoordSys = False # save time so that we don't have to check for a matching coordSys for every # single location class coordSystem: name = "" xMax = 0 yMax = 0 zMax = 0 _locationArray = [] # I have it as a "private variable" (as far as they exist in Python) to avoid confusion: # as the implementation stands, you have to access the array in the order of [z][y][x], but # most people are used to the opposite ordering. Rather than screw around with naming and # perhaps add confusion, I want people to only ever access the array by get and set methods. def getLocation(self, x, y, z): return self._locationArray[z][y][x] def __init__(self, name, xMax, yMax, zMax): self.name = name self.xMax = xMax self.yMax = yMax self.zMax = zMax self._locationArray = [[[location() for x in range(xMax)] for x in range(yMax)] for x in range(zMax)] #The above line is weird, but I can't think of a better way to initialize an array of arrays
nickdab/pygame
maptools.py
Python
gpl-2.0
2,622
''' This file is part of the lenstractor project. Copyright 2012 David W. Hogg (NYU) and Phil Marshall (Oxford). Description ----------- Wrapper class for tractor operation, to enable high level options (ie sampling or optimization). To-do ----- - debug, test ''' import numpy as np import os,subprocess import tractor import lenstractor import emcee emcee_defaults = {} import pylab as plt # ============================================================================ class LensTractor(): ''' PURPOSE Optimize or sample a Lens or Nebula model using the Tractor. COMMENTS INPUTS data A list of tractor.images model A model (including a list of tractor.sources) by A mode of operation ['optimizing','sampling'] using The required settings survey The name of the survey being worked on plot Make plots if desired OUTPUTS BUGS HISTORY 2014-04-17 Started Marshall & Agnello (UCSB) ''' # ---------------------------------------------------------------------------- def __init__(self,dataset,model,outstem,survey,counter=0,vb=0,noplots=True): self.name = 'LensTractor' self.survey = survey self.settings = {} # Optimization settings: # self.settings['Nrounds'] = 5 # self.settings['Nsteps_optimizing_catalog'] = 100 # self.settings['Nsteps_optimizing_PSFs'] = 2 # Sampling settings: self.settings['Nwalkers_per_dim'] = 8 self.settings['Nsnapshots'] = 3 self.settings['Nsteps_per_snapshot'] = 5000 self.settings['Restart'] = True self.model = model self.vb = vb self.noplots = noplots self.plot_all = True self.outstem = outstem.split('.')[0] self.bestpars = None self.maxlnp = None self.minchisq = None self.psteps = None self.counter = counter # self.chug = tractor.Tractor(dataset) self.chug = lenstractor.Trattore(dataset) for src in self.model.srcs: self.chug.addSource(src) # Freeze the PSFs, wcs and photocal, leaving the sky and sources: self.chug.thawParam('catalog') for image in self.chug.getImages(): image.thawParams('sky') image.freezeParams('photocal') image.freezeParams('wcs') image.freezeParams('psf') # Plot initial state: if not self.noplots: self.plot_state('progress-%02d_initial_'%self.counter+self.model.name) return None # ---------------------------------------------------------------------------- # Drive the LensTractor. We have both steepest ascent and MCMC capability. # Try a mixture! def drive(self,by='cunning_and_guile'): self.method = by if self.method == 'sampling': self.sample() elif self.method == 'optimizing': if self.model.flavor == 'Nebula': # First optimize to get the Nebula model about right, at fixed PSF: self.settings['Nrounds'] = 2 self.settings['Nsteps_optimizing_catalog'] = 100000 self.settings['Nsteps_optimizing_PSFs'] = 0 self.optimize() # Now optimize PSF at fixed model: self.settings['Nrounds'] = 1 self.settings['Nsteps_optimizing_catalog'] = 0 self.settings['Nsteps_optimizing_PSFs'] = 2 self.optimize() # Refine Nebula model at best PSF: self.settings['Nrounds'] = 2 self.settings['Nsteps_optimizing_catalog'] = 10000 self.settings['Nsteps_optimizing_PSFs'] = 0 self.optimize() elif self.model.flavor == 'Lens': # PSF is already optimized, during Nebula run. # Just do the lens part: self.settings['Nrounds'] = 2 self.settings['Nsteps_optimizing_catalog'] = 10000 self.settings['Nsteps_optimizing_PSFs'] = 0 self.optimize() else: # Apply cunning and guile! Both optimization and sampling. # First optimize to get the fluxes about right: self.settings['Nrounds'] = 1 self.settings['Nsteps_optimizing_catalog'] = 100000 self.settings['Nsteps_optimizing_PSFs'] = 0 self.optimize() # Now optimize PSF at fixed model: self.settings['Nrounds'] = 1 self.settings['Nsteps_optimizing_catalog'] = 0 self.settings['Nsteps_optimizing_PSFs'] = 2 self.optimize() self.settings['Nrounds'] = 1 self.settings['Nsteps_optimizing_catalog'] = 10000 self.settings['Nsteps_optimizing_PSFs'] = 0 self.optimize() # Now draw a few samples to shuffle the positions: self.settings['Nsnapshots'] = 1 self.settings['Nwalkers_per_dim'] = 4 self.settings['Nsteps_per_snapshot'] = 2500 self.settings['Restart'] = True self.sample() # Now optimize to refine model and PSF: self.settings['Nrounds'] = 1 self.settings['Nsteps_optimizing_catalog'] = 50000 self.settings['Nsteps_optimizing_PSFs'] = 0 self.optimize() self.settings['Nrounds'] = 1 self.settings['Nsteps_optimizing_catalog'] = 0 self.settings['Nsteps_optimizing_PSFs'] = 2 self.optimize() self.settings['Nrounds'] = 1 self.settings['Nsteps_optimizing_catalog'] = 10000 self.settings['Nsteps_optimizing_PSFs'] = 0 self.optimize() self.getBIC() return None # ---------------------------------------------------------------------------- # Fit the model to the image data by maximizing the posterior PDF # ("optimizing") with respect to the parameters. def optimize(self): Nrounds = self.settings['Nrounds'] Nsteps_optimizing_catalog = self.settings['Nsteps_optimizing_catalog'] Nsteps_optimizing_PSFs = self.settings['Nsteps_optimizing_PSFs'] if self.vb: print " " print "Optimizing model:" print " - no. of iterations per round to be spent on catalog: ",Nsteps_optimizing_catalog print " - no. of iterations per round to be spent on PSFs: ",Nsteps_optimizing_PSFs print " - no. of rounds: ",Nrounds for round in range(Nrounds): self.counter += 1 if self.vb: print "Fitting "+self.model.name+": seconds out, round",round if self.vb: print "Fitting "+self.model.name+": Catalog parameters to be optimized are:",self.chug.getParamNames() print "Fitting "+self.model.name+": Initial values are:",self.chug.getParams() print "Fitting "+self.model.name+": Step sizes:",self.chug.getStepSizes() # Optimize sources: for i in range(Nsteps_optimizing_catalog): dlnp,X,a = self.chug.optimize(damp=3,shared_params=False) # print "Fitting "+self.model.name+": at step",k,"parameter values are:",self.chug.getParams() if self.vb: print "Progress: counter,dlnp = ",self.counter,dlnp print "" print "Catalog parameters:",self.chug.getParamNames() print "Catalog values:",self.chug.getParams() if dlnp == 0: print "Converged? Exiting..." # Although this only leaves *this* loop... break if not self.noplots: self.plot_state('progress-%02d_optimizing_'%self.counter+self.model.name) if Nsteps_optimizing_PSFs > 0: # Freeze the sources and calibration, and thaw the psfs: if self.vb: print "Freezing catalog..." self.chug.freezeParams('catalog') for image in self.chug.getImages(): if self.vb: print "Thawing PSF..." image.thawParams('psf') if self.vb: print "Freezing photocal, WCS, sky (just to make sure...)" image.freezeParams('photocal', 'wcs', 'sky') if self.vb: print "Fitting PSF: After thawing, zeroth PSF = ",self.chug.getImage(0).psf print "Fitting PSF: PSF parameters to be optimized are:",self.chug.getParamNames() print "Fitting PSF: Initial values are:",self.chug.getParams() print "Fitting PSF: Step sizes:",self.chug.getStepSizes() # Optimize everything that is not frozen: for i in range(Nsteps_optimizing_PSFs): dlnp,X,a = self.chug.optimize(shared_params=False) if self.vb: print "Fitting PSF: at counter =",self.counter,"parameter values are:",self.chug.getParams() self.counter += 1 if self.vb: print "Fitting PSF: After optimizing, zeroth PSF = ",self.chug.getImage(0).psf if not self.noplots: self.plot_state( 'progress-%02d_optimizing_PSF_for_'%self.counter+self.model.name) # Freeze the psf again, and thaw the sources: if self.vb: print "Re-thawing catalog..." self.chug.thawParams('catalog') for image in self.chug.getImages(): if self.vb: print "Re-freezing PSF..." image.freezeParams('psf') if self.vb: print "Re-freezing photocal, WCS, sky (just to make sure...)" image.freezeParams('photocal', 'wcs', 'sky') # Save the best parameters! self.maxlnp = self.chug.getLogProb() self.bestpars = self.chug.getParams() if self.vb: print "Optimizer: Best parameters: ",self.maxlnp,self.bestpars self.minchisq = -2.0*self.chug.getLogLikelihood() if self.vb: print "Optimizer: chisq at highest lnprob point: ",self.minchisq return None # ---------------------------------------------------------------------------- # Fit the model to the image data by drawing samples from the posterior PDF # that have high probability density: note, this is not really sampling, # its *sampling to optimize*... def sample(self): if self.vb: print "Sampling model parameters with Emcee:" # Magic numbers: Nwalkers_per_dim = self.settings['Nwalkers_per_dim'] Nsnapshots = self.settings['Nsnapshots'] Nsteps_per_snapshot = self.settings['Nsteps_per_snapshot'] Restart = self.settings['Restart'] # Get the thawed parameters: p0 = np.array(self.chug.getParams()) if self.vb: print 'Tractor parameters:' for i,parname in enumerate(self.chug.getParamNames()): print ' ', parname, '=', p0[i] Ndim = len(p0) if self.vb: print 'Number of parameter space dimensions: ',Ndim # Make an emcee sampler that uses our tractor to compute its logprob: Nw = Nwalkers_per_dim*Ndim # 8*ndim sampler = emcee.EnsembleSampler(Nw, Ndim, self.chug, threads=4) # Start the walkers off near the initialisation point - # We need it to be ~1 pixel in position, and not too much # flux restriction... But use any psteps we already have! if self.psteps is None: if self.model.name=='Lens': # The following gets us 0.05" in dec: self.psteps = np.zeros_like(p0) + 0.00001 # This could be optimized, to allow more initial freedom in eg flux. else: # Good first guess should be some fraction of the optimization step sizes: self.psteps = 0.01*np.array(self.chug.getStepSizes()) if self.vb: print "Initial size (in each dimension) of sample ball = ",self.psteps #pp = emcee.EnsembleSampler.sampleBall(p0, self.psteps, Nw) pp = emcee.utils.sample_ball(p0, self.psteps, Nw) rstate = None lnp = None # Take a few steps - memory leaks fast! (~10Mb per sec) for snapshot in range(1,Nsnapshots+1): self.counter += 1 if self.vb: print 'Emcee: MCMC snapshot:', snapshot t0 = tractor.Time() pp,lnp,rstate = sampler.run_mcmc(pp, Nsteps_per_snapshot, lnprob0=lnp, rstate0=rstate) if self.vb: print 'Emcee: Mean acceptance fraction after', sampler.iterations, 'iterations =',np.mean(sampler.acceptance_fraction) t_mcmc = (tractor.Time() - t0) if self.vb: print 'Emcee: Runtime:', t_mcmc # Find the current best sample, and sample ball: self.maxlnp = np.max(lnp) best = np.where(lnp == self.maxlnp) self.bestpars = np.ravel(pp[best,:]) if self.vb: print "Emcee: Best parameters: ",self.maxlnp,self.bestpars self.minchisq = -2.0*self.chug.getLogLikelihood() if self.vb: print "Emcee: chisq at highest lnprob point: ",self.minchisq if not self.noplots: self.chug.setParams(self.bestpars) self.plot_state('progress-%02d_sampling_'%self.counter+self.model.name) if Restart: # Make a new sample ball centred on the current best point, # and with width given by the standard deviations in each # dimension: self.chug.setParams(self.bestpars) p0 = np.array(self.chug.getParams()) self.psteps = np.std(pp,axis=0) # pp = emcee.EnsembleSampler.sampleBall(p0, self.psteps, Nw) pp = emcee.utils.sample_ball(p0, self.psteps, Nw) rstate = None lnp = None if self.vb: print 'Emcee: total run time', t_mcmc, 'sec' return None # ---------------------------------------------------------------------------- def getBIC(self): self.K = len(self.bestpars) self.N = self.chug.getNdata() self.BIC = self.minchisq + self.K*np.log(1.0*self.N) return self.BIC # ---------------------------------------------------------------------------- def write_catalog(self): # Get parameter names and values: parnames = self.chug.getParamNames() values = np.array(np.outer(1,self.bestpars)) # Get image names: imgnames = [] for image in self.chug.getImages(): imgnames.append(image.name) # Set catalog file name: outfile = self.outstem+'_'+self.model.name+'.cat' # Open up a new file, over-writing any old one: try: os.remove(outfile) except OSError: pass output = open(outfile,'w') # Write header: hdr = [] hdr.append('# LensTractor output parameter catalog') # hdr.append('# ') # hdr.append('# Date: %s' % datestring) hdr.append('# ') hdr.append('# Model: %s' % self.model.name) hdr.append('# Notes:') hdr.append('# * First source is always the galaxy, point sources follow') for ii,imgname in enumerate(imgnames): hdr.append('# * images.image%d = %s' % (ii,imgname)) hdr.append('# ') # Last line contains the parameter names: nameline = "# " for name in parnames: nameline += name+" " hdr.append(nameline) # Write to file: for line in hdr: output.write("%s\n" % line) # Close file: output.close() np.savetxt('junk', values) cat = subprocess.call("cat junk >> " + outfile, shell=True) rm = subprocess.call("rm junk", shell=True) if cat != 0 or rm != 0: print "Error: write subprocesses failed in some way :-/" sys.exit() return outfile # ---------------------------------------------------------------------------- def set_cookie(self,outstem,result): outfile = self.outstem+'_result.cookie' # Open up a new file, over-writing any old one: try: os.remove(outfile) except OSError: pass output = open(outfile,'w') # Write result to file: output.write("%s\n" % result) # Close file: output.close() return outfile # ---------------------------------------------------------------------------- # Plot progress. def plot_state(self,suffix): ''' Make all the plots we need to assess the state of the LensTractor. Mainly, a multi-panel figure of image, synthetic image and chi, for each image being modelled. self.chug is a Tractor object, containing a list of images. ''' if self.plot_all: # Make one giant plot with all progress panels on it, and # save it to PNG: # Plotting setup: px,py = 4,len(self.chug.images) figprops = dict(figsize=(5*px,5*py), dpi=128) adjustprops = dict(\ left=0.05,\ bottom=0.05,\ right=0.95,\ top=0.95,\ wspace=0.1,\ hspace=0.1) # Start the plot: fig = plt.figure(**figprops) fig.subplots_adjust(**adjustprops) plt.clf() plt.gray() counter = 0 # Name the plot file: pngfile = self.outstem+'_'+suffix+'.png' else: # Make one plot per image, and save each to PNG. # Plotting setup: px,py = 2,2 figprops = dict(figsize=(5*px,5*py), dpi=128) adjustprops = dict(\ left=0.05,\ bottom=0.05,\ right=0.95,\ top=0.95,\ wspace=0.1,\ hspace=0.1) # Loop over images, making plots: for i,image in enumerate(self.chug.images): if image.name is None: imname = suffix+str(i) else: imname = image.name chi = self.chug.getChiImage(i) if self.survey == 'PS1': ima, chia, psfa = lenstractor.PS1_imshow_settings(image,chi) elif self.survey == 'KIDS': ima, chia, psfa = lenstractor.KIDS_imshow_settings(image,chi) else: # Do the same as for PS1 scale = np.sqrt(np.median(1.0/image.invvar[image.invvar > 0.0])) ima = dict(interpolation='nearest', origin='lower', vmin=-100.*scale, vmax=3.*scale) chia = dict(interpolation='nearest', origin='lower', vmin=-5., vmax=5.) psfa = dict(interpolation='nearest', origin='lower') if not self.plot_all: # Start a new plot: fig = plt.figure(**figprops) fig.subplots_adjust(**adjustprops) plt.clf() plt.gray() counter = 0 # 1) Data Image counter += 1 plt.subplot(py,px,counter) plt.imshow(-image.data, **ima) self.tidyup_plot() plt.title('Observed image') # Overlay image filter in lower left corner plt.text(1,1,image.photocal.bandname+'-band') # Figure out how to get this in bottom right hand corner instead # 2) Predicted image counter += 1 plt.subplot(py,px,counter) model = self.chug.getModelImages()[i] plt.imshow(-model, **ima) self.tidyup_plot() # Overlay cartoon of model: self.model.plot(image.wcs,image.photocal.bandname) plt.title('Predicted image') # Overlay name of model in lower left corner plt.text(1,1,self.model.name) # Figure out how to get this in top left hand corner instead # 3) Normalised residual counter += 1 plt.subplot(py,px,counter) plt.imshow(-chi, **chia) self.tidyup_plot() if self.survey == 'KIDS': # It is not clear why the residual image is not in units of # sigma. Perhaps this causes problems in the modelling. # This code is not refactored into kids.py since it should # not be necessary in the first place. plt.title('Residuals (flexible scale)') else: plt.title('Residuals ($\pm 5\sigma$)') # Overlay quantified goodness of fit, in sigma from acceptable... # TBI! # 4) PSF image counter += 1 plt.subplot(py,px,counter) psfimage = image.psf.getPointSourcePatch(*model.shape).patch plt.imshow(-psfimage, **psfa) self.tidyup_plot() plt.title('PSF') if not self.plot_all: # Save this image's plot: pngfile = imname+'_'+suffix+'.png' plt.savefig(pngfile) if self.vb: print "Progress snapshot saved to "+pngfile if self.plot_all: # Save the giant plot: plt.savefig(pngfile) if self.vb: print "Progress snapshot saved to "+pngfile return # ---------------------------------------------------------------------------- # Turn off the axis ticks and labels: def tidyup_plot(self): ax = plt.gca() ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) return # ============================================================================ if __name__ == '__main__': pass
davidwhogg/LensTractor
lenstractor/driver.py
Python
gpl-2.0
21,961
<?php /** * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; under version 2 * of the License (non-upgradable). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright (c) 2015 (original work) Open Assessment Technologies SA; * * */ namespace oat\tao\model\requiredAction\implementation; use oat\tao\model\requiredAction\RequiredActionAbstract; use oat\tao\model\routing\FlowController; /** * Class RequiredAction * * RequiredAction is action which should be executed by user before performing any activities in the TAO * * @package oat\tao\model\requiredAction\implementation */ class RequiredActionRedirectUrlPart extends RequiredActionAbstract { /** * Route to be ignored * * @var array */ protected $excludedRoutes = [ [ 'extension' => 'tao', 'module' => 'ClientConfig', 'action' => 'config', ] ]; /** * Array of url parts * * @var array */ protected $url; /** * RequiredActionRedirectUrlPart constructor. * @param string $name * @param array $rules * @param array $url */ public function __construct($name, array $rules, array $url) { parent::__construct($name, $rules); $this->url = $url; } /** * Execute an action * * @param array $params * @return string The callback url */ public function execute(array $params = []) { $context = \Context::getInstance(); $excludedRoutes = $this->getExcludedRoutes(); $currentRoute = [ 'extension' => $context->getExtensionName(), 'module' => $context->getModuleName(), 'action' => $context->getActionName(), ]; if (! in_array($currentRoute, $excludedRoutes)) { $currentUrl = \common_http_Request::currentRequest()->getUrl(); $transformedUrl = $this->getTransformedUrl($params); $url = $transformedUrl . (parse_url($transformedUrl, PHP_URL_QUERY) ? '&' : '?') . 'return_url=' . urlencode($currentUrl); $flowController = new FlowController(); $flowController->redirect($url); } } /** * @see \oat\oatbox\PhpSerializable::__toPhpCode() */ public function __toPhpCode() { $class = get_class($this); $name = $this->name; $rules = \common_Utils::toHumanReadablePhpString($this->getRules()); $url = \common_Utils::toHumanReadablePhpString($this->url); return "new $class( '$name', $rules, $url )"; } /** * Get url string from $this->url * * @param array $params * @return string */ protected function getTransformedUrl(array $params = []) { return call_user_func_array('_url', array_merge($this->url, [$params])); } /** * Some actions should not be redirected (such as retrieving requireJs config) * * @return array */ protected function getExcludedRoutes() { $result = $this->excludedRoutes; $resolver = new \Resolver($this->getTransformedUrl()); $result[] = [ 'extension' => $resolver->getExtensionFromURL(), 'module' => $resolver->getModule(), 'action' => $resolver->getAction(), ]; return $result; } }
oat-sa/tao-core
models/classes/requiredAction/implementation/RequiredActionRedirectUrlPart.php
PHP
gpl-2.0
3,945
/** */ package components.provider; import components.Association; import components.ComponentsPackage; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IEditingDomainItemProvider; import org.eclipse.emf.edit.provider.IItemLabelProvider; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.IItemPropertySource; import org.eclipse.emf.edit.provider.IStructuredItemContentProvider; import org.eclipse.emf.edit.provider.ITreeItemContentProvider; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ViewerNotification; /** * This is the item provider adapter for a {@link components.Association} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class AssociationItemProvider extends ClassifierItemProvider implements IEditingDomainItemProvider, IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public AssociationItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addTargetPropertyDescriptor(object); addSourcePropertyDescriptor(object); addLowerBoundPropertyDescriptor(object); addUpperBoundPropertyDescriptor(object); } return itemPropertyDescriptors; } /** * This adds a property descriptor for the Target feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addTargetPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Association_target_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Association_target_feature", "_UI_Association_type"), ComponentsPackage.Literals.ASSOCIATION__TARGET, true, false, true, null, null, null)); } /** * This adds a property descriptor for the Source feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addSourcePropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Association_source_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Association_source_feature", "_UI_Association_type"), ComponentsPackage.Literals.ASSOCIATION__SOURCE, true, false, true, null, null, null)); } /** * This adds a property descriptor for the Lower Bound feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addLowerBoundPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Association_lowerBound_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Association_lowerBound_feature", "_UI_Association_type"), ComponentsPackage.Literals.ASSOCIATION__LOWER_BOUND, true, false, false, ItemPropertyDescriptor.INTEGRAL_VALUE_IMAGE, null, null)); } /** * This adds a property descriptor for the Upper Bound feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addUpperBoundPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_Association_upperBound_feature"), getString("_UI_PropertyDescriptor_description", "_UI_Association_upperBound_feature", "_UI_Association_type"), ComponentsPackage.Literals.ASSOCIATION__UPPER_BOUND, true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } /** * This returns Association.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/Association")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((Association)object).getName(); return label == null || label.length() == 0 ? getString("_UI_Association_type") : getString("_UI_Association_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); switch (notification.getFeatureID(Association.class)) { case ComponentsPackage.ASSOCIATION__LOWER_BOUND: case ComponentsPackage.ASSOCIATION__UPPER_BOUND: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true)); return; } super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } }
peterbartha/j2eecm
edu.bme.vik.iit.j2eecm.edit/src/components/provider/AssociationItemProvider.java
Java
gpl-2.0
6,415
/********************************************************************************************************************** * Copyright (c) 2015. Lorem ipsum dolor sit amet, consectetur adipiscing elit. * * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan. * * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna. * * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus. * * Vestibulum commodo. Ut rhoncus gravida arcu. * **********************************************************************************************************************/ package z.z.w.test.common.core.notify; /************************************************************************** * <pre> * FileName: IDataManipulation * Desc: * author: Z_Z.W - myhongkongzhen@gmail.com * version: 2015-12-28 23:54 * LastChange: 2015-12-28 23:54 * History: * </pre> **************************************************************************/ public interface IDataManipulation< T > { void operating( T t ); }
myhongkongzhen/pro-study-jdk
src/main/java/z/z/w/test/common/core/notify/IDataManipulation.java
Java
gpl-2.0
1,312
# -*- coding: utf-8 -*- import json import datetime from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from misc.decorators import staff_required, common_ajax_response, verify_permission from common import cache, debug, page from message.interface import GlobalNoticeBase #--------------------------------- 缓存管理 @verify_permission('') def caches(request, template_name='admin/caches.html'): indexes = [{'name': cache.CACHE_INDEX[k][0], 'value': k} for k in cache.CACHE_INDEX.keys()] descs = [{'name': cache.CACHE_KEYS_DESC[k], 'value': k} for k in cache.CACHE_KEYS_DESC.keys()] return render_to_response(template_name, locals(), context_instance=RequestContext(request)) @verify_permission('modify_cache') @common_ajax_response def modify_cache(request): index = request.REQUEST.get('index') key = request.REQUEST.get('key_name') value = request.REQUEST.get('key_value', '') expire = request.REQUEST.get('key_expire', 3600) try: c = cache.Cache(cache.CACHE_INDEX[index][1]) c.set(key, value, expire) return 0, u'修改成功!' except Exception, e: debug.get_debug_detail(e) return 1, u'系统错误!' @verify_permission('remove_cache') @common_ajax_response def remove_cache(request): index = request.REQUEST.get('index') key = request.REQUEST.get('key_name') try: c = cache.Cache(cache.CACHE_INDEX[index][1]) c.delete(key) return 0, u'删除成功!' except Exception, e: debug.get_debug_detail(e) return 1, u'系统错误!' @verify_permission('get_cache') @common_ajax_response def get_cache(request): index = request.REQUEST.get('index') key = request.REQUEST.get('key_name') try: c = cache.Cache(cache.CACHE_INDEX[index][1]) return 0, [c.get(key) or '', c.ttl(key) or 0] except Exception, e: debug.get_debug_detail(e) return 1, u'系统错误!' #--------------------------------- 全站通告 @verify_permission('') def notice(request, template_name='admin/notice.html'): return render_to_response(template_name, locals(), context_instance=RequestContext(request)) @verify_permission('query_notice') def search_notice(request): data = [] gnb = GlobalNoticeBase() page_index = int(request.REQUEST.get('page_index')) page_objs = page.Cpt(gnb.get_all_global_notice(), count=10, page=page_index).info num = 10 * (page_index - 1) for obj in page_objs[0]: num += 1 data.append({ 'num': num, 'notice_id': obj.id, 'content': obj.content, 'start_time': str(obj.start_time), 'end_time': str(obj.end_time), 'level': obj.level, 'state': True if (obj.end_time - datetime.datetime.now()).total_seconds > 0 else False }) return HttpResponse( json.dumps({'data': data, 'page_count': page_objs[4], 'total_count': page_objs[5]}), mimetype='application/json' ) @verify_permission('add_notice') @common_ajax_response def add_notice(request): content = request.REQUEST.get('content') start_time = request.REQUEST.get('start_time') end_time = request.REQUEST.get('end_time') level = request.REQUEST.get('level') return GlobalNoticeBase().create_global_notice( content, start_time, end_time, request.user.id, level) @verify_permission('query_notice') def get_notice_by_id(request): notice_id = request.REQUEST.get('notice_id') data = '' obj = GlobalNoticeBase().get_notice_by_id(notice_id) if obj: data = { 'num': 1, 'notice_id': obj.id, 'content': obj.content, 'start_time': str(obj.start_time)[:10], 'end_time': str(obj.end_time)[:10], 'level': obj.level, 'state': True if (obj.end_time - datetime.datetime.now()).total_seconds > 0 else False } return HttpResponse(json.dumps(data), mimetype='application/json') @verify_permission('modify_notice') @common_ajax_response def modify_notice(request): notice_id = request.REQUEST.get('notice_id') content = request.REQUEST.get('content') start_time = request.REQUEST.get('start_time') end_time = request.REQUEST.get('end_time') level = request.REQUEST.get('level') return GlobalNoticeBase().modify_global_notice( notice_id, content=content, start_time=start_time, end_time=end_time, level=level) @verify_permission('remove_notice') @common_ajax_response def remove_notice(request): notice_id = request.REQUEST.get('notice_id') return GlobalNoticeBase().remove_global_notice(notice_id)
lantianlz/zx
www/admin/views_tools.py
Python
gpl-2.0
4,764
/* * wowhead basic.js * adapted to phpbb * */ window.onload = resizeIfOdd; window.onresize = forceBrowserEven; function resizeIfOdd(){ if(navigator.userAgent.indexOf('Firefox/3') != -1 || navigator.userAgent.indexOf('WebKit') != -1) if(document.documentElement.clientWidth % 2 == 1) window.resizeBy(-1,0); }; function forceBrowserEven(){ window.setTimeout('resizeIfOdd()',5); }; if (typeof $WH == "undefined") { var $WH = {} } if ((whPos = document.domain.indexOf(".wowhead.com")) != -1) { document.domain = document.domain.substring(whPos + 1) } $WH.$E = function(a) { if (!a) { if (typeof event != "undefined") { a = event } else { return null } } if (a.which) { a._button = a.which } else { a._button = a.button; if ($WH.Browser.ie6789 && a._button) { if (a._button & 4) { a._button = 2 } else { if (a._button & 2) { a._button = 3 } } } else { a._button = a.button + 1 } } a._target = a.target ? a.target : a.srcElement; a._wheelDelta = a.wheelDelta ? a.wheelDelta : -a.detail; return a }; $WH.$A = function(c) { var e = []; for ( var d = 0, b = c.length; d < b; ++d) { e.push(c[d]) } return e }; if (!Function.prototype.bind) { Function.prototype.bind = function() { var c = this, a = $WH.$A(arguments), b = a.shift(); return function() { return c.apply(b, a.concat($WH.$A(arguments))) } } } $WH.bindfunc = function() { args = $WH.$A(arguments); var b = args.shift(); var a = args.shift(); return function() { return b.apply(a, args.concat($WH.$A(arguments))) } }; if (!String.prototype.ltrim) { String.prototype.ltrim = function() { return this.replace(/^\s*/, "") } } if (!String.prototype.rtrim) { String.prototype.rtrim = function() { return this.replace(/\s*$/, "") } } if (!String.prototype.trim) { String.prototype.trim = function() { return this.ltrim().rtrim() } } if (!String.prototype.removeAllWhitespace) { String.prototype.removeAllWhitespace = function() { return this.replace("/s+/g", "") } } $WH.strcmp = function(d, c) { if (d == c) { return 0 } if (d == null) { return -1 } if (c == null) { return 1 } var f = parseFloat(d); var e = parseFloat(c); if (!isNaN(f) && !isNaN(e) && f != e) { return f < e ? -1 : 1 } if (typeof d == "string" && typeof c == "string") { return d.localeCompare(c) } return d < c ? -1 : 1 }; $WH.trim = function(a) { return a.replace(/(^\s*|\s*$)/g, "") }; $WH.rtrim = function(c, d) { var b = c.length; while (--b > 0 && c.charAt(b) == d) { } c = c.substring(0, b + 1); if (c == d) { c = ""; } return c }; $WH.sprintf = function(b) { var a; for (a = 1, len = arguments.length; a < len; ++a) { b = b.replace("$" + a, arguments[a]) } return b }; $WH.sprintfa = function(b) { var a; for (a = 1, len = arguments.length; a < len; ++a) { b = b.replace(new RegExp("\\$" + a, "g"), arguments[a]) } return b }; $WH.sprintfo = function(c) { if (typeof c == "object" && c.length) { var a = c; c = a[0]; var b; for (b = 1; b < a.length; ++b) { c = c.replace("$" + b, a[b]) } return c } }; $WH.str_replace = function(e, d, c) { while (e.indexOf(d) != -1) { e = e.replace(d, c) } return e }; $WH.urlencode = function(a) { a = encodeURIComponent(a); a = $WH.str_replace(a, "+", "%2B"); return a }; $WH.urlencode2 = function(a) { a = encodeURIComponent(a); a = $WH.str_replace(a, "%20", "+"); a = $WH.str_replace(a, "%3D", "="); return a }; $WH.number_format = function(a) { x = ("" + parseFloat(a)).split("."); a = x[0]; x = x.length > 1 ? "." + x[1] : ""; if (a.length <= 3) { return a + x } return $WH.number_format(a.substr(0, a.length - 3)) + "," + a.substr(a.length - 3) + x }; $WH.is_array = function(b) { return !!(b && b.constructor == Array) }; $WH.in_array = function(c, g, h, e) { if (c == null) { return -1 } if (h) { return $WH.in_arrayf(c, g, h, e) } for ( var d = e || 0, b = c.length; d < b; ++d) { if (c[d] == g) { return d } } return -1 }; $WH.in_arrayf = function(c, g, h, e) { for ( var d = e || 0, b = c.length; d < b; ++d) { if (h(c[d]) == g) { return d } } return -1 }; $WH.rs = function() { var e = $WH.rs.random; var b = ""; for ( var a = 0; a < 16; a++) { var d = Math.floor(Math.random() * e.length); if (a == 0 && d < 11) { d += 10 } b += e.substring(d, d + 1) } return b }; $WH.rs.random = "0123456789abcdefghiklmnopqrstuvwxyz"; $WH.isset = function(a) { return typeof window[a] != "undefined" }; if (!$WH.isset("console")) { console = { log : function() { } } } $WH.array_walk = function(d, h, c) { var g; for ( var e = 0, b = d.length; e < b; ++e) { g = h(d[e], c, d, e); if (g != null) { d[e] = g } } }; $WH.array_apply = function(d, h, c) { var g; for ( var e = 0, b = d.length; e < b; ++e) { h(d[e], c, d, e) } }; $WH.array_filter = function(c, g) { var e = []; for ( var d = 0, b = c.length; d < b; ++d) { if (g(c[d])) { e.push(c[d]) } } return e }; $WH.array_index = function(c, e, g, h) { if (!$WH.is_array(c)) { return false } if (!c.__R || h) { c.__R = {}; if (!g) { g = function(a) { return a } } for ( var d = 0, b = c.length; d < b; ++d) { c.__R[g(c[d])] = d } } return (e == null ? c.__R : !isNaN(c.__R[e])) }; $WH.array_compare = function(d, c) { if (d.length != c.length) { return false } var g = {}; for ( var f = d.length; f >= 0; --f) { g[d[f]] = true } var e = true; for ( var f = c.length; f >= 0; --f) { if (g[c[f]] === undefined) { e = false } } return e }; $WH.array_unique = function(b) { var c = []; var e = {}; for ( var d = b.length - 1; d >= 0; --d) { e[b[d]] = 1 } for ( var d in e) { c.push(d) } return c }; $WH.ge = function(a) { if (typeof a != "string") { return a } return document.getElementById(a) }; $WH.gE = function(a, b) { return a.getElementsByTagName(b) }; $WH.ce = function(d, b, e) { var a = document.createElement(d); if (b) { $WH.cOr(a, b) } if (e) { $WH.ae(a, e) } return a }; $WH.de = function(a) { if (!a || !a.parentNode) { return } a.parentNode.removeChild(a) }; $WH.ae = function(a, b) { if ($WH.is_array(b)) { $WH.array_apply(b, a.appendChild.bind(a)); return b } else { return a.appendChild(b) } }; $WH.aef = function(a, b) { return a.insertBefore(b, a.firstChild) }; $WH.ee = function(a, b) { if (!b) { b = 0 } while (a.childNodes[b]) { a.removeChild(a.childNodes[b]) } }; $WH.ct = function(a) { return document.createTextNode(a) }; $WH.st = function(a, b) { if (a.firstChild && a.firstChild.nodeType == 3) { a.firstChild.nodeValue = b } else { $WH.aef(a, $WH.ct(b)) } }; $WH.nw = function(a) { a.style.whiteSpace = "nowrap" }; $WH.rf = function() { return false }; $WH.rf2 = function(a) { a = $WH.$E(a); if (a.ctrlKey || a.shiftKey || a.altKey || a.metaKey) { return } return false }; $WH.tb = function() { this.blur() }; $WH.aE = function(b, c, a) { if ($WH.Browser.ie6789) { b.attachEvent("on" + c, a) } else { b.addEventListener(c, a, false) } }; $WH.dE = function(b, c, a) { if ($WH.Browser.ie6789) { b.detachEvent("on" + c, a) } else { b.removeEventListener(c, a, false) } }; $WH.sp = function(a) { if (!a) { a = event } if ($WH.Browser.ie6789) { a.cancelBubble = true } else { a.stopPropagation() } }; $WH.sc = function(h, j, d, f, g) { var e = new Date(); var c = h + "=" + escape(d) + "; "; e.setDate(e.getDate() + j); c += "expires=" + e.toUTCString() + "; "; if (f) { c += "path=" + f + "; " } if (g) { c += "domain=" + g + "; " } document.cookie = c; $WH.gc(h); $WH.gc.C[h] = d }; $WH.dc = function(a) { $WH.sc(a, -1); $WH.gc.C[a] = null }; $WH.gc = function(f) { if ($WH.gc.I == null) { var e = unescape(document.cookie).split("; "); $WH.gc.C = {}; for ( var c = 0, a = e.length; c < a; ++c) { var g = e[c].indexOf("="), b, d; if (g != -1) { b = e[c].substr(0, g); d = e[c].substr(g + 1) } else { b = e[c]; d = "" } $WH.gc.C[b] = d } $WH.gc.I = 1 } if (!f) { return $WH.gc.C } else { return $WH.gc.C[f] } }; $WH.ns = function(a) { if ($WH.Browser.ie6789) { a.onfocus = $WH.tb; a.onmousedown = a.onselectstart = a.ondragstart = $WH.rf } }; $WH.eO = function(b) { for ( var a in b) { delete b[a] } }; $WH.dO = function(a) { function b() { } b.prototype = a; return new b }; $WH.cO = function(c, a) { for ( var b in a) { if (a[b] !== null && typeof a[b] == "object" && a[b].length) { c[b] = a[b].slice(0) } else { c[b] = a[b] } } return c }; $WH.cOr = function(c, a) { for ( var b in a) { if (typeof a[b] == "object") { if (a[b].length) { c[b] = a[b].slice(0) } else { if (!c[b]) { c[b] = {} } $WH.cOr(c[b], a[b]) } } else { c[b] = a[b] } } return c }; $WH.Browser = { ie : !!(window.attachEvent && !window.opera), opera : !!window.opera, safari : navigator.userAgent.indexOf("Safari") != -1, firefox : navigator.userAgent.indexOf("Firefox") != -1, chrome : navigator.userAgent.indexOf("Chrome") != -1 }; $WH.Browser.ie9 = $WH.Browser.ie && navigator.userAgent.indexOf("MSIE 9.0") != -1; $WH.Browser.ie8 = $WH.Browser.ie && navigator.userAgent.indexOf("MSIE 8.0") != -1 && !$WH.Browser.ie9; $WH.Browser.ie7 = $WH.Browser.ie && navigator.userAgent.indexOf("MSIE 7.0") != -1 && !$WH.Browser.ie8; $WH.Browser.ie6 = $WH.Browser.ie && navigator.userAgent.indexOf("MSIE 6.0") != -1 && !$WH.Browser.ie7; $WH.Browser.ie67 = $WH.Browser.ie6 || $WH.Browser.ie7; $WH.Browser.ie678 = $WH.Browser.ie67 || $WH.Browser.ie8; $WH.Browser.ie6789 = $WH.Browser.ie678 || $WH.Browser.ie9; $WH.OS = { windows : navigator.appVersion.indexOf("Windows") != -1, mac : navigator.appVersion.indexOf("Macintosh") != -1, linux : navigator.appVersion.indexOf("Linux") != -1 }; $WH.g_getWindowSize = function() { var a = 0, b = 0; if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) { a = document.documentElement.clientWidth; b = document.documentElement.clientHeight } else { if (document.body && (document.body.clientWidth || document.body.clientHeight)) { a = document.body.clientWidth; b = document.body.clientHeight } else { if (typeof window.innerWidth == "number") { a = window.innerWidth; b = window.innerHeight } } } return { w : a, h : b } }; $WH.g_getScroll = function() { var a = 0, b = 0; if (typeof (window.pageYOffset) == "number") { a = window.pageXOffset; b = window.pageYOffset } else { if (document.body && (document.body.scrollLeft || document.body.scrollTop)) { a = document.body.scrollLeft; b = document.body.scrollTop } else { if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) { a = document.documentElement.scrollLeft; b = document.documentElement.scrollTop } } } return { x : a, y : b } }; $WH.g_getCursorPos = function(c) { var a, d; if (window.innerHeight) { a = c.pageX; d = c.pageY } else { var b = $WH.g_getScroll(); a = c.clientX + b.x; d = c.clientY + b.y } return { x : a, y : d } }; $WH.ac = function(c, d) { var a = 0, g = 0, b; while (c) { a += c.offsetLeft; g += c.offsetTop; b = c.parentNode; while (b && b != c.offsetParent && b.offsetParent) { if (b.scrollLeft || b.scrollTop) { a -= (b.scrollLeft | 0); g -= (b.scrollTop | 0); break } b = b.parentNode } c = c.offsetParent } if ($WH.isset("Lightbox") && Lightbox.isVisible()) { d = true } if (d) { var f = $WH.g_getScroll(); a += f.x; g += f.y } var e = [ a, g ]; e.x = a; e.y = g; return e }; $WH.g_scrollTo = function(c, b) { var m, l = $WH.g_getWindowSize(), o = $WH.g_getScroll(), j = l.w, e = l.h, g = o.x, d = o.y; c = $WH.ge(c); if (b == null) { b = [] } else { if (typeof b == "number") { b = [ b ] } } m = b.length; if (m == 0) { b[0] = b[1] = b[2] = b[3] = 0 } else { if (m == 1) { b[1] = b[2] = b[3] = b[0] } else { if (m == 2) { b[2] = b[0]; b[3] = b[1] } else { if (m == 3) { b[3] = b[1] } } } } m = $WH.ac(c); var a = m[0] - b[3], h = m[1] - b[0], k = m[0] + c.offsetWidth + b[1], f = m[1] + c.offsetHeight + b[2]; if (k - a > j || a < g) { g = a } else { if (k - j > g) { g = k - j } } if (f - h > e || h < d) { d = h } else { if (f - e > d) { d = f - e } } scrollTo(g, d) }; $WH.g_createReverseLookupJson = function(b) { var c = {}; for ( var a in b) { c[b[a]] = a } return c }; $WH.g_getLocaleFromDomain = function(a) { var c = $WH.g_getLocaleFromDomain.L; if (a) { var b = a.indexOf("."); if (b != -1) { a = a.substring(0, b) } } return (c[a] ? c[a] : 0) }; $WH.g_getLocaleFromDomain.L = { fr : 2, de : 3, es : 6, ru : 7, www : 0 }; $WH.g_getDomainFromLocale = function(a) { var b; if ($WH.g_getDomainFromLocale.L) { b = $WH.g_getDomainFromLocale.L } else { b = $WH.g_getDomainFromLocale.L = $WH .g_createReverseLookupJson($WH.g_getLocaleFromDomain.L) } return (b[a] ? b[a] : "www") }; $WH.g_getIdFromTypeName = function(a) { var b = $WH.g_getIdFromTypeName.L; return (b[a] ? b[a] : -1) }; $WH.g_getIdFromTypeName.L = { npc : 1, object : 2, item : 3, itemset : 4, quest : 5, spell : 6, zone : 7, faction : 8, pet : 9, achievement : 10, title : 11, statistic : 16, profile : 100, "transmog-set" : 101 }; $WH.g_ajaxIshRequest = function(b) { var c = document.getElementsByTagName("head")[0], a = $WH.g_getGets(); if (a.refresh != null) { if (a.refresh.length) { b += ("&refresh=" + a.refresh) } else { b += "&refresh" } } if (a.locale != null) { b += "&locale=" + a.locale } if (a.ptr != null) { b += "&ptr" } $WH.ae(c, $WH.ce("script", { type : "text/javascript", src : b, charset : "utf8" })) }; $WH.g_getGets = function() { if ($WH.g_getGets.C != null) { return $WH.g_getGets.C } var b = $WH.g_getQueryString(); var a = $WH.g_parseQueryString(b); $WH.g_getGets.C = a; return a }; $WH.g_getQueryString = function() { var a = ""; if (location.pathname) { a += location.pathname.substr(1) } if (location.search) { if (location.pathname) { a += "&" } a += location.search.substr(1) } return a }; $WH.g_parseQueryString = function(e) { e = decodeURIComponent(e); var d = e.split("&"); var c = {}; for ( var b = 0, a = d.length; b < a; ++b) { $WH.g_splitQueryParam(d[b], c) } return c }; $WH.g_splitQueryParam = function(c, d) { var e = c.indexOf("="); var a; var b; if (e != -1) { a = c.substr(0, e); b = c.substr(e + 1) } else { a = c; b = "" } d[a] = b }; $WH.g_createRect = function(d, c, a, b) { return { l : d, t : c, r : d + a, b : c + b } }; $WH.g_intersectRect = function(d, c) { return !(d.l >= c.r || c.l >= d.r || d.t >= c.b || c.t >= d.b) }; $WH.g_convertRatingToPercent = function(h, b, g, d) { var f = $WH.g_convertRatingToPercent.RB, e = $WH.g_convertRatingToPercent.LH; if (h < 0) { h = 1 } else { if (h > 85) { h = 85 } } if ((b == 12 || b == 13 || b == 14 || b == 15) && h < 34) { h = 34 } if ((b == 28 || b == 36) && (d == 2 || d == 6 || d == 7 || d == 11)) { f[b] /= 1.3 } if (g < 0) { g = 0 } var a; if (!f || f[b] == null) { a = 0 } else { var c; if (h > 80) { c = e[h] } else { if (h > 70) { c = (82 / 52) * Math.pow((131 / 63), ((h - 70) / 10)) } else { if (h > 60) { c = (82 / (262 - 3 * h)) } else { if (h > 10) { c = ((h - 8) / 52) } else { c = 2 / 52 } } } } a = g / f[b] / c } return a }; $WH.g_statToJson = { 0 : "mana", 1 : "health", 3 : "agi", 4 : "str", 5 : "int", 6 : "spi", 7 : "sta", 8 : "energy", 9 : "rage", 10 : "focus", 13 : "dodgertng", 14 : "parryrtng", 16 : "mlehitrtng", 17 : "rgdhitrtng", 18 : "splhitrtng", 19 : "mlecritstrkrtng", 20 : "rgdcritstrkrtng", 21 : "splcritstrkrtng", 22 : "_mlehitrtng", 23 : "_rgdhitrtng", 24 : "_splhitrtng", 25 : "_mlecritstrkrtng", 26 : "_rgdcritstrkrtng", 27 : "_splcritstrkrtng", 28 : "mlehastertng", 29 : "rgdhastertng", 30 : "splhastertng", 31 : "hitrtng", 32 : "critstrkrtng", 33 : "_hitrtng", 34 : "_critstrkrtng", 35 : "resirtng", 36 : "hastertng", 37 : "exprtng", 38 : "atkpwr", 39 : "rgdatkpwr", 41 : "splheal", 42 : "spldmg", 43 : "manargn", 44 : "armorpenrtng", 45 : "splpwr", 46 : "healthrgn", 47 : "splpen", 49 : "mastrtng", 50 : "armor", 51 : "firres", 52 : "frores", 53 : "holres", 54 : "shares", 55 : "natres", 56 : "arcres" }; $WH.g_jsonToStat = {}; for ( var i in $WH.g_statToJson) { $WH.g_jsonToStat[$WH.g_statToJson[i]] = i } $WH.g_individualToGlobalStat = { 16 : 31, 17 : 31, 18 : 31, 19 : 32, 20 : 32, 21 : 32, 22 : 33, 23 : 33, 24 : 33, 25 : 34, 26 : 34, 27 : 34, 28 : 36, 29 : 36, 30 : 36 }; $WH.g_convertScalingFactor = function(c, b, g, d, k) { var f = $WH.g_convertScalingFactor.SV; var e = $WH.g_convertScalingFactor.SD; if (!f[c]) { if (g_user.roles & U_GROUP_ADMIN) { alert("There are no item scaling values for level " + c) } return (k ? {} : 0) } var j = {}, h = f[c], a = e[g]; if (!a || !(d >= 0 && d <= 9)) { j.v = h[b] } else { j.n = $WH.g_statToJson[a[d]]; j.s = a[d]; j.v = Math.floor(h[b] * a[d + 10] / 10000) } return (k ? j : j.v) }; if (!$WH.wowheadRemote) { $WH.g_ajaxIshRequest("/data=item-scaling") } $WH.g_convertScalingSpell = function(b, g) { var j = {}, f = $WH.g_convertScalingSpell.SV, d = $WH.g_convertScalingSpell.SD, a, k; if (!d[g]) { if (g_user.roles & U_GROUP_ADMIN) { alert("There are no spell scaling distributions for dist " + g) } return j } if (!f[b]) { if (g_user.roles & U_GROUP_ADMIN) { alert("There are no spell scaling values for level " + b) } return j } a = d[g]; if (!a[3]) { if (g_user.roles & U_GROUP_ADMIN) { alert("This spell should not scale at all") } return j } else { if (a[3] == -1) { if (g_user.roles & U_GROUP_ADMIN) { alert("This spell should use the generic scaling distribution 12") } a[3] = 12 } } if (!f[b][a[3] - 1]) { if (g_user.roles & U_GROUP_ADMIN) { alert("Unknown category for spell scaling " + a[3]) } return j } k = f[b][a[3] - 1]; k *= (Math.min(b, a[14]) + (a[13] * Math.max(0, b - a[14]))) / b; j.cast = Math.min(a[1], a[1] > 0 && b > 1 ? a[0] + (((b - 1) * (a[1] - a[0])) / (a[2] - 1)) : a[0]); j.effects = {}; for ( var c = 0; c < 3; ++c) { var l = a[4 + c], h = a[7 + c], e = a[10 + c], m = j.effects[c + 1] = {}; m.avg = l * k * (a[1] > 0 ? j.cast / a[1] : 1); m.min = Math.round(m.avg) - Math.floor(m.avg * h / 2); m.max = Math.round(m.avg) + Math.floor(m.avg * h / 2); m.pts = Math.round(e * k); m.avg = Math.max(Math.ceil(l), Math.round(m.avg)) } j.cast = Math.round(j.cast / 10) / 100; return j }; if (!$WH.wowheadRemote) { $WH.g_ajaxIshRequest("/data=spell-scaling") } $WH.g_getDataSource = function() { if ($WH.isset("g_pageInfo")) { switch (g_pageInfo.type) { case 3: if ($WH.isset("g_items")) { return g_items } case 6: if ($WH.isset("g_spells")) { return g_spells } } } return [] }; $WH.g_setJsonItemLevel = function(o, b) { if (!o.scadist || !o.scaflags) { return } o.bonuses = o.bonuses || {}; var f = o.scaflags & 255, h = (o.scaflags >> 8) & 255, l = (o.scaflags & (1 << 16)) != 0, k = (o.scaflags & (1 << 17)) != 0, a = (o.scaflags & (1 << 18)) != 0, d; switch (f) { case 5: case 1: case 7: case 17: d = 7; break; case 3: case 12: d = 8; break; case 16: case 11: d = 9; break; case 15: d = 10; break; case 23: case 21: case 22: case 13: d = 11; break; default: d = -1 } if (d >= 0) { for ( var e = 0; e < 10; ++e) { var m = $WH.g_convertScalingFactor(b, d, o.scadist, e, 1); if (m.n) { o[m.n] = m.v } o.bonuses[m.s] = m.v } } if (a) { o.splpwr = o.bonuses[45] = $WH.g_convertScalingFactor(b, 6) } if (l) { switch (f) { case 3: o.armor = $WH.g_convertScalingFactor(b, 11 + h); break; case 5: o.armor = $WH.g_convertScalingFactor(b, 15 + h); break; case 1: o.armor = $WH.g_convertScalingFactor(b, 19 + h); break; case 7: o.armor = $WH.g_convertScalingFactor(b, 23 + h); break; case 16: o.armor = $WH.g_convertScalingFactor(b, 28); break; default: o.armor = 0 } } if (k) { var j = (o.mledps ? "mle" : "rgd"), g; switch (f) { case 23: case 21: case 22: case 13: o.dps = o[j + "dps"] = $WH.g_convertScalingFactor(b, a ? 2 : 0); g = 0.3; break; case 17: o.dps = o[j + "dps"] = $WH.g_convertScalingFactor(b, a ? 3 : 1); g = 0.2; break; case 15: o.dps = o[j + "dps"] = $WH.g_convertScalingFactor(b, h == 19 ? 5 : 4); g = 0.3; break; default: o.dps = o[j + "dps"] = 0; g = 0 } o.dmgmin = o[j + "dmgmin"] = Math.floor(o.dps * o.speed * (1 - g)); o.dmgmax = o[j + "dmgmax"] = Math.floor(o.dps * o.speed * (1 + g)) } if (o.gearscore != null) { if (o._gearscore == null) { o._gearscore = o.gearscore } var c = Math.min(85, b + 1); if (c >= 70) { n = ((c - 70) * 9.5) + 105 } else { if (c >= 60) { n = ((c - 60) * 4.5) + 60 } else { n = c + 5 } } o.gearscore = (o._gearscore * n) / 1.8 } }; $WH.g_setJsonSpellLevel = function(a, b) { if (!a.scadist) { return } $WH.cO(a, $WH.g_convertScalingSpell(b, a.scadist)) }; $WH.g_getJsonReforge = function(b, c) { if (!c) { if (!$WH.g_reforgeStats) { return [] } if (!b.__reforge) { b.__reforge = {} } if (!b.__reforge.all) { b.__reforge.all = []; for ( var c in $WH.g_reforgeStats) { var d = $WH.g_getJsonReforge(b, c); if (d.amount) { b.__reforge.all.push(d) } } } return b.__reforge.all } if (!$WH.g_reforgeStats || !$WH.g_reforgeStats[c]) { return {} } if (!b.__statidx) { b.__statidx = {}; for ( var a in b) { if ($WH.g_individualToGlobalStat[$WH.g_jsonToStat[a]]) { b.__statidx[$WH.g_individualToGlobalStat[$WH.g_jsonToStat[a]]] = b[a] } else { b.__statidx[$WH.g_jsonToStat[a]] = b[a] } } } if (!b.__reforge) { b.__reforge = {} } if (!b.__reforge[c]) { var d = b.__reforge[c] = $WH.dO($WH.g_reforgeStats[c]); b.__reforge[c].amount = Math.floor(d.v * (b.__statidx[d.i1] && !b.__statidx[d.i2] ? b.__statidx[d.i1] : 0)) } return b.__reforge[c] }; $WH.g_setTooltipLevel = function(g, a, l) { var h = typeof g; if (h == "number") { var e = $WH.g_getDataSource(); if (e[g] && e[g][(l ? "buff_" : "tooltip_") + Locale.getName()]) { g = e[g][(l ? "buff_" : "tooltip_") + Locale.getName()] } else { return g } } else { if (h != "string") { return g } } h = g.match(/<!--\?([0-9:]*)-->/); if (!h) { return g } h = h[1].split(":"); var a = Math.min(parseInt(h[2]), Math.max(parseInt(h[1]), a)), b = parseInt(h[4]) || 0; if (b) { if (!g.match(/<!--pts[0-9](:[0-9])?-->/g)) { var k = parseInt(h[5]) || 0, c = g.match(/<!--spd-->(\d\.\d+)/); if (c) { c = parseFloat(c[1]) || 0 } var j = { scadist : b, scaflags : k, speed : c }; $WH.g_setJsonItemLevel(j, a); g = g.replace(/(<!--asc(\d+)-->)([^<]+)/, function(p, m, o) { h = o; if (a < 40 && (o == 3 || o == 4)) { --h } return m + g_itemset_types[h] }); g = g.replace(/(<!--dmg-->)\d+(\D+)\d+/, function(p, m, o) { return m + j.dmgmin + o + j.dmgmax }); g = g.replace(/(<!--dps-->\D*?)(\d+\.\d)/, function(o, m) { return m + j.dps.toFixed(1) }); g = g.replace(/(<!--amr-->)\d+/, function(o, m) { return m + j.armor }); g = g .replace( /<span><!--stat(\d+)-->[-+]\d+(\D*?)<\/span>(<!--e-->)?(<!--ps-->)?(<br ?\/?>)?/gi, function(r, o, m, t, u, p) { var q, s = j.bonuses[o]; if (s) { s = (s > 0 ? "+" : "-") + s; q = ""; p = (p ? "<br />" : "") } else { s = "+0"; q = ' style="display: none"'; p = (p ? "<!--br-->" : "") } return "<span" + q + "><!--stat" + o + "-->" + s + m + "</span>" + (t || "") + (u || "") + p }); g = g .replace( /<span class="q2">(.*?)<!--rtg(\d+)-->\d+(.*?)<\/span>(<br \/>)?/gi, function(m, q, s, u, r, o, v) { var p, t = j.bonuses[$WH.g_individualToGlobalStat[s] || s]; if (t) { p = ""; v = (v ? "<br />" : "") } else { p = ' style="display: none"'; v = (v ? "<!--br-->" : "") } return '<span class="q2"' + p + ">" + q + "<!--rtg" + s + "-->" + t + u + "</span>" + v }) } else { var j = { scadist : b }; $WH.g_setJsonSpellLevel(j, a); g = g.replace(/<!--cast-->\d+\.\d+/, "<!--cast-->" + j.cast); if (j.effects) { for ( var d = 1; d < 4; ++d) { var f = j.effects[d]; g = g.replace(new RegExp("<!--pts" + d + "(:0)?-->(.+?)<", "g"), "<!--pts" + d + "$1-->" + (f.min == f.max ? f.avg : f.min + " to " + f.max) + "<"); g = g.replace( new RegExp("<!--pts" + d + ":1-->(.+?)<", "g"), "<!--pts" + d + ":1-->" + f.min + "<"); g = g.replace( new RegExp("<!--pts" + d + ":2-->(.+?)<", "g"), "<!--pts" + d + ":2-->" + f.max + "<"); g = g.replace(new RegExp("<!--pts" + d + ":3:(\\d+)-->(.+?)<", "g"), function(o, m) { return "<!--pts" + d + ":3:" + m + "-->" + (f.avg * m) + "<" }); g = g.replace( new RegExp("<!--pts" + d + ":4-->(.+?)<", "g"), "<!--pts" + d + ":4-->" + f.pts + "<") } } } } g = g.replace(/<!--ppl(\d+):(\d+):(\d+):(\d+)-->\s*\d+/gi, function(p, m, o, q, r) { return "<!--ppl" + m + ":" + o + ":" + q + ":" + r + "-->" + Math.round(parseInt(q) + (Math.min(Math.max(a, m), o) - m) * r / 100) }); g = g.replace(/(<!--rtg%(\d+)-->)([\.0-9]+)/g, function(p, m, q, o) { h = g.match(new RegExp("<!--rtg" + q + "-->(\\d+)")); if (!h) { return p } return m + Math.round($WH.g_convertRatingToPercent(a, q, h[1]) * 100) / 100 }); g = g.replace(/(<!--\?\d+:\d+:\d+:)\d+/, "$1" + a); g = g.replace(/<!--lvl-->\d+/g, "<!--lvl-->" + a); return g }; $WH.g_setTooltipSpells = function(h, e, g, c) { var k = {}, j = "<!--sp([0-9]+):[01]-->.+?<!--sp\\1-->", d; if (e == null) { e = [] } if (c == null) { c = {} } for ( var b = 0; b < e.length; ++b) { k[e[b]] = 1 } if (d = h.match(new RegExp(j, "g"))) { for ( var b = 0; b < d.length; ++b) { var a = d[b].match(j)[1]; k[a] = (k[a] | 0); if (c[a] == null) { c[a] = -1 } c[a]++; if (g[a] == null || g[a][c[a]] == null || g[a][c[a]][k[a]] == null) { continue } var f = g[a][c[a]][k[a]]; f = $WH.g_setTooltipSpells(f, e, g, c); h = h.replace(d[b], "<!--sp" + a + ":" + k[a] + "-->" + f + "<!--sp" + a + "-->") } } return h }; $WH.g_enhanceTooltip = function(h, l, j, d, o, m, e) { var k = typeof h, c; if (k == "number") { var g = $WH.g_getDataSource(), a = h; if (g[a] && g[a][(o ? "buff_" : "tooltip_") + Locale.getName()]) { h = g[a][(o ? "buff_" : "tooltip_") + Locale.getName()]; c = g[a][(o ? "buff" : "") + "spells_" + Locale.getName()]; if (c) { h = $WH.g_setTooltipSpells(h, m, c) } } else { return h } } else { if (k != "string") { return h } } if (j) { var b = $WH.g_getGets(); if (b.lvl) { h = $WH.g_setTooltipLevel(h, b.lvl, o) } } if (l) { h = h .replace( /<span class="q2"><!--addamr(\d+)--><span>.*?<\/span><\/span>/i, function(p, q) { return '<span class="q2 tip" onmouseover="$WH.Tooltip.showAtCursor(event, $WH.sprintf(LANG.tooltip_armorbonus, ' + q + '), 0, 0, \'q\')" onmousemove="$WH.Tooltip.cursorUpdate(event)" onmouseout="$WH.Tooltip.hide()">' + p + "</span>" }); h = h .replace( /\(([^\)]*?<!--lvl-->[^\(]*?)\)/gi, function(q, p) { return '(<a href="javascript:;" onmousedown="return false" class="tip" style="color: white; cursor: pointer" onclick="$WH.g_staticTooltipLevelClick(this, null, 0)" onmouseover="$WH.Tooltip.showAtCursor(event, \'<span class=\\\'q2\\\'>\' + LANG.tooltip_changelevel + \'</span>\')" onmousemove="$WH.Tooltip.cursorUpdate(event)" onmouseout="$WH.Tooltip.hide()">' + p + "</a>)" }) } if (d && Slider) { if (o && o.slider) { o.bufftip = this } else { var k = h.match(/<!--\?(\d+):(\d+):(\d+):(\d+)/); if (k && k[2] != k[3]) { this.slider = Slider.init(d, { minValue : parseInt(k[2]), maxValue : parseInt(k[3]), onMove : $WH.g_tooltipSliderMove.bind(this) }); Slider.setValue(this.slider, parseInt(k[4])); this.slider.onmouseover = function(p) { $WH.Tooltip.showAtCursor(p, LANG.tooltip_changelevel2, 0, 0, "q2") }; this.slider.onmousemove = $WH.Tooltip.cursorUpdate; this.slider.onmouseout = $WH.Tooltip.hide } } } if (e) { if (o && o.modified) { o.bufftip = this } else { for ( var f in c) { if (!g_spells[f] || $WH.in_array(m, f) != -1) { continue } $(e).append('<input type="checkbox" id="known-' + f + '" />') .append( '<label for="known-' + f + '"><a rel="spell=' + f + "&know=" + f + '">' + g_spells[f]["name_" + Locale.getName()] + (g_spells[f]["rank_" + Locale.getName()] ? " (" + g_spells[f]["rank_" + Locale.getName()] + ")" : "") + "</a></label>") .append("<br />"); $("#known-" + f).change($WH.g_tooltipSpellsChange.bind(this)) } } this.modified = [ e, c, m ]; $(e).toggle(!$(e).is(":empty")) } return h }; $WH.g_staticTooltipLevelClick = function(b, a, g, j) { while (b.className.indexOf("tooltip") == -1) { b = b.parentNode } var h = b.innerHTML; h = h.match(/<!--\?(\d+):(\d+):(\d+):(\d+)/); if (!h) { return } var k = parseInt(h[1]), e = parseInt(h[2]), f = parseInt(h[3]), d = parseInt(h[4]); if (e >= f) { return } if (!a) { a = prompt($WH.sprintf(LANG.prompt_ratinglevel, e, f), d) } a = parseInt(a); if (isNaN(a)) { return } if (a == d || a < e || a > f) { return } var c = $WH.g_getDataSource(); h = $WH.g_setTooltipLevel(c[k][(j ? "buff_" : "tooltip_") + Locale.getName()], a, j); h = $WH.g_enhanceTooltip(h, true); b.innerHTML = "<table><tr><td>" + h + '</td><th style="background-position: top right"></th></tr><tr><th style="background-position: bottom left"></th><th style="background-position: bottom right"></th></tr></table>'; $WH.Tooltip.fixSafe(b, 1, 1); if (b.slider && !g) { Slider.setValue(b.slider, a) } if (!j) { ($WH.g_tooltipSpellsChange.bind(b))() } }; $WH.g_tooltipSliderMove = function(c, b, a) { $WH.g_staticTooltipLevelClick(this, a.value, 1); if (this.bufftip) { $WH.g_staticTooltipLevelClick(this.bufftip, a.value, 1, 1) } $WH.Tooltip.hide() }; $WH.g_tooltipSpellsChange = function() { if (!this.modified) { return } var c = this.modified[0], a = this.modified[1], b = []; $.each($("input:checked", c), function(d, e) { b.push(parseInt(e.id.replace("known-", ""))) }); this.modified[2] = b; this.innerHTML = $WH.g_setTooltipSpells(this.innerHTML, b, a); if (this.bufftip) { ($WH.g_tooltipSpellsChange.bind(this.bufftip))() } }; $WH.Tooltip = { create : function(j, l) { var g = $WH.ce("div"), o = $WH.ce("table"), b = $WH.ce("tbody"), f = $WH .ce("tr"), c = $WH.ce("tr"), a = $WH.ce("td"), m = $WH.ce("th"), k = $WH .ce("th"), h = $WH.ce("th"); g.className = "wowhead-tooltip"; m.style.backgroundPosition = "top right"; k.style.backgroundPosition = "bottom left"; h.style.backgroundPosition = "bottom right"; if (j) { a.innerHTML = j } $WH.ae(f, a); $WH.ae(f, m); $WH.ae(b, f); $WH.ae(c, k); $WH.ae(c, h); $WH.ae(b, c); $WH.ae(o, b); if (!l) { $WH.Tooltip.icon = $WH.ce("p"); /*$WH.Tooltip.icon.style.visibility = "hidden";*/ $WH.ae($WH.Tooltip.icon, $WH.ce("div")); $WH.ae(g, $WH.Tooltip.icon) } $WH.ae(g, o); if (!l) { var e = $WH.ce("div"); e.className = "wowhead-tooltip-powered"; $WH.ae(g, e); $WH.Tooltip.logo = e } return g }, getMultiPartHtml : function(b, a) { return "<table><tr><td>" + b + "</td></tr></table><table><tr><td>" + a + "</td></tr></table>" }, fix : function(d, b, f) { var e = $WH.gE(d, "table")[0], h = $WH.gE(e, "td")[0], g = h.childNodes; d.className = $WH.trim(d.className.replace("tooltip-slider", "")); if (g.length >= 2 && g[0].nodeName == "TABLE" && g[1].nodeName == "TABLE") { g[0].style.whiteSpace = "nowrap"; var a = parseInt(d.style.width); if (!d.slider || !a) { if (g[1].offsetWidth > 300) { a = Math.max(300, g[0].offsetWidth) + 20 } else { a = Math.max(g[0].offsetWidth, g[1].offsetWidth) + 20 } } a = Math.min(320, a); if (a > 20) { d.style.width = a + "px"; g[0].style.width = g[1].style.width = "100%"; if (d.slider) { Slider.setSize(d.slider, a - 6); d.className += " tooltip-slider" } if (!b && d.offsetHeight > document.body.clientHeight) { e.className = "shrink" } } } if (f) { d.style.visibility = "visible" } }, fixSafe : function(c, b, a) { $WH.Tooltip.fix(c, b, a) }, append : function(c, b) { var c = $WH.ge(c); var a = $WH.Tooltip.create(b); $WH.ae(c, a); $WH.Tooltip.fixSafe(a, 1, 1) }, prepare : function() { if ($WH.Tooltip.tooltip) { return } var a = $WH.Tooltip.create(); a.style.position = "absolute"; a.style.left = a.style.top = "-2323px"; $WH.ae(document.body, a); $WH.Tooltip.tooltip = a; $WH.Tooltip.tooltipTable = $WH.gE(a, "table")[0]; $WH.Tooltip.tooltipTd = $WH.gE(a, "td")[0]; var a = $WH.Tooltip.create(null, true); a.style.position = "absolute"; a.style.left = a.style.top = "-2323px"; $WH.ae(document.body, a); $WH.Tooltip.tooltip2 = a; $WH.Tooltip.tooltipTable2 = $WH.gE(a, "table")[0]; $WH.Tooltip.tooltipTd2 = $WH.gE(a, "td")[0] }, set : function(c, b) { var a = $WH.Tooltip.tooltip; a.style.width = "550px"; a.style.left = "-2323px"; a.style.top = "-2323px"; if (c.nodeName) { $WH.ee($WH.Tooltip.tooltipTd); $WH.ae($WH.Tooltip.tooltipTd, c) } else { $WH.Tooltip.tooltipTd.innerHTML = c } a.style.display = ""; $WH.Tooltip.fix(a, 0, 0); if (b) { $WH.Tooltip.showSecondary = true; var a = $WH.Tooltip.tooltip2; a.style.width = "550px"; a.style.left = "-2323px"; a.style.top = "-2323px"; if (b.nodeName) { $WH.ee($WH.Tooltip.tooltipTd2); $WH.ae($WH.Tooltip.tooltipTd2, b) } else { $WH.Tooltip.tooltipTd2.innerHTML = b } a.style.display = ""; $WH.Tooltip.fix(a, 0, 0) } else { $WH.Tooltip.showSecondary = false } }, moveTests : [ [ null, null ], [ null, false ], [ false, null ], [ false, false ] ], move : function(q, p, e, r, d, b) { if (!$WH.Tooltip.tooltipTable) { return } var o = $WH.Tooltip.tooltip, j = $WH.Tooltip.tooltipTable.offsetWidth, c = $WH.Tooltip.tooltipTable.offsetHeight, l = $WH.Tooltip.tooltip2, g = $WH.Tooltip.showSecondary ? $WH.Tooltip.tooltipTable2.offsetWidth : 0, a = $WH.Tooltip.showSecondary ? $WH.Tooltip.tooltipTable2.offsetHeight : 0, s; o.style.width = j + "px"; l.style.width = g + "px"; var m, f; for ( var h = 0, k = $WH.Tooltip.moveTests.length; h < k; ++h) { s = $WH.Tooltip.moveTests[h]; m = $WH.Tooltip.moveTest(q, p, e, r, d, b, s[0], s[1]); if ($WH.isset("Ads") && !Ads.intersect(m)) { f = true; break } else { if (!$WH.isset("Ads")) { break } } } if ($WH.isset("Ads") && !f) { Ads.intersect(m, true) } o.style.left = m.l + "px"; o.style.top = m.t + "px"; o.style.visibility = "visible"; if ($WH.Tooltip.showSecondary) { l.style.left = m.l + j + "px"; l.style.top = m.t + "px"; l.style.visibility = "visible" } }, moveTest : function(e, o, r, C, c, a, q, b) { var m = e, A = o, g = $WH.Tooltip.tooltip, k = $WH.Tooltip.tooltipTable.offsetWidth, t = $WH.Tooltip.tooltipTable.offsetHeight, p = $WH.Tooltip.tooltip2, B = $WH.Tooltip.showSecondary ? $WH.Tooltip.tooltipTable2.offsetWidth : 0, f = $WH.Tooltip.showSecondary ? $WH.Tooltip.tooltipTable2.offsetHeight : 0, j = $WH.g_getWindowSize(), l = $WH.g_getScroll(), h = j.w, s = j.h, d = l.x, z = l.y, y = d, w = z, v = d + h, u = z + s; if (q == null) { q = (e + r + k + B <= v) } if (b == null) { b = (o - Math.max(t, f) >= w) } if (q) { e += r + c } else { e = Math.max(e - (k + B), y) - c } if (b) { o -= Math.max(t, f) + a } else { o += C + a } if (e < y) { e = y } else { if (e + k + B > v) { e = v - (k + B) } } if (o < w) { o = w } else { if (o + Math.max(t, f) > u) { o = Math.max(z, u - Math.max(t, f)) } } if ($WH.Tooltip.iconVisible) { if (m >= e - 48 && m <= e && A >= o - 4 && A <= o + 48) { o -= 48 - (A - o) } } return $WH.g_createRect(e, o, k, t) }, show : function(g, f, d, b, c, e) { if ($WH.Tooltip.disabled) { return } if (!d || d < 1) { d = 1 } if (!b || b < 1) { b = 1 } if (c) { f = '<span class="' + c + '">' + f + "</span>" } var a = $WH.ac(g); $WH.Tooltip.prepare(); $WH.Tooltip.set(f, e); $WH.Tooltip.move(a.x, a.y, g.offsetWidth, g.offsetHeight, d, b) }, showAtCursor : function(f, g, c, a, b, d) { if ($WH.Tooltip.disabled) { return } if (!c || c < 10) { c = 10 } if (!a || a < 10) { a = 10 } if (b) { g = '<span class="' + b + '">' + g + "</span>"; if (d) { d = '<span class="' + b + '">' + d + "</span>" } } f = $WH.$E(f); var h = $WH.g_getCursorPos(f); $WH.Tooltip.prepare(); $WH.Tooltip.set(g, d); $WH.Tooltip.move(h.x, h.y, 0, 0, c, a) }, showAtXY : function(e, a, f, c, b, d) { if ($WH.Tooltip.disabled) { return } $WH.Tooltip.prepare(); $WH.Tooltip.set(e, d); $WH.Tooltip.move(a, f, 0, 0, c, b) }, cursorUpdate : function(b, a, d) { if ($WH.Tooltip.disabled || !$WH.Tooltip.tooltip) { return } b = $WH.$E(b); if (!a || a < 10) { a = 10 } if (!d || d < 10) { d = 10 } var c = $WH.g_getCursorPos(b); $WH.Tooltip.move(c.x, c.y, 0, 0, a, d) }, hide : function() { if ($WH.Tooltip.tooltip) { $WH.Tooltip.tooltip.style.display = "none"; $WH.Tooltip.tooltip.visibility = "hidden"; $WH.Tooltip.tooltipTable.className = ""; $WH.Tooltip.setIcon(null); if ($WH.isset("Ads")) { Ads.restoreHidden() } } if ($WH.Tooltip.tooltip2) { $WH.Tooltip.tooltip2.style.display = "none"; $WH.Tooltip.tooltip2.visibility = "hidden"; $WH.Tooltip.tooltipTable2.className = "" } }, setIcon : function(a) { $WH.Tooltip.prepare(); if (a) { $WH.Tooltip.icon.style.backgroundImage = "url(https://wowimg.zamimg.com/images/wow/icons/medium/" + a.toLowerCase() + ".jpg)"; $WH.Tooltip.icon.style.visibility = "visible" } else { $WH.Tooltip.icon.style.backgroundImage = "none"; $WH.Tooltip.icon.style.visibility = "hidden" } $WH.Tooltip.iconVisible = a ? 1 : 0 } }; if ($WH.isset("$WowheadPower")) { $WowheadPower.init() } $WH.g_getProfileIcon = function(d, e, a, g, c, b) { var f = { 10 : { 6 : 1, 3 : 1, 8 : 1, 2 : 1, 5 : 1, 4 : 1, 9 : 1 }, 11 : { 6 : 1, 3 : 1, 8 : 1, 2 : 1, 5 : 1, 7 : 1, 1 : 1 }, 3 : { 6 : 1, 3 : 1, 2 : 1, 5 : 1, 4 : 1, 1 : 1 }, 7 : { 6 : 1, 8 : 1, 4 : 1, 9 : 1, 1 : 1 }, 1 : { 6 : 1, 8 : 1, 2 : 1, 5 : 1, 4 : 1, 9 : 1, 1 : 1 }, 4 : { 6 : 1, 11 : 1, 3 : 1, 5 : 1, 4 : 1, 1 : 1 }, 2 : { 6 : 1, 3 : 1, 4 : 1, 7 : 1, 9 : 1, 1 : 1 }, 6 : { 6 : 1, 11 : 1, 3 : 1, 7 : 1, 1 : 1 }, 8 : { 6 : 1, 3 : 1, 8 : 1, 5 : 1, 4 : 1, 7 : 1, 1 : 1 }, 5 : { 6 : 1, 8 : 1, 5 : 1, 4 : 1, 9 : 1, 1 : 1 } }; if (c) { return isNaN(c) ? c : "/profile=avatar" + (b ? "&size=" + b : "") + "&id=" + c + (b == "tiny" ? ".gif" : ".jpg") } if (!g_file_races[d] || !g_file_classes[e] || !g_file_genders[a] || !f[d] || !f[d][e] || (e == 6 && g < 55)) { return "inv_misc_questionmark" } return "chr_" + g_file_races[d] + "_" + g_file_genders[a] + "_" + g_file_classes[e] + "0" + (g > 59 ? (Math.floor((g - 60) / 10) + 2) : 1) };
bbDKP/bbTips
root/adm/style/dkp/bbtips/basic.js
JavaScript
gpl-2.0
40,700
<?php $captcha_word = 'R75S'; ?>
CoordCulturaDigital-Minc/setoriais
wp-content/plugins/si-captcha-for-wordpress/captcha/temp/sQ5mnMOQmEJcMCR2.php
PHP
gpl-2.0
32
/* This file is part of the KDE project Copyright (C) 2004 David Faure <faure@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kio_trash.h" #include <kio/job.h> #include <kapplication.h> #include <kdebug.h> #include <klocale.h> #include <klargefile.h> #include <kcmdlineargs.h> #include <kmimetype.h> #include <kprocess.h> #include <dcopclient.h> #include <qdatastream.h> #include <qtextstream.h> #include <qfile.h> #include <qeventloop.h> #include <time.h> #include <pwd.h> #include <grp.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> static const KCmdLineOptions options[] = { { "+protocol", I18N_NOOP( "Protocol name" ), 0 }, { "+pool", I18N_NOOP( "Socket name" ), 0 }, { "+app", I18N_NOOP( "Socket name" ), 0 }, KCmdLineLastOption }; extern "C" { int KDE_EXPORT kdemain( int argc, char **argv ) { //KInstance instance( "kio_trash" ); // KApplication is necessary to use kio_file putenv(strdup("SESSION_MANAGER=")); KApplication::disableAutoDcopRegistration(); KCmdLineArgs::init(argc, argv, "kio_trash", 0, 0, 0, 0); KCmdLineArgs::addCmdLineOptions( options ); KApplication app( false, false ); KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); TrashProtocol slave( args->arg(0), args->arg(1), args->arg(2) ); slave.dispatchLoop(); return 0; } } #define INIT_IMPL \ if ( !impl.init() ) { \ error( impl.lastErrorCode(), impl.lastErrorMessage() ); \ return; \ } TrashProtocol::TrashProtocol( const QCString& protocol, const QCString &pool, const QCString &app) : SlaveBase(protocol, pool, app ) { struct passwd *user = getpwuid( getuid() ); if ( user ) m_userName = QString::fromLatin1(user->pw_name); struct group *grp = getgrgid( getgid() ); if ( grp ) m_groupName = QString::fromLatin1(grp->gr_name); } TrashProtocol::~TrashProtocol() { } void TrashProtocol::restore( const KURL& trashURL ) { int trashId; QString fileId, relativePath; bool ok = TrashImpl::parseURL( trashURL, trashId, fileId, relativePath ); if ( !ok ) { error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( trashURL.prettyURL() ) ); return; } TrashedFileInfo info; ok = impl.infoForFile( trashId, fileId, info ); if ( !ok ) { error( impl.lastErrorCode(), impl.lastErrorMessage() ); return; } KURL dest; dest.setPath( info.origPath ); if ( !relativePath.isEmpty() ) dest.addPath( relativePath ); // Check that the destination directory exists, to improve the error code in case it doesn't. const QString destDir = dest.directory(); KDE_struct_stat buff; if ( KDE_lstat( QFile::encodeName( destDir ), &buff ) == -1 ) { error( KIO::ERR_SLAVE_DEFINED, i18n( "The directory %1 does not exist anymore, so it is not possible to restore this item to its original location. " "You can either recreate that directory and use the restore operation again, or drag the item anywhere else to restore it." ).arg( destDir ) ); return; } copyOrMove( trashURL, dest, false /*overwrite*/, Move ); } void TrashProtocol::rename( const KURL &oldURL, const KURL &newURL, bool overwrite ) { INIT_IMPL; kdDebug()<<"TrashProtocol::rename(): old="<<oldURL<<" new="<<newURL<<" overwrite=" << overwrite<<endl; if ( oldURL.protocol() == "trash" && newURL.protocol() == "trash" ) { error( KIO::ERR_CANNOT_RENAME, oldURL.prettyURL() ); return; } copyOrMove( oldURL, newURL, overwrite, Move ); } void TrashProtocol::copy( const KURL &src, const KURL &dest, int /*permissions*/, bool overwrite ) { INIT_IMPL; kdDebug()<<"TrashProtocol::copy(): " << src << " " << dest << endl; if ( src.protocol() == "trash" && dest.protocol() == "trash" ) { error( KIO::ERR_UNSUPPORTED_ACTION, i18n( "This file is already in the trash bin." ) ); return; } copyOrMove( src, dest, overwrite, Copy ); } void TrashProtocol::copyOrMove( const KURL &src, const KURL &dest, bool overwrite, CopyOrMove action ) { if ( src.protocol() == "trash" && dest.isLocalFile() ) { // Extracting (e.g. via dnd). Ignore original location stored in info file. int trashId; QString fileId, relativePath; bool ok = TrashImpl::parseURL( src, trashId, fileId, relativePath ); if ( !ok ) { error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( src.prettyURL() ) ); return; } const QString destPath = dest.path(); if ( QFile::exists( destPath ) ) { if ( overwrite ) { ok = QFile::remove( destPath ); Q_ASSERT( ok ); // ### TODO } else { error( KIO::ERR_FILE_ALREADY_EXIST, destPath ); return; } } if ( action == Move ) { kdDebug() << "calling moveFromTrash(" << destPath << " " << trashId << " " << fileId << ")" << endl; ok = impl.moveFromTrash( destPath, trashId, fileId, relativePath ); } else { // Copy kdDebug() << "calling copyFromTrash(" << destPath << " " << trashId << " " << fileId << ")" << endl; ok = impl.copyFromTrash( destPath, trashId, fileId, relativePath ); } if ( !ok ) { error( impl.lastErrorCode(), impl.lastErrorMessage() ); } else { if ( action == Move && relativePath.isEmpty() ) (void)impl.deleteInfo( trashId, fileId ); finished(); } return; } else if ( src.isLocalFile() && dest.protocol() == "trash" ) { QString dir = dest.directory(); //kdDebug() << "trashing a file to " << dir << endl; // Trashing a file // We detect the case where this isn't normal trashing, but // e.g. if kwrite tries to save (moving tempfile over destination) if ( dir.length() <= 1 && src.fileName() == dest.fileName() ) // new toplevel entry { const QString srcPath = src.path(); // In theory we should use TrashImpl::parseURL to give the right filename to createInfo, // in case the trash URL didn't contain the same filename as srcPath. // But this can only happen with copyAs/moveAs, not available in the GUI // for the trash (New/... or Rename from iconview/listview). int trashId; QString fileId; if ( !impl.createInfo( srcPath, trashId, fileId ) ) { error( impl.lastErrorCode(), impl.lastErrorMessage() ); } else { bool ok; if ( action == Move ) { kdDebug() << "calling moveToTrash(" << srcPath << " " << trashId << " " << fileId << ")" << endl; ok = impl.moveToTrash( srcPath, trashId, fileId ); } else { // Copy kdDebug() << "calling copyToTrash(" << srcPath << " " << trashId << " " << fileId << ")" << endl; ok = impl.copyToTrash( srcPath, trashId, fileId ); } if ( !ok ) { (void)impl.deleteInfo( trashId, fileId ); error( impl.lastErrorCode(), impl.lastErrorMessage() ); } else { // Inform caller of the final URL. Used by konq_undo. const KURL url = impl.makeURL( trashId, fileId, QString::null ); setMetaData( "trashURL-" + srcPath, url.url() ); finished(); } } return; } else { kdDebug() << "returning KIO::ERR_ACCESS_DENIED, it's not allowed to add a file to an existing trash directory" << endl; // It's not allowed to add a file to an existing trash directory. error( KIO::ERR_ACCESS_DENIED, dest.prettyURL() ); return; } } else error( KIO::ERR_UNSUPPORTED_ACTION, "should never happen" ); } static void addAtom(KIO::UDSEntry& entry, unsigned int ID, long long l, const QString& s = QString::null) { KIO::UDSAtom atom; atom.m_uds = ID; atom.m_long = l; atom.m_str = s; entry.append(atom); } void TrashProtocol::createTopLevelDirEntry(KIO::UDSEntry& entry) { entry.clear(); addAtom(entry, KIO::UDS_NAME, 0, "."); addAtom(entry, KIO::UDS_FILE_TYPE, S_IFDIR); addAtom(entry, KIO::UDS_ACCESS, 0700); addAtom(entry, KIO::UDS_MIME_TYPE, 0, "inode/directory"); addAtom(entry, KIO::UDS_USER, 0, m_userName); addAtom(entry, KIO::UDS_GROUP, 0, m_groupName); } void TrashProtocol::stat(const KURL& url) { INIT_IMPL; const QString path = url.path(); if( path.isEmpty() || path == "/" ) { // The root is "virtual" - it's not a single physical directory KIO::UDSEntry entry; createTopLevelDirEntry( entry ); statEntry( entry ); finished(); } else { int trashId; QString fileId, relativePath; bool ok = TrashImpl::parseURL( url, trashId, fileId, relativePath ); if ( !ok ) { // ######## do we still need this? kdDebug() << k_funcinfo << url << " looks fishy, returning does-not-exist" << endl; // A URL like trash:/file simply means that CopyJob is trying to see if // the destination exists already (it made up the URL by itself). error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL() ); //error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.prettyURL() ) ); return; } const QString filePath = impl.physicalPath( trashId, fileId, relativePath ); if ( filePath.isEmpty() ) { error( impl.lastErrorCode(), impl.lastErrorMessage() ); return; } QString fileName = filePath.section('/', -1, -1, QString::SectionSkipEmpty); QString fileURL = QString::null; if ( url.path().length() > 1 ) { fileURL = url.url(); } KIO::UDSEntry entry; TrashedFileInfo info; ok = impl.infoForFile( trashId, fileId, info ); if ( ok ) ok = createUDSEntry( filePath, fileName, fileURL, entry, info ); if ( !ok ) { error( KIO::ERR_COULD_NOT_STAT, url.prettyURL() ); } statEntry( entry ); finished(); } } void TrashProtocol::del( const KURL &url, bool /*isfile*/ ) { int trashId; QString fileId, relativePath; bool ok = TrashImpl::parseURL( url, trashId, fileId, relativePath ); if ( !ok ) { error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.prettyURL() ) ); return; } ok = relativePath.isEmpty(); if ( !ok ) { error( KIO::ERR_ACCESS_DENIED, url.prettyURL() ); return; } ok = impl.del(trashId, fileId); if ( !ok ) { error( impl.lastErrorCode(), impl.lastErrorMessage() ); return; } finished(); } void TrashProtocol::listDir(const KURL& url) { INIT_IMPL; kdDebug() << "listdir: " << url << endl; if ( url.path().length() <= 1 ) { listRoot(); return; } int trashId; QString fileId; QString relativePath; bool ok = TrashImpl::parseURL( url, trashId, fileId, relativePath ); if ( !ok ) { error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.prettyURL() ) ); return; } //was: const QString physicalPath = impl.physicalPath( trashId, fileId, relativePath ); // Get info for deleted directory - the date of deletion and orig path will be used // for all the items in it, and we need the physicalPath. TrashedFileInfo info; ok = impl.infoForFile( trashId, fileId, info ); if ( !ok || info.physicalPath.isEmpty() ) { error( impl.lastErrorCode(), impl.lastErrorMessage() ); return; } if ( !relativePath.isEmpty() ) { info.physicalPath += "/"; info.physicalPath += relativePath; } // List subdir. Can't use kio_file here since we provide our own info... kdDebug() << k_funcinfo << "listing " << info.physicalPath << endl; QStrList entryNames = impl.listDir( info.physicalPath ); totalSize( entryNames.count() ); KIO::UDSEntry entry; QStrListIterator entryIt( entryNames ); for (; entryIt.current(); ++entryIt) { QString fileName = QFile::decodeName( entryIt.current() ); if ( fileName == ".." ) continue; const QString filePath = info.physicalPath + "/" + fileName; // shouldn't be necessary //const QString url = TrashImpl::makeURL( trashId, fileId, relativePath + "/" + fileName ); entry.clear(); TrashedFileInfo infoForItem( info ); infoForItem.origPath += '/'; infoForItem.origPath += fileName; if ( ok && createUDSEntry( filePath, fileName, QString::null /*url*/, entry, infoForItem ) ) { listEntry( entry, false ); } } entry.clear(); listEntry( entry, true ); finished(); } bool TrashProtocol::createUDSEntry( const QString& physicalPath, const QString& fileName, const QString& url, KIO::UDSEntry& entry, const TrashedFileInfo& info ) { QCString physicalPath_c = QFile::encodeName( physicalPath ); KDE_struct_stat buff; if ( KDE_lstat( physicalPath_c, &buff ) == -1 ) { kdWarning() << "couldn't stat " << physicalPath << endl; return false; } if (S_ISLNK(buff.st_mode)) { char buffer2[ 1000 ]; int n = readlink( physicalPath_c, buffer2, 1000 ); if ( n != -1 ) { buffer2[ n ] = 0; } addAtom( entry, KIO::UDS_LINK_DEST, 0, QFile::decodeName( buffer2 ) ); // Follow symlink // That makes sense in kio_file, but not in the trash, especially for the size // #136876 #if 0 if ( KDE_stat( physicalPath_c, &buff ) == -1 ) { // It is a link pointing to nowhere buff.st_mode = S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO; buff.st_mtime = 0; buff.st_atime = 0; buff.st_size = 0; } #endif } mode_t type = buff.st_mode & S_IFMT; // extract file type mode_t access = buff.st_mode & 07777; // extract permissions access &= 07555; // make it readonly, since it's in the trashcan addAtom( entry, KIO::UDS_NAME, 0, fileName ); addAtom( entry, KIO::UDS_FILE_TYPE, type ); if ( !url.isEmpty() ) addAtom( entry, KIO::UDS_URL, 0, url ); KMimeType::Ptr mt = KMimeType::findByPath( physicalPath, buff.st_mode ); addAtom( entry, KIO::UDS_MIME_TYPE, 0, mt->name() ); addAtom( entry, KIO::UDS_ACCESS, access ); addAtom( entry, KIO::UDS_SIZE, buff.st_size ); addAtom( entry, KIO::UDS_USER, 0, m_userName ); // assumption addAtom( entry, KIO::UDS_GROUP, 0, m_groupName ); // assumption addAtom( entry, KIO::UDS_MODIFICATION_TIME, buff.st_mtime ); addAtom( entry, KIO::UDS_ACCESS_TIME, buff.st_atime ); // ## or use it for deletion time? addAtom( entry, KIO::UDS_EXTRA, 0, info.origPath ); addAtom( entry, KIO::UDS_EXTRA, 0, info.deletionDate.toString( Qt::ISODate ) ); return true; } void TrashProtocol::listRoot() { INIT_IMPL; const TrashedFileInfoList lst = impl.list(); totalSize( lst.count() ); KIO::UDSEntry entry; createTopLevelDirEntry( entry ); listEntry( entry, false ); for ( TrashedFileInfoList::ConstIterator it = lst.begin(); it != lst.end(); ++it ) { const KURL url = TrashImpl::makeURL( (*it).trashId, (*it).fileId, QString::null ); KURL origURL; origURL.setPath( (*it).origPath ); entry.clear(); if ( createUDSEntry( (*it).physicalPath, origURL.fileName(), url.url(), entry, *it ) ) listEntry( entry, false ); } entry.clear(); listEntry( entry, true ); finished(); } void TrashProtocol::special( const QByteArray & data ) { INIT_IMPL; QDataStream stream( data, IO_ReadOnly ); int cmd; stream >> cmd; switch (cmd) { case 1: if ( impl.emptyTrash() ) finished(); else error( impl.lastErrorCode(), impl.lastErrorMessage() ); break; case 2: impl.migrateOldTrash(); finished(); break; case 3: { KURL url; stream >> url; restore( url ); break; } default: kdWarning(7116) << "Unknown command in special(): " << cmd << endl; error( KIO::ERR_UNSUPPORTED_ACTION, QString::number(cmd) ); break; } } void TrashProtocol::put( const KURL& url, int /*permissions*/, bool /*overwrite*/, bool /*resume*/ ) { INIT_IMPL; kdDebug() << "put: " << url << endl; // create deleted file. We need to get the mtime and original location from metadata... // Maybe we can find the info file for url.fileName(), in case ::rename() was called first, and failed... error( KIO::ERR_ACCESS_DENIED, url.prettyURL() ); } void TrashProtocol::get( const KURL& url ) { INIT_IMPL; kdDebug() << "get() : " << url << endl; if ( !url.isValid() ) { kdDebug() << kdBacktrace() << endl; error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.url() ) ); return; } if ( url.path().length() <= 1 ) { error( KIO::ERR_IS_DIRECTORY, url.prettyURL() ); return; } int trashId; QString fileId; QString relativePath; bool ok = TrashImpl::parseURL( url, trashId, fileId, relativePath ); if ( !ok ) { error( KIO::ERR_SLAVE_DEFINED, i18n( "Malformed URL %1" ).arg( url.prettyURL() ) ); return; } const QString physicalPath = impl.physicalPath( trashId, fileId, relativePath ); if ( physicalPath.isEmpty() ) { error( impl.lastErrorCode(), impl.lastErrorMessage() ); return; } // Usually we run jobs in TrashImpl (for e.g. future kdedmodule) // But for this one we wouldn't use DCOP for every bit of data... KURL fileURL; fileURL.setPath( physicalPath ); KIO::Job* job = KIO::get( fileURL ); connect( job, SIGNAL( data( KIO::Job*, const QByteArray& ) ), this, SLOT( slotData( KIO::Job*, const QByteArray& ) ) ); connect( job, SIGNAL( mimetype( KIO::Job*, const QString& ) ), this, SLOT( slotMimetype( KIO::Job*, const QString& ) ) ); connect( job, SIGNAL( result(KIO::Job *) ), this, SLOT( jobFinished(KIO::Job *) ) ); qApp->eventLoop()->enterLoop(); } void TrashProtocol::slotData( KIO::Job*, const QByteArray&arr ) { data( arr ); } void TrashProtocol::slotMimetype( KIO::Job*, const QString& mt ) { mimeType( mt ); } void TrashProtocol::jobFinished( KIO::Job* job ) { if ( job->error() ) error( job->error(), job->errorText() ); else finished(); qApp->eventLoop()->exitLoop(); } #if 0 void TrashProtocol::mkdir( const KURL& url, int /*permissions*/ ) { INIT_IMPL; // create info about deleted dir // ############ Problem: we don't know the original path. // Let's try to avoid this case (we should get to copy() instead, for local files) kdDebug() << "mkdir: " << url << endl; QString dir = url.directory(); if ( dir.length() <= 1 ) // new toplevel entry { // ## we should use TrashImpl::parseURL to give the right filename to createInfo int trashId; QString fileId; if ( !impl.createInfo( url.path(), trashId, fileId ) ) { error( impl.lastErrorCode(), impl.lastErrorMessage() ); } else { if ( !impl.mkdir( trashId, fileId, permissions ) ) { (void)impl.deleteInfo( trashId, fileId ); error( impl.lastErrorCode(), impl.lastErrorMessage() ); } else finished(); } } else { // Well it's not allowed to add a directory to an existing deleted directory. error( KIO::ERR_ACCESS_DENIED, url.prettyURL() ); } } #endif #include "kio_trash.moc"
iegor/kdebase
kioslave/trash/kio_trash.cpp
C++
gpl-2.0
20,976
import unittest from mock import Mock import os from katello.tests.core.action_test_utils import CLIOptionTestCase, CLIActionTestCase from katello.tests.core.repo import repo_data import katello.client.core.repo from katello.client.core.repo import Status from katello.client.api.utils import ApiDataError class RequiredCLIOptionsTests(CLIOptionTestCase): #repo is defined by either (org, product, repo_name, env name) or repo_id action = Status() disallowed_options = [ ('--name=repo1', '--product=product1'), ('--org=ACME', '--name=repo1'), ('--org=ACME', '--product=product1'), (), ] allowed_options = [ ('--org=ACME', '--name=repo1', '--product=product1'), ('--id=repo_id1', ), ] class RepoStatusTest(CLIActionTestCase): ORG_NAME = "org_1" PROD_NAME = "product_1" REPO = repo_data.REPOS[0] ENV_NAME = "env_1" OPTIONS_WITH_ID = { 'id': REPO['id'], } OPTIONS_WITH_NAME = { 'name': REPO['name'], 'product': PROD_NAME, 'org': ORG_NAME, 'environment': ENV_NAME, } repo = None def setUp(self): self.set_action(Status()) self.set_module(katello.client.core.repo) self.mock_printer() self.mock_options(self.OPTIONS_WITH_NAME) self.mock(self.action.api, 'repo', self.REPO) self.mock(self.action.api, 'last_sync_status', repo_data.SYNC_RESULT_WITHOUT_ERROR) self.repo = self.mock(self.module, 'get_repo', self.REPO).return_value def tearDown(self): self.restore_mocks() def test_finds_repo_by_id(self): self.mock_options(self.OPTIONS_WITH_ID) self.run_action() self.action.api.repo.assert_called_once_with(self.REPO['id']) def test_finds_repo_by_name(self): self.mock_options(self.OPTIONS_WITH_NAME) self.run_action() self.module.get_repo.assert_called_once_with(self.ORG_NAME, self.REPO['name'], self.PROD_NAME, None, None, self.ENV_NAME, False, None, None, None) def test_returns_with_error_when_no_repo_found(self): self.mock_options(self.OPTIONS_WITH_NAME) self.mock(self.module, 'get_repo').side_effect = ApiDataError() self.run_action(os.EX_DATAERR) def test_it_calls_last_sync_status_api(self): self.run_action() self.action.api.last_sync_status.assert_called_once_with(self.REPO['id']) def test_it_does_not_set_progress_for_not_running_sync(self): self.run_action() self.assertRaises(KeyError, lambda: self.repo['progress'] ) def test_it_sets_progress_for_running_sync(self): self.mock(self.action.api, 'last_sync_status', repo_data.SYNC_RUNNING_RESULT) self.run_action() self.assertTrue(isinstance(self.repo['progress'], str))
Katello/katello-cli
test/katello/tests/core/repo/repo_status_test.py
Python
gpl-2.0
3,038
<?php /** * Created by PhpStorm. * User: tiemanntan * Date: 16/11/15 * Time: 16:51 */ class Nextorder_Yandexmetrica_Block_Adminhtml_System_Config_Result extends Mage_Adminhtml_Block_Abstract implements Varien_Data_Form_Element_Renderer_Interface{ public function render(Varien_Data_Form_Element_Abstract $element){ $countID = Mage::helper('yandexmetrica/data')->getCountID(); $resultURL = "https://metrika.yandex.ru/dashboard?id=". $countID; $html ="<button type='button' id='result'><a style='color:white' href='". $resultURL ."'>Analyse Result bei Yandex Dashboard</a></button>"; return $html; } }
fatalerrortan/Magento_Yandexmetrica
app/code/local/Nextorder/Yandexmetrica/Block/Adminhtml/System/Config/Result.php
PHP
gpl-2.0
657
/* * Player - One Hell of a Robot Server * Copyright (C) 2010 * Mayte Lázaro, Alejandro R. Mosteo * * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef SUB_OPT_H_ #define SUB_OPT_H_ #include "transf.hh" void EIFnn(Matrix H, Matrix G, Matrix h, Matrix S, Matrix &F, Matrix &N); void CalculateEstimationEIFnn(Matrix Fk, Matrix Nk, Matrix &x, Matrix &P); #endif /* SUB_OPT_H_ */
swem/player-git-svn
server/drivers/localization/ekfvloc/sub_opt.hh
C++
gpl-2.0
1,106
//SpikeStream includes #include "Globals.h" #include "NetworkDisplay.h" #include "ConnectionGroupModel.h" #include "SpikeStreamException.h" using namespace spikestream; //Qt includes #include <QDebug> #include <QIcon> /*! Constructor */ ConnectionGroupModel::ConnectionGroupModel() : QAbstractTableModel(){ connect(Globals::getEventRouter(), SIGNAL(networkChangedSignal()), this, SLOT(loadConnectionGroups())); connect(Globals::getEventRouter(), SIGNAL(showAllOrNoneConnectionsSignal()), this, SLOT(showAllOrNone())); } /*! Destructor */ ConnectionGroupModel::~ConnectionGroupModel(){ } /*--------------------------------------------------------*/ /*------- PUBLIC METHODS -------*/ /*--------------------------------------------------------*/ /*! Clears the list of selected neuron groups */ void ConnectionGroupModel::clearSelection(){ selectionMap.clear(); } /*! Inherited from QAbstractTableModel. Returns the number of columns in the model */ int ConnectionGroupModel::columnCount(const QModelIndex&) const{ return NUM_COLS; } /*! Inherited from QAbstractTableModel. Returns the data at the specified model index ready to be displayed in the way requested */ QVariant ConnectionGroupModel::data(const QModelIndex & index, int role) const{ //Return invalid index if index is invalid or no network loaded if (!index.isValid()) return QVariant(); if(!Globals::networkLoaded()) return QVariant(); //Check rows and columns are in range if (index.row() < 0 || index.row() >= rowCount() || index.column() < 0 || index.column() >= columnCount()) return QVariant(); //Return appropriate data if (role == Qt::DisplayRole){ if(index.column() == ID_COL) return conGrpInfoList[index.row()].getID(); if(index.column() == DESC_COL) return conGrpInfoList[index.row()].getDescription(); if(index.column() == SIZE_COL) return conGrpSizeList[index.row()]; if(index.column() == FROM_NEUR_ID_COL) return conGrpInfoList[index.row()].getFromNeuronGroupID(); if(index.column() == T0_NEUR_ID_COL) return conGrpInfoList[index.row()].getToNeuronGroupID(); if(index.column() == SYNAPSE_TYPE_COL) return conGrpInfoList[index.row()].getSynapseTypeID(); } //Icons if (role == Qt::DecorationRole){ if(index.column() == VIS_COL ){ if(Globals::getNetworkDisplay()->connectionGroupVisible(conGrpInfoList[index.row()].getID())) return QIcon(Globals::getSpikeStreamRoot() + "/images/visible.xpm"); return QIcon(Globals::getSpikeStreamRoot() + "/images/hidden.xpm"); } if(index.column() == PARAM_COL){ return QIcon(Globals::getSpikeStreamRoot() + "/images/parameters.xpm"); } } if(role == Qt::SizeHintRole){ if(index.column() == PARAM_COL){ return QSize(50, 18); } } //Check boxes if(role == Qt::CheckStateRole){ if(index.column() == SELECT_COL){ if(selectionMap.contains(index.row())){ return true; } else { return false; } } } //If we have reached this point ignore request return QVariant(); } /*! Returns the connection group info corresponding to a particular row or throws an exception if this cannot be found. */ ConnectionGroupInfo ConnectionGroupModel::getInfo(const QModelIndex & index){ if(index.row() >= conGrpInfoList.size()) throw SpikeStreamException("Index out of range: " + QString::number(index.row())); return conGrpInfoList[index.row()]; } /*! Returns the parameters associated with a connection group */ QHash<QString, double> ConnectionGroupModel::getParameters(int row){ if(row >= rowCount()) throw SpikeStreamException("Failed to get parameters: row out of range: " + QString::number(row)); return conGrpInfoList[row].getParameterMap(); } /*! Returns the IDs of the selected neuron groups */ QList<unsigned int> ConnectionGroupModel::getSelectedConnectionGroupIDs(){ //Double check lengths if(conGrpInfoList.size() < selectionMap.size()) throw SpikeStreamException("There are more selected indexes than indexes"); QList<unsigned int> conGrpIDList; foreach(unsigned int index, selectionMap.keys()){ conGrpIDList.append(conGrpInfoList.at(index).getID()); } //Return list return conGrpIDList; } /*! Reloads the list of connection groups */ void ConnectionGroupModel::reload(){ loadConnectionGroups(); } /*! Selects all or none of the connection groups */ void ConnectionGroupModel::selectAllOrNone(){ //Deselect all groups if(selectionMap.size() == conGrpInfoList.size()){ selectionMap.clear(); } //Select all groups else{ for(int i=0; i<conGrpInfoList.size(); ++i) selectionMap[i] = true; } reset(); } /*! Shows all or none of the connection groups */ void ConnectionGroupModel::showAllOrNone(){ //Make all groups visible if there are none showing QList<unsigned> visConGrpIds = Globals::getNetworkDisplay()->getVisibleConnectionGroupIDs(); if(visConGrpIds.isEmpty()){ for(int i=0; i<conGrpInfoList.size(); ++i) visConGrpIds.append(conGrpInfoList.at(i).getID()); } //One or more is hidden: make all groups invisible else{ visConGrpIds.clear(); } Globals::getNetworkDisplay()->setVisibleConnectionGroupIDs(visConGrpIds); reset(); } /*! Inherited from QAbstractTableModel */ bool ConnectionGroupModel::setData(const QModelIndex& index, const QVariant&, int) { if (!index.isValid() || !Globals::networkLoaded()) return false; if (index.row() < 0 || index.row() >= rowCount()) return false; //Change visibility of neuron group if(index.column() == VIS_COL){ unsigned int tmpConGrpID = conGrpInfoList[index.row()].getID(); if(Globals::getNetworkDisplay()->connectionGroupVisible(tmpConGrpID)) Globals::getNetworkDisplay()->setConnectionGroupVisibility(tmpConGrpID, false); else Globals::getNetworkDisplay()->setConnectionGroupVisibility(tmpConGrpID, true); //Emit signal that data has changed and return true to indicate data set succesfully. emit dataChanged(index, index); return true; } //Change selection status of connection group if(index.column() == SELECT_COL){ if(selectionMap.contains(index.row())) selectionMap.remove(index.row()); else selectionMap[index.row()] = true; reset(); return true; } //If we have reached this point no data has been set return false; } /*! Inherited from QAbstractTableModel. Returns the header data */ QVariant ConnectionGroupModel::headerData(int section, Qt::Orientation orientation, int role) const{ if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal){ if(section == ID_COL) return "ID"; if(section == DESC_COL) return "Description"; if(section == SIZE_COL) return "Size"; if(section == FROM_NEUR_ID_COL) return "From"; if(section == T0_NEUR_ID_COL) return "To"; if(section == SYNAPSE_TYPE_COL) return "Synapse Type"; if(section == PARAM_COL) return "Parameters"; } return QVariant();//QString("Roow %1").arg(section); } /*! Inherited from QAbstractTableModel. Returns the number of rows in the model. */ int ConnectionGroupModel::rowCount(const QModelIndex&) const{ return conGrpInfoList.size(); } /*! Reloads the current list of connection groups if a network is present */ void ConnectionGroupModel::loadConnectionGroups(){ //Clear current list of neuron group information conGrpInfoList.clear(); conGrpSizeList.clear(); //Get list of current connection group info if(Globals::networkLoaded()) conGrpInfoList = Globals::getNetwork()->getConnectionGroupsInfo(); //Load up sizes of connection groups for(int i=0; i<conGrpInfoList.size(); ++i) conGrpSizeList.append( Globals::getNetwork()->getConnectionCount( conGrpInfoList.at(i).getID() ) ); //Sanity check if(conGrpInfoList.size() != conGrpSizeList.size()) qCritical()<<"Mismatch between list of connection group info and list of connection group size."; //Instruct listening classes to reload data this->reset(); }
nico202/spikestream
applicationlibrary/src/models/ConnectionGroupModel.cpp
C++
gpl-2.0
7,961
<?php // Copyright 2013 Toby Zerner, Simon Zerner // This file is part of esoTalk. Please see the included license file for usage information. if (!defined("IN_ESOTALK")) { exit; } ET::$pluginInfo["Debug"] = array( "name" => "Debug", "description" => "Shows useful debugging information, such as SQL queries, to administrators.", "version" => ESOTALK_VERSION, "author" => "esoTalk Team", "authorEmail" => "support@esotalk.org", "authorURL" => "http://esotalk.org", "license" => "GPLv2" ); /** * Debug Plugin * * Shows useful debugging information, such as SQL queries, to administrators. */ class ETPlugin_Debug extends ETPlugin { /** * The time at which the current query started running. * @var int */ private $queryStartTime; /** * An application backtrace taken before a query is executed, and used to work out which model/method the * query came from. * @var array */ private $backtrace; /** * An array of queries that have been executed. * @var array */ private $queries = array(); /** * Initialize the plugin: turn esoTalk's debug config variable on. * * @return void */ public function init() { parent::init(); // Turn debug mode on. if (!ET::$session->isAdmin()) { return; } ET::$config["esoTalk.debug"] = true; } /** * On all controller initializations, add the debug CSS file to the page. * * @return void */ public function handler_init() { if (!ET::$session->isAdmin()) { return; } ET::$controller->addCSSFile($this->resource("debug.css"), true); ET::$controller->addJSFile($this->resource("debug.js"), true); } /** * Store the current time (before a query is executed) so we can work out how long it took when it finishes. * * @return void */ public function handler_database_beforeQuery($sender, $query) { if (is_object(ET::$session) and !ET::$session->isAdmin()) { return; } $this->queryStartTime = microtime(true); $this->backtrace = debug_backtrace(); } /** * Work out how long the query took to run and add it to the log. * * @return void */ public function handler_database_afterQuery($sender, $result) { if (is_object(ET::$session) and !ET::$session->isAdmin()) { return; } // The sixth item in the backtrace is typically the model. Screw being reliable. $item = $this->backtrace[6]; $method = isset($item["class"]) ? $item["class"] . "::" : ""; $method .= $item["function"] . "()"; // Store the query in our queries array. $this->queries[] = array($result->queryString, round(microtime(true) - $this->queryStartTime, 4), $method); } /** * Render the debug area at the bottom of the page. * * @return void */ function handler_pageEnd($sender) { // Don't proceed if the user is not permitted to see the debug information! if (!ET::$session->isAdmin()) { return; } // Stop the page loading timer. $end = microtime(true); $time = round($end - PAGE_START_TIME, 4); // Output the debug area. echo "<div id='debug'> <div id='debugHdr'><h2>".sprintf(T("Page loaded in %s seconds"), $time) . "</h2></div>"; // Include the geshi library so we can syntax-highlight MySQL queries. include "geshi/geshi.php"; echo "<h3><a href='#' onclick='$(\"#debugQueries\").slideToggle(\"fast\");return false'>" . T("MySQL queries") . " (<span id='debugQueriesCount'>" . count($this->queries) . "</span>)</a></h3> <div id='debugQueries' class='section'>"; foreach ($this->queries as $query) { $geshi = new GeSHi(trim($query[0]), "mysql"); $geshi->set_header_type(GESHI_HEADER_PRE); echo "<div><strong>" . $query[2] . "</strong> <span class='queryTime subText" . ($query[1] > 0.5 ? " warning" : "") . "'>" . $query[1] . "s</span>" . $geshi->parse_code() . "</div>"; } $this->queries = array(); // Output POST + GET + FILES information. echo "</div> <h3><a href='#' onclick='$(\"#debugPostGetFiles\").slideToggle(\"fast\");return false'>".T("POST + GET + FILES information") . "</a></h3> <div id='debugPostGetFiles' class='section'> <p style='white-space:pre' class='fixed' id='debugPost'>\$_POST = "; echo sanitizeHTML(print_r($_POST, true)); echo "</p><p style='white-space:pre' class='fixed' id='debugGet'>\$_GET = "; echo sanitizeHTML(print_r($_GET, true)); echo "</p><p style='white-space:pre' class='fixed' id='debugFiles'>\$_FILES = "; echo sanitizeHTML(print_r($_FILES, true)); echo "</p> </div>"; // Output SESSION + COOKIE information. echo "<h3><a href='#' onclick='$(\"#debugSessionCookie\").slideToggle(\"fast\");return false'>" . T("SESSION + COOKIE information") . "</a></h3> <div id='debugSessionCookie' class='section'><p style='white-space:pre' class='fixed' id='debugSession'>\$_SESSION = "; echo sanitizeHTML(print_r($_SESSION, true)); echo "</p><p style='white-space:pre' class='fixed' id='debugCookie'>\$_COOKIE = "; echo sanitizeHTML(print_r($_COOKIE, true)); echo "</p></div>"; // Hide all panels by default. echo "<script> $(function() { $('#debug .section').hide(); }); </script>"; } // Construct and process the settings form. public function settings($sender) { // Set up the settings form. $form = ETFactory::make("form"); $form->action = URL("admin/plugins/settings/Debug"); // If the form was submitted... if ($form->validPostBack("upgradeDB")) { // Run the upgrade process. ET::upgradeModel()->upgrade(); // Upgrade plugins as well. foreach (ET::$plugins as $name => $plugin) { $plugin->setup(C("$name.version")); } $sender->message(T("message.upgradeSuccessful"), "success"); $sender->redirect(URL("admin/plugins")); } $sender->data("debugSettingsForm", $form); return $this->view("settings"); } }
Felli/fireside
addons/plugins/Debug/plugin.php
PHP
gpl-2.0
6,463
/** * Copyright 2011 Kurtis L. Nusbaum * * This file is part of UDJ. * * UDJ 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. * * UDJ 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 UDJ. If not, see <http://www.gnu.org/licenses/>. */ #include "ActivePlaylistView.hpp" #include "ActivePlaylistModel.hpp" #include "Utils.hpp" #include "Logger.hpp" #include <QHeaderView> #include <QSqlRecord> #include <QAction> #include <QMenu> #include <QContextMenuEvent> namespace UDJ{ ActivePlaylistView::ActivePlaylistView(DataStore* dataStore, QWidget* parent): QTableView(parent), dataStore(dataStore) { setContextMenuPolicy(Qt::CustomContextMenu); setFocusPolicy(Qt::TabFocus); setEditTriggers(QAbstractItemView::NoEditTriggers); model = new ActivePlaylistModel(getDataQuery(), dataStore, this); horizontalHeader()->setStretchLastSection(true); createActions(); setModel(model); setSelectionBehavior(QAbstractItemView::SelectRows); setSelectionMode(QAbstractItemView::ContiguousSelection); configureHeaders(); connect( dataStore, SIGNAL(activePlaylistModified()), model, SLOT(refresh())); connect( this, SIGNAL(activated(const QModelIndex&)), this, SLOT(setCurrentSong(const QModelIndex&))); connect(this, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(handleContextMenuRequest(const QPoint&))); connect( selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(handleSelectionChange(const QItemSelection&, const QItemSelection&))); } void ActivePlaylistView::configureHeaders(){ QSqlRecord record = model->record(); int idIndex = record.indexOf(DataStore::getActivePlaylistLibIdColName()); int downVoteIndex = record.indexOf(DataStore::getDownVoteColName()); int upVoteIndex = record.indexOf(DataStore::getUpVoteColName()); int adderNameIndex = record.indexOf(DataStore::getAdderUsernameColName()); int timeAddedIndex = record.indexOf(DataStore::getTimeAddedColName()); setColumnHidden(idIndex, true); model->setHeaderData( downVoteIndex, Qt::Horizontal, tr("Down Votes"), Qt::DisplayRole); model->setHeaderData( upVoteIndex, Qt::Horizontal, tr("Up Votes"), Qt::DisplayRole); model->setHeaderData( adderNameIndex, Qt::Horizontal, tr("Adder"), Qt::DisplayRole); model->setHeaderData( timeAddedIndex, Qt::Horizontal, tr("Time Added"), Qt::DisplayRole); } void ActivePlaylistView::setCurrentSong(const QModelIndex& index){ Logger::instance()->log("Manual setting of current song"); QSqlRecord songToPlayRecord = model->record(index.row()); QVariant data = songToPlayRecord.value(DataStore::getActivePlaylistLibIdColName()); selectionModel()->clearSelection(); dataStore->setCurrentSong(data.value<library_song_id_t>()); } void ActivePlaylistView::createActions(){ removeSongAction = new QAction(tr("Remove Song"), this); connect( removeSongAction, SIGNAL(triggered()), this, SLOT(removeSongs())); } void ActivePlaylistView::handleContextMenuRequest(const QPoint& /*pos*/){ QMenu contextMenu(this); contextMenu.addAction(removeSongAction); QAction *selected = contextMenu.exec(QCursor::pos()); if(selected==NULL){ selectionModel()->clearSelection(); } } void ActivePlaylistView::removeSongs(){ QSet<library_song_id_t> toRemove = Utils::getSelectedIds<library_song_id_t>( this, model, DataStore::getActivePlaylistLibIdColName()); dataStore->removeSongsFromActivePlaylist(toRemove); selectionModel()->clearSelection(); } void ActivePlaylistView::handleSelectionChange( const QItemSelection& selected, const QItemSelection& /*deselected*/) { if(selected.indexes().size() == 0){ connect( dataStore, SIGNAL(activePlaylistModified()), model, SLOT(refresh())); } else{ disconnect( dataStore, SIGNAL(activePlaylistModified()), model, SLOT(refresh())); } } void ActivePlaylistView::focusOutEvent(QFocusEvent *event){ if(event->reason() != Qt::PopupFocusReason){ selectionModel()->clearSelection(); } } } //end namespace
klnusbaum/UDJ-Desktop-Client
src/ActivePlaylistView.cpp
C++
gpl-2.0
4,615
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Board Class Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("QUT")] [assembly: AssemblyProduct("Board Class Library")] [assembly: AssemblyCopyright("Copyright © QUT 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("db88e36f-8def-4e67-9836-e3aa9cb610ea")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Jaydak54/assignment4
HareAndTortoise/Board Class Library/Properties/AssemblyInfo.cs
C#
gpl-2.0
1,420
#! /usr/bin/env python # -*- coding: utf-8 -*- import gtk # @UnusedImport import gtk.glade import gobject from lib.pycsb19 import recibo from lib.pycsb19 import ordenante import sqlite3 as sqlite import time class Remesas: def __init__(self): self.Llamada="" self.NifOrdenante="" self.CodRemesa="" self.fecha="" glRemesas=gtk.glade.XML("./gld/remesas.glade") self.ventana=glRemesas.get_widget("Remesas") self.ventana.connect("destroy", self.Salir) self.tvRecibos=glRemesas.get_widget("tvRecibos") self.tvRecibos.connect("button_press_event",self.SacaCampos) self.tNombre=glRemesas.get_widget("tNombre") self.tOrdenante=glRemesas.get_widget("tOrdenante") self.tImporte=glRemesas.get_widget("tImporte") self.fecha=glRemesas.get_widget("tFecha") self.btnOrdenante=glRemesas.get_widget("btnSeleccionar") self.btnOrdenante.connect("clicked", self.SelOrdenante) self.btnSalir=glRemesas.get_widget("btnSalir") self.btnSalir.connect("clicked", self.Salir) self.btnAnadir=glRemesas.get_widget("btnAnadir") self.btnAnadir.connect("clicked", self.Anadir) self.btnEliminar=glRemesas.get_widget("btnEliminar") self.btnEliminar.connect("clicked", self.Eliminar) self.btnModificar=glRemesas.get_widget("btnModificar") self.btnModificar.connect("clicked", self.Modificar) self.btnImprimir=glRemesas.get_widget("btnImprimir") self.btnImprimir.connect("clicked", self.Imprimir) self.btnGenerar=glRemesas.get_widget("btnGenerar") self.btnGenerar.connect("clicked", self.Generar) self.btnAyuda=glRemesas.get_widget("btnAyuda") # self.btnAyuda.connect("clicked", self.Ayuda) data=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING) data.clear() self.tvRecibos.set_model(data) column = gtk.TreeViewColumn("Cod ", gtk.CellRendererText(), text=0) self.tvRecibos.append_column(column) column = gtk.TreeViewColumn("Cliente ", gtk.CellRendererText(), text=1) self.tvRecibos.append_column(column) render=gtk.CellRendererText() render.set_property('xalign', 1.0) column = gtk.TreeViewColumn("Importe", render, text=2) self.tvRecibos.append_column(column) def AbreDb(self): self.conexion=sqlite.connect(db="./dbCsb19/db", mode=077) # @UndefinedVariable def CierraDb(self): self.conexion.close() def SacaCampos(self,widget,event): if event.type==5: self.Modificar(widget) def MiraRemesa(self,Nombre): con=sqlite.connect(db="./dbCsb19/db", mode=077) # @UndefinedVariable cursor = con.cursor() #Mira a ver si ya existe la remesa sql="Select count(codigo) from remesas where titulo='"+self.tNombre.get_text()+"'" cursor.execute(sql) if int(cursor.fetchall()[0][0])<>0: #no hay ninguno dado de alta sql="Select titulo, ordenante, importe, codigo from remesas where titulo='"+Nombre+"'" cursor.execute(sql) for x in cursor.fetchall(): item=[] for n in x: item.append(n) # En item[2] esta el importe self.tImporte.set_text(str(item[2])) self.NifOrdenante=item[1] self.CodRemesa=str(item[3]) # miramos el nombre del ordenante sql="Select nombre from ordenantes where nif='"+item[1].split(":")[0]+"' and sufijo='"+item[1].split(":")[1]+"'" cursor.execute(sql) self.tOrdenante.set_text(cursor.fetchall()[0][0]) #Mira el detalle #Si no hay ningun detalle pasa de mirar mas porque si no da error sql="SELECT count(codigo) FROM det_remesas" cursor.execute(sql) if int(cursor.fetchall()[0][0])<>0: sql="SELECT det_remesas.indice, clientes.nombre, det_remesas.importe FROM det_remesas,clientes WHERE clientes.codigo=det_remesas.cliente AND det_remesas.codigo='"+self.CodRemesa+"'" cursor.execute(sql) for x in cursor.fetchall(): item=[] numero=0 for n in x: numero=numero+1 if numero==3: #Todo este rollo es para completar el importe con dos decimales en el treeview cadena=str(n) if cadena.find(".")==-1: cadena=cadena+".00" elif (len(cadena)-1)-cadena.find(".")<2: cadena=cadena+"0" item.append(cadena) else: item.append(n) self.VisualizaDatos(item) con.close() def Eliminar(self, widget): if self.tvRecibos.get_selection().get_selected()[1]<>None: store=self.tvRecibos.get_model() self.AbreDb() c = self.conexion.cursor() #Borramos el recibo sql="delete from det_remesas where codigo="+self.CodRemesa+" and indice="+store[self.tvRecibos.get_cursor()[0][0]][0] c.execute(sql) self.conexion.commit() #Miramos a ver cuanto es el importe de la remesa ahora sql="Select sum(importe) from det_remesas where codigo='"+self.CodRemesa+"'" c.execute(sql) Importe=0.0 Importe=float(c.fetchall()[0][0]) #Mete el importe en la casilla del importe self.tImporte.set_text(str(Importe)) #Actualiza el importe en la base de datos de remesa sql="UPDATE remesas SET importe="+str(Importe)+" WHERE codigo="+self.CodRemesa c.execute(sql) self.conexion.commit() self.CierraDb() store.remove(self.tvRecibos.get_selection().get_selected()[1]) self.tvRecibos.set_model(store) else: d=gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK,"Debe de seleccionar una recibo para poder eliminarlo") d.connect('response', lambda dialog, response: dialog.destroy()) d.show() def MiraOrdenante(self): if self.Otro.CodOrdenante<>"x": if self.Otro.CodOrdenante<>"": self.tOrdenante.set_text(self.Otro.NomOrdenante) self.NifOrdenante=self.Otro.CodOrdenante self.AbreDb() cursor = self.conexion.cursor() #Hay que mirar a ver si es la primera remesa de la base de datos sql="Select count(codigo) from remesas" cursor.execute(sql) if int(cursor.fetchall()[0][0])==0: #Es la primera remesa asin que el codigo es = 1 y solo hay que darla de alta codigo="1" self.CodRemesa=codigo sql="insert into remesas(codigo, titulo, ordenante, generada, importe) values("+codigo+",'" +self.tNombre.get_text()+"','"+self.NifOrdenante+"','NO',0)" cursor.execute(sql) self.conexion.commit() else: #Mira a ver si ya existe la remesa por si es una modificacion del ordenante sql="Select count(codigo) from remesas where titulo='"+self.tNombre.get_text()+"'" cursor.execute(sql) if int(cursor.fetchall()[0][0])==0: #"no hay ninguno dado de alta" # "Ahora miramos a ver cual es el ultimo codigo dado de alta y le sumamos 1" sql="Select max(codigo) from remesas" cursor.execute(sql) codigo=str(int(cursor.fetchall()[0][0])+1) self.CodRemesa=codigo #Ahora la damos de alta sql="insert into remesas(codigo, titulo, ordenante, generada, importe) values("+codigo+",'" +self.tNombre.get_text()+"','"+self.NifOrdenante+"','NO',0)" cursor.execute(sql) self.conexion.commit() else: # "ya esta dado de alta, Hay que hace un Update Tabla" sql="Select codigo from remesas where titulo='"+self.tNombre.get_text()+"'" cursor.execute(sql) codigo=str(cursor.fetchall()[0][0]) self.CodRemesa=codigo sql="UPDATE remesas SET titulo='" +self.tNombre.get_text()+"', ordenante='"+self.NifOrdenante+"' WHERE codigo="+codigo cursor.execute(sql) self.conexion.commit() self.CierraDb() return 0 else: return 1 def VisualizaDatos(self,Datos): store=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING) # @UnusedVariable store=self.tvRecibos.get_model() itr=store.append() store.set(itr,0,Datos[0],1,Datos[1],2,Datos[2]) self.tvRecibos.set_model(store) def MiraRecibos(self): #Aqui se graban los recibos que devuelve la pantalla de recibos if self.VenRecibos.Llamada<>"remesas": if self.VenRecibos.Llamada<>"Salir": #Saca el codigo de la remesa en el improbable caso de que no exista if self.CodRemesa=="": self.AbreDb() cursor = self.conexion.cursor() sql="Select codigo from remesas where titulo='"+self.tNombre.get_text()+"'" cursor.execute(sql) self.CodRemesa=str(cursor.fetchall()[0][0]) self.CierraDb() #lo primero es saber si es una modificacion de un recibo if self.VenRecibos.Modificacion<>"": #Es una modificacion self.AbreDb() cursor = self.conexion.cursor() indice=self.VenRecibos.Modificacion #Modificamos los datos del recibo #sql="Update det_remesas SET cliente=?, importe=?, conceptos=? WHERE codigo='"+self.CodRemesa+"' AND indice='"+indice+"'" #cursor.execute(sql, (self.VenRecibos.CodCliente,float(self.VenRecibos.Importe),self.VenRecibos.Conceptos)) sql="Update det_remesas SET cliente='"+self.VenRecibos.CodCliente+"', importe="+self.VenRecibos.Importe+", conceptos='"+self.VenRecibos.Conceptos+"' WHERE codigo="+self.CodRemesa+" AND indice="+indice cursor.execute(sql) self.conexion.commit() cursor = self.conexion.cursor() #Miramos a ver cuanto es el importe de la remesa ahora sql="Select sum(importe) from det_remesas where codigo="+self.CodRemesa cursor.execute(sql) Importe=float(cursor.fetchall()[0][0]) #Mete el importe en la casilla del importe self.tImporte.set_text(str(Importe)) cursor = self.conexion.cursor() #Actualiza el importe en la base de datos de remesa sql="UPDATE remesas SET importe="+str(Importe)+" WHERE codigo="+self.CodRemesa cursor.execute(sql) #sql="UPDATE remesas SET importe=? WHERE codigo=?" #cursor.execute(sql,(Importe,self.CodRemesa)) self.conexion.commit() #Carga los datos en el treeview store=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING) self.tvRecibos.set_model(store) self.MiraRemesa(self.tNombre.get_text()) self.CierraDb() else: #Es un recibo nuevo self.AbreDb() cursor = self.conexion.cursor() #miramos a ver si es el primer recibo de esta remesa (si el importe es 0) sql="SELECT sum(importe) FROM remesas WHERE codigo="+self.CodRemesa cursor.execute(sql) if float(cursor.fetchall()[0][0])==0: #Es el primero asin que le ponemos el numero 1 indice=1 else: #No es el primero #Miramos a ver el codigo que le corresponde a este recibo sql="SELECT max(indice) FROM det_remesas WHERE codigo='"+self.CodRemesa+"'" cursor.execute(sql) indice=str(int(cursor.fetchall()[0][0])+1) #A�adimos los datos del recibo #sql="insert into det_remesas (codigo,indice, cliente, importe, conceptos) values (?,?,?,?,?)" #cursor.execute(sql, (str(self.CodRemesa),indice , self.VenRecibos.CodCliente, str(self.VenRecibos.Importe), self.VenRecibos.Conceptos)) sql="insert into det_remesas (codigo, indice, cliente, importe, conceptos) values ("+str(self.CodRemesa)+","+str(indice)+",'"+self.VenRecibos.CodCliente+"',"+str(self.VenRecibos.Importe)+",'"+self.VenRecibos.Conceptos+"')" cursor.execute(sql) self.conexion.commit() sql="SELECT sum(importe) FROM det_remesas WHERE codigo='"+self.CodRemesa+"'" cursor.execute(sql) Importe = float(cursor.fetchall()[0][0]) self.tImporte.set_text(str(Importe)) #Actualiza el importe en la base de datos de remesa sql="UPDATE remesas SET importe="+str(Importe)+" WHERE codigo='"+self.CodRemesa+"'" cursor.execute(sql) self.conexion.commit() #Mete los datos del recibo en el TreeView store=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING) self.tvRecibos.set_model(store) self.MiraRemesa(self.tNombre.get_text()) self.CierraDb() else: pass # print "salio por aqui" return 0 else: #print "no Es distinto" return 1 def SelOrdenante(self,widget): #Se llama a la pantalla del ordenante self.Otro=ordenante.Ordenante() self.Otro.Llamada="remesas" #self.Otro.ventana.set_modal(True) self.Otro.CodOrdenante="x" self.timeout= gtk.timeout_add(250, self.MiraOrdenante) def Anadir(self,widget): if self.tNombre.get_text()=="": self.Dialogo("No se puede anadir un recibo si no se le ha dado un nombre a la remesa",2) elif self.tOrdenante.get_text()=="": self.Dialogo("No se puede anadir un recibo si no se ha selecionado el ordenante",2) else: self.VenRecibos=recibo.Recibo() self.VenRecibos.Llamada="remesas" self.VenRecibos.Modificacion="" self.VenRecibos.Remesa=self.tNombre.get_text() #self.VenRecibos.ventana.set_modal(True) self.timeout= gtk.timeout_add(250, self.MiraRecibos) def Modificar(self,widget): store=gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING) # @UnusedVariable store=self.tvRecibos.get_model() if self.tvRecibos.get_cursor()[0]<>None: self.VenRecibos=recibo.Recibo() self.VenRecibos.Llamada="remesas" #Mete el numero de recibo de la remesa self.VenRecibos.Modificacion=store[self.tvRecibos.get_cursor()[0][0]][0] self.AbreDb() cClientes = self.conexion.cursor() sql="SELECT codigo, nombre, banco, oficina, dc, cuenta FROM clientes WHERE nombre='"+store[self.tvRecibos.get_cursor()[0][0]][1]+"'" cClientes.execute(sql) pp=[] pp=cClientes.fetchone() CodCliente=pp[0] self.VenRecibos.tCodCliente.set_text(CodCliente) self.VenRecibos.tNomCliente.set_text(pp[1]) self.VenRecibos.tBanco.set_text(pp[2]) self.VenRecibos.tOficina.set_text(pp[3]) self.VenRecibos.tDc.set_text(pp[4]) self.VenRecibos.tCuenta.set_text(pp[5]) self.VenRecibos.tImporte.set_text(store[self.tvRecibos.get_cursor()[0][0]][2]) cDetalle = self.conexion.cursor() sql="SELECT codigo, cliente, importe, conceptos FROM det_remesas WHERE codigo="+self.CodRemesa+" AND indice="+store[self.tvRecibos.get_cursor()[0][0]][0] cDetalle.execute(sql) n=cDetalle.fetchone()[3].split("�") self.VenRecibos.tConcepto1.set_text(n[0]) self.VenRecibos.tConcepto2.set_text(n[1]) self.VenRecibos.tConcepto3.set_text(n[2]) self.VenRecibos.tConcepto4.set_text(n[3]) self.VenRecibos.tConcepto5.set_text(n[4]) self.VenRecibos.tConcepto6.set_text(n[5]) self.VenRecibos.tConcepto7.set_text(n[6]) self.VenRecibos.tConcepto8.set_text(n[7]) self.VenRecibos.tConcepto9.set_text(n[8]) self.VenRecibos.tConcepto10.set_text(n[9]) self.VenRecibos.tConcepto11.set_text(n[10]) self.VenRecibos.tConcepto12.set_text(n[11]) self.VenRecibos.tConcepto13.set_text(n[12]) self.VenRecibos.tConcepto14.set_text(n[13]) self.VenRecibos.tConcepto15.set_text(n[14]) self.VenRecibos.tConcepto16.set_text(n[15]) self.VenRecibos.Remesa=self.tNombre.get_text() #self.VenRecibos.ventana.set_modal(True) self.timeout= gtk.timeout_add(250, self.MiraRecibos) self.CierraDb() else: d=gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK,"Debe de seleccionar un recibo para poder abrirlo") d.connect('response', lambda dialog, response: dialog.destroy()) d.show() def Imprimir(self,widget): pass def Espacios(self,Numero): d="" for n in range(0,Numero): # @UnusedVariable d=d+" " return d def Ceros(self,Numero): d="" for n in range(0,Numero): # @UnusedVariable d=d+"0" return d def Generar(self,widget): self.Fiche = gtk.FileSelection("Seleccionar Fichero") self.Fiche.connect("destroy", self.CerrarAbrirFichero) self.Fiche.ok_button.connect("clicked", self.FicheroSeleccionado) self.Fiche.cancel_button.connect("clicked", self.CerrarAbrirFichero) self.Fiche.set_filename("") self.Fiche.set_modal(True) self.Fiche.show() def CerrarAbrirFichero(self,widget): self.Fiche.destroy() def FicheroSeleccionado(self, widget): #Cerramos la ventana de seleccionar fichero if self.Fiche.get_filename()[len(self.Fiche.get_filename())-1:len(self.Fiche.get_filename())]<>'\\': self.GrabaCSB(self.Fiche.get_filename()) else: d=gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK,"Debe de introducir el nombre de un fichero para poder grabarlo") d.connect('response', lambda dialog, response: dialog.destroy()) d.show() self.Fiche.destroy() def GrabaCSB(self,Fichero): #Aqui se crea el fichero con el formato CSB19 self.AbreDb() f=open(Fichero,"w") #Cabecera de presentador cur=self.conexion.cursor() sql="SELECT ordenante FROM remesas WHERE codigo="+self.CodRemesa cur.execute(sql) ordenante=cur.fetchall()[0][0] rem=self.conexion.cursor() sql="SELECT nif, sufijo, nombre, banco, oficina, dc, cuenta FROM ordenantes WHERE nif='"+ordenante.split(":")[0]+"' and sufijo='"+ordenante.split(":")[1]+"'" rem.execute(sql) Linea=rem.fetchall()[0] nif=Linea[0] sufijo=Linea[1] nombre=Linea[2] banco=Linea[3] oficina=Linea[4] dc=Linea[5] cuenta=Linea[6] #a�o, mes, dia dia=str(time.localtime()[2]) if len(dia)<2: dia="0"+dia mes=str(time.localtime()[1]) if len(mes)<2: mes="0"+mes ano=str(time.localtime()[0])[2:4] FechaConfeccion=dia+mes+ano #FechaCargo=FechaConfeccion FechaCargo=self.fecha.get_text() #Cambiar la FechaCargo por el valor del texto (casi nada...) if len(nombre)<40: nombre=nombre+self.Espacios(40-len(nombre)) Cadena="5180"+nif+sufijo+FechaConfeccion+self.Espacios(6)+nombre+self.Espacios(20)+banco+oficina+self.Espacios(12)+self.Espacios(40)+"***PyCsb19****"+"\r\n" f.write(Cadena) #Cabecera de Ordenante Cadena="5380"+nif+sufijo+FechaConfeccion+FechaCargo+nombre+banco+oficina+dc+cuenta+self.Espacios(8)+"01"+self.Espacios(10)+self.Espacios(40)+"***PyCsb19****"+"\r\n" f.write(Cadena) #Registros de recibos rec=self.conexion.cursor() sql="SELECT indice, cliente, importe, conceptos FROM det_remesas WHERE codigo="+self.CodRemesa rec.execute(sql) nNumDomiciliaciones=0 nSuma=0.0 nNumRegistrosOrdenante=2 #Se pone con dos porque el fichero ya tiene las 2 cabeceras escritas for remesa in rec.fetchall(): #El indice lo voy a utilizar para el codigo de devolucion Indice=str(remesa[0]) nNumDomiciliaciones=nNumDomiciliaciones+1 if len(Indice)<6: Indice=Indice+self.Espacios(6-len(Indice)) elif len(Indice)>6: Indice=Indice[0:5] Cliente=remesa[1] nSuma=nSuma+remesa[2] Importe=str(remesa[2]) if Importe.find(".")==-1: Importe=Importe+self.Ceros(2) else: if len(Importe.split(".")[1])<2: Importe=Importe.split(".")[0]+Importe.split(".")[1]+self.Ceros(2-len(Importe.split(".")[1])) elif len(Importe.split(".")[1])>2: Importe=Importe.split(".")[0]+Importe.split(".")[1][0:1] else: Importe=Importe.split(".")[0]+Importe.split(".")[1] if len(Importe)<10: Importe=self.Ceros(10-len(Importe))+Importe Conceptos=[] for n in remesa[3].split("�"): if len(n)==0: dato="" elif len(n)<40: dato=n+self.Espacios(40-len(n)) elif len(n)>40: dato=n[0:40] else: dato=n Conceptos.append(dato) #Vamos a por los datos del cliente cli=self.conexion.cursor() sql="SELECT codigo, nif, nombre, direccion, ciudad, cp, banco, oficina, dc, cuenta FROM clientes WHERE codigo='"+Cliente+"'" cli.execute(sql) c=cli.fetchall()[0] if len(c[0])<12: CodCliente=c[0]+self.Espacios(12-len(c[0])) else: CodCliente=c[0] #El nif lo voy a utilizar para el codigo de referencia interna NifCliente=c[1] if len(NifCliente)<10: NifCliente=NifCliente+self.Espacios(10-len(NifCliente)) if len(c[2])<40: NombreCliente=c[2]+self.Espacios(40-len(c[2])) else: NombreCliente=c[2] DireCliente=c[3] # @UnusedVariable CiudadCliente=c[4] # @UnusedVariable CpCliente=c[5] # @UnusedVariable BancoCliente=c[6] OficinaCliente=c[7] DcCliente=c[8] CuentaCliente=c[9] if len(Conceptos[0])<40: Conceptos[0]=Conceptos[0]+self.Espacios(40-len(Conceptos[0])) if len(Conceptos[0])>40: Conceptos[0]=Conceptos[0][0:40] Cadena="5680"+nif+sufijo+CodCliente+NombreCliente+BancoCliente+OficinaCliente+DcCliente+CuentaCliente+Importe+Indice+NifCliente+Conceptos[0]+self.Espacios(8)+"\r\n" f.write(Cadena) nNumRegistrosOrdenante=nNumRegistrosOrdenante+1 #Vamos a ver que pasa con los otros conceptos. if len(Conceptos[1])<>0 or len(Conceptos[2])<>0 or len(Conceptos[3])<>0: if len(Conceptos[1])<>40: Conceptos[1]=Conceptos[1]+self.Espacios(40-len(Conceptos[1])) if len(Conceptos[2])<>40: Conceptos[2]=Conceptos[2]+self.Espacios(40-len(Conceptos[2])) if len(Conceptos[3])<>40: Conceptos[3]=Conceptos[3]+self.Espacios(40-len(Conceptos[3])) Cadena="5681"+nif+sufijo+CodCliente+Conceptos[1]+Conceptos[2]+Conceptos[3]+self.Espacios(14)+"\r\n" f.write(Cadena) nNumRegistrosOrdenante=nNumRegistrosOrdenante+1 if len(Conceptos[4])<>0 or len(Conceptos[5])<>0 or len(Conceptos[6])<>0: if len(Conceptos[4])<>40: Conceptos[4]=Conceptos[4]+self.Espacios(40-len(Conceptos[4])) if len(Conceptos[5])<>40: Conceptos[5]=Conceptos[5]+self.Espacios(40-len(Conceptos[5])) if len(Conceptos[6])<>40: Conceptos[6]=Conceptos[6]+self.Espacios(40-len(Conceptos[6])) Cadena="5682"+nif+sufijo+CodCliente+Conceptos[4]+Conceptos[5]+Conceptos[6]+self.Espacios(14)+"\r\n" f.write(Cadena) nNumRegistrosOrdenante=nNumRegistrosOrdenante+1 if len(Conceptos[7])<>0 or len(Conceptos[8])<>0 or len(Conceptos[9])<>0: if len(Conceptos[7])<>40: Conceptos[7]=Conceptos[7]+self.Espacios(40-len(Conceptos[7])) if len(Conceptos[8])<>40: Conceptos[8]=Conceptos[8]+self.Espacios(40-len(Conceptos[8])) if len(Conceptos[9])<>40: Conceptos[9]=Conceptos[9]+self.Espacios(40-len(Conceptos[9])) Cadena="5683"+nif+sufijo+CodCliente+Conceptos[7]+Conceptos[8]+Conceptos[9]+self.Espacios(14)+"\r\n" f.write(Cadena) nNumRegistrosOrdenante=nNumRegistrosOrdenante+1 if len(Conceptos[10])<>0 or len(Conceptos[11])<>0 or len(Conceptos[12])<>0: if len(Conceptos[10])<>40: Conceptos[10]=Conceptos[10]+self.Espacios(40-len(Conceptos[10])) if len(Conceptos[11])<>40: Conceptos[11]=Conceptos[11]+self.Espacios(40-len(Conceptos[11])) if len(Conceptos[12])<>40: Conceptos[12]=Conceptos[12]+self.Espacios(40-len(Conceptos[12])) Cadena="5684"+nif+sufijo+CodCliente+Conceptos[10]+Conceptos[11]+Conceptos[12]+self.Espacios(14)+"\r\n" f.write(Cadena) nNumRegistrosOrdenante=nNumRegistrosOrdenante+1 if len(Conceptos[13])<>0 or len(Conceptos[14])<>0 or len(Conceptos[15])<>0: if len(Conceptos[13])<>40: Conceptos[13]=Conceptos[13]+self.Espacios(40-len(Conceptos[13])) if len(Conceptos[14])<>40: Conceptos[14]=Conceptos[14]+self.Espacios(40-len(Conceptos[14])) if len(Conceptos[15])<>40: Conceptos[15]=Conceptos[15]+self.Espacios(40-len(Conceptos[15])) Cadena="5685"+nif+sufijo+CodCliente+Conceptos[13]+Conceptos[14]+Conceptos[15]+self.Espacios(14)+"\r\n" f.write(Cadena) nNumRegistrosOrdenante=nNumRegistrosOrdenante+1 #La linea de datos del cliente no se implementa de monento #Cadena="5686"+nif+sufijo+CodCliente #Linea de totales de ordenante Suma=str(nSuma) if Suma.find(".")==-1: Suma=Suma+self.Ceros(2) else: if len(Suma.split(".")[1])<2: Suma=Suma.split(".")[0]+Suma.split(".")[1]+self.Ceros(2-len(Suma.split(".")[1])) elif len(Suma.split(".")[1])>2: Suma=Suma.split(".")[0]+Suma.split(".")[1][0:1] else: Suma=Suma.split(".")[0]+Suma.split(".")[1] if len(Suma)<10: Suma=self.Ceros(10-len(Suma))+Suma NumDomiciliaciones=str(nNumDomiciliaciones) if len(NumDomiciliaciones)<10: NumDomiciliaciones=self.Ceros(10-len(NumDomiciliaciones))+NumDomiciliaciones NumRegistrosOrdenante=str(nNumRegistrosOrdenante) if len(NumRegistrosOrdenante)<10: NumRegistrosOrdenante=self.Ceros(10-len(NumRegistrosOrdenante))+NumRegistrosOrdenante Cadena="5880"+nif+sufijo+self.Espacios(12)+self.Espacios(40)+self.Espacios(20)+Suma+self.Espacios(6)+NumDomiciliaciones+NumRegistrosOrdenante+self.Espacios(20)+"*****PyCsb19******"+"\r\n" f.write(Cadena) nNumRegistrosOrdenante=nNumRegistrosOrdenante+1 NumRegistrosOrdenante=str(nNumRegistrosOrdenante+1) if len(NumRegistrosOrdenante)<10: NumRegistrosOrdenante=self.Ceros(10-len(NumRegistrosOrdenante))+NumRegistrosOrdenante #Linea de total general Cadena="5980"+nif+sufijo+self.Espacios(12)+self.Espacios(40)+"0001"+self.Espacios(16)+Suma+self.Espacios(6)+NumDomiciliaciones+NumRegistrosOrdenante+self.Espacios(20)+"*****PyCsb19******"+"\r\n" f.write(Cadena) f.close() self.CierraDb() self.Dialogo("El fichero se ha generado correctamente",1) def Dialogo(self, msg, Tipo): if Tipo==1: dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK,msg) elif Tipo==2: dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_CLOSE,msg) elif Tipo==3: dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO,msg) elif Tipo==4: dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL,msg) dialog.connect('response', lambda dialog, response: dialog.destroy()) dialog.show() return dialog def Salir(self,*args): #True if self.Llamada<>"": self.ventana.hide() self.Cliente="" self.Importe="" self.Llamada="" return True else: gtk.main_quit() def Main(self): self.Llamada="" gtk.main() if __name__ == "__main__": gtk.rc_parse("gtkrc.txt") ven = Remesas() ven.Main()
pacoqueen/ginn
ginn/lib/pycsb19/remesas.py
Python
gpl-2.0
32,357
<?php /** * @version $Id: rokpad.php 9100 2013-04-03 23:19:42Z djamil $ * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only */ defined('_JEXEC') or die; /** * */ class plgEditorRokPad extends JPlugin { /** * @var bool */ protected static $_assets = false; /** * @var string */ protected $_version = '2.1.4'; /** * @var string */ protected $_basepath = '/plugins/editors/rokpad/'; /** * @var */ protected $_acepath; /** * @param $subject * @param $config */ public function __construct(&$subject, $config) { parent::__construct($subject, $config); $this->loadLanguage(); } /** * @return string */ public function onInit() { JHtml::_('behavior.framework', true); $document = JFactory::getDocument(); $this->_basepath = JURI::root(true) . $this->_basepath; $this->_acepath = $this->_basepath . 'ace/'; if (!self::$_assets) { /* $document->addStyleSheet($this->_basepath . 'assets/css/rokpad.css'.$this->_appendCacheToken()); $document->addScript($this->_acepath . 'ace.js'.$this->_appendCacheToken()); $document->addScript($this->_basepath . 'assets/js/rokpad.js'.$this->_appendCacheToken()); */ $document->addScriptDeclaration($this->getJSParams()); $this->compileLess(); $this->compileJS(); self::$_assets = true; } return ''; } /** * @param $id * * @return string */ public function onSave($id) { return "RokPadData.insertion.onSave('".$id."');\n"; } /** * @param $id * * @return string */ public function onGetContent($id) { return "RokPadData.insertion.onGetContent('".$id."');\n"; } /** * @param $id * @param $content * * @return string */ public function onSetContent($id, $content) { return "RokPadData.insertion.onSetContent('".$id."', ".$content.");\n"; } /** * @return bool */ public function onGetInsertMethod() { static $done = false; // Do this only once. if (!$done) { $done = true; $doc = JFactory::getDocument(); $js = "\tfunction jInsertEditorText(text, editor) {\n RokPadData.insertion.onGetInsertMethod(text, editor);\n }\n"; $doc->addScriptDeclaration($js); } return true; } /** * @param $name * @param $content * @param $width * @param $height * @param $col * @param $row * @param bool $buttons * @param null $id * @param null $asset * @param null $author * @param array $params * * @return string */ public function onDisplay($name, $content, $width, $height, $col, $row, $buttons = true, $id = null, $asset = null, $author = null, $params = array()) { if (empty($id)) $id = $name; $buttons = $this->_displayButtons($id, $buttons, $asset, $author); $html = array(); $html[] = '<div class="rokpad-editor-wrapper" data-rokpad-editor="' . $id . '">'; $html[] = ' <div class="rokpad-toolbar">'; $html[] = ' <ul class="rok-left">'; $html[] = ' <li><div class="rok-button rok-button-primary rokpad-tip" data-original-title="Ajax Save" data-placement="below-left" data-rokpad-save><i class="rokpad-icon-save"></i> save</div></li>'; $html[] = ' <li class="rok-buttons-group">'; $html[] = ' <div class="rok-button rok-button-disabled rokpad-tip" data-original-title="Undo" data-placement="below" data-rokpad-undo><i class="rokpad-icon-undo"></i></div>'; $html[] = ' <div class="rok-button rok-button-disabled rokpad-tip" data-original-title="Redo" data-placement="below" data-rokpad-redo><i class="rokpad-icon-redo"></i></div>'; $html[] = ' </li>'; $html[] = ' <li><div class="rok-button rokpad-tip" data-original-title="Find..." data-placement="below" data-rokpad-find><i class="rokpad-icon-search"></i></div></li>'; $html[] = ' <li>'; $html[] = ' <div class="rok-dropdown-group">'; $html[] = ' <div class="rok-button" data-rokpad-toggle="extras"><i class="rokpad-icon-more"></i><span class="caret"></span></div>'; $html[] = ' <ul class="rok-dropdown" data-rokpad-dropdown="extras">'; $html[] = ' <li><a href="#" data-rokpad-goto>Goto Line...</a></li>'; $html[] = ' <li><a href="#" data-rokpad-find-replace>Find and Replace...</a></li>'; $html[] = ' <li class="divider"></li>'; $html[] = ' <li><a href="#" data-rokpad-beautify>Beautify HTML</a></li>'; $html[] = ' </ul>'; $html[] = ' </div>'; $html[] = ' </li>'; $html[] = ' </ul>'; $html[] = ' <ul class="rok-right">'; $html[] = ' <li>'; $html[] = ' <div class="rok-popover-group">'; $html[] = ' <div class="rok-button rokpad-tip" data-original-title="Editor Settings" data-placement="below" data-rokpad-toggle="settings"><i class="rokpad-icon-settings"></i></div>'; $html[] = ' <div class="rok-popover" data-rokpad-popover="settings">'; $html[] = ' <ul class="options">'; $html[] = ' <li><span class="title">Theme</span><span class="input"><select data-rokpad-options="theme" class="chzn-done"></select></span></li>'; $html[] = ' <li><span class="title">Font Size</span><span class="input"><select data-rokpad-options="font-size" class="chzn-done"></select></span></li>'; $html[] = ' <li><span class="title">Code Folding</span><span class="input"><select data-rokpad-options="fold-style" class="chzn-done"><option value="manual">Manual</option><option value="markbegin">Mark Begin</option><option value="markbeginend">Mark Begin and End</option></select></span></li>'; $html[] = ' <li><span class="title">Soft Wrap</span><span class="input"><select data-rokpad-options="use-wrap-mode" class="chzn-done"><option value="off">Off</option><option value="40">40 Chars</option><option value="80">80 Chars</option><option value="free">Free</option></select></span></li>'; $html[] = ' <li><span class="title-checkbox">Full Line Selection</span><span class="input"><input type="checkbox" data-rokpad-options="selection-style" /></span></li>'; $html[] = ' <li><span class="title-checkbox">Highlight Active Line</span><span class="input"><input type="checkbox" data-rokpad-options="highlight-active-line" /></span></li>'; $html[] = ' <li><span class="title-checkbox">Show Invisibles</span><span class="input"><input type="checkbox" data-rokpad-options="show-invisibles" /></span></li>'; $html[] = ' <li><span class="title-checkbox">Show Gutter</span><span class="input"><input type="checkbox" data-rokpad-options="show-gutter" /></span></li>'; $html[] = ' <li><span class="title-checkbox">Show Print Margin</span><span class="input"><input type="checkbox" data-rokpad-options="show-print-margin" /></span></li>'; $html[] = ' <li><span class="title-checkbox">Highlight Selected Word</span><span class="input"><input type="checkbox" data-rokpad-options="highlight-selected-word" /></span></li>'; $html[] = ' <li><span class="title-checkbox">Autohide Fold Widgets</span><span class="input"><input type="checkbox" data-rokpad-options="fade-fold-widgets" /></span></li>'; $html[] = ' <li><span class="title-checkbox">Autosave</span><span class="input"><input type="checkbox" data-rokpad-options="autosave-enabled" /> <input type="text" data-rokpad-options="autosave-time" /> mins</span></li>'; $html[] = ' </ul>'; $html[] = ' <div class="rok-popover-arrow"></div>'; $html[] = ' </div>'; $html[] = ' </div>'; $html[] = ' </li>'; $html[] = ' <li>'; $html[] = ' <div class="rok-popover-group">'; $html[] = ' <div class="rok-button rokpad-tip" data-original-title="Keyboard Shortcuts" data-placement="below" data-rokpad-toggle="keyboard"><i class="rokpad-icon-keyboard"></i></div>'; $html[] = ' <div class="rok-popover rok-popover-keyboard" data-rokpad-popover="keyboard">'; $html[] = ' <ul class="keyboard">'; $html[] = ' <li class="rokpad-keyboard-mac">'; $html[] = ' <span class="rokpad-kbd-win"></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">L</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Center selection</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">U</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">U</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Change to uppser case</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">U</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">U</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Change to lower case</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">ALT</span> + <span class="rokpad-key">&darr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">OPT</span> + <span class="rokpad-key">&darr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Copy lines down</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">ALT</span> + <span class="rokpad-key">&uarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">OPT</span> + <span class="rokpad-key">&uarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Copy lines up</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">S</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">S</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Save</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">F</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">F</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Find</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">E</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">E</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Use selection for find</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">K</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">G</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Find next</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">K</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">G</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Find previous</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">0</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">0</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Fold all</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">0</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">0</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Unfold all</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">&darr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&darr;</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">N</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Go line down</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">&uarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&uarr;</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">P</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Go line up</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">END</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">&darr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984</span> + <span class="rokpad-key">END</span> <br /><span class="rokpad-key">&#8984</span> + <span class="rokpad-key">&darr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Go to end</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">&larr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&larr;</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">B</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Go to left</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">L</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">L</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Goto line</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">&rarr;</span> <br /><span class="rokpad-key">END</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">&rarr;</span> <br /><span class="rokpad-key">END</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">E</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Goto to line end</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">&larr;</span> <br /><span class="rokpad-key">HOME</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">&larr;</span> <br /><span class="rokpad-key">HOME</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">A</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Goto to line start</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">PAGEDOWN</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">PAGEDOWN</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">V</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Goto to page down</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">PAGEUP</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">PAGEUP</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Goto to page up</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">&rarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&rarr;</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">F</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Go to right</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">HOME</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">&uarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">HOME</span> <br /><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">&uarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Go to start</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">&larr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">&larr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Go to word left</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">&rarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">&rarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Go to word right</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">TAB</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">TAB</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Indent</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">&darr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">&darr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Move lines down</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">&uarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">&uarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Move lines up</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">TAB</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">TAB</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Outdent</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">INS</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">INSERT</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Overwrite</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac">'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">PAGEDOWN</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Pagedown</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac">'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">PAGEUP</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Pageup</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">Z</span> <br /><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">Y</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">Z</span> <br /><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">Y</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Redo</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">D</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">D</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Remove line</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac">'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">K</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Remove to line end</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac">'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">BACKSPACE</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Remove to line start</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac">'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">BACKSPACE</span> <br /> <span class="rokpad-key">CTRL</span> + <span class="rokpad-key">ALT</span> + <span class="rokpad-key">BACKSPACE</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Remove word left</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac">'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">DELETE</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Remove word right</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">A</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">A</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select all</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&darr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&darr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select down</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&larr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&larr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select left</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">END</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">END</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select line end</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">HOME</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">HOME</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select line start</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">PAGEDOWN</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">PAGEDOWN</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select page down</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">PAGEUP</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">PAGEUP</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select page up</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&rarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&rarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select right</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">END</span> <br /> <span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&darr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&darr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select to end</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&rarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&rarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select to line end</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&larr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&larr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select to line start</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">HOME</span> <br /> <span class="rokpad-key">ALT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&uarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&uarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select to start</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&uarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&uarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select up</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&larr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&larr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select word left</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&rarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">OPT</span> + <span class="rokpad-key">SHIFT</span> + <span class="rokpad-key">&rarr;</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Select word right</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac">'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">O</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Split line</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">7</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">7</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Toggle comment</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">T</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">T</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Transpose letters</span>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-keyboard-mac rokpad-keyboard-win">'; $html[] = ' <span class="rokpad-kbd-win"><span class="rokpad-key">CTRL</span> + <span class="rokpad-key">Z</span></span>'; $html[] = ' <span class="rokpad-kbd-mac"><span class="rokpad-key">&#8984;</span> + <span class="rokpad-key">Z</span></span>'; $html[] = ' <span class="rokpad-kbd-desc">Undo</span>'; $html[] = ' </li>'; $html[] = ' </ul>'; $html[] = ' <div class="rok-popover-arrow"></div>'; $html[] = ' </div>'; $html[] = ' </div>'; $html[] = ' </li>'; $html[] = ' <li><div class="rok-button rokpad-tip" data-original-title="Fullscreen / Windowed" data-placement="below-right" data-rokpad-fullscreen><i class="rokpad-icon-fullscreen"></i></div></li>'; //$html[] = ' <li><div class="rok-button rok-button-red"></div></li>'; //$html[] = ' <li><div class="rok-button rok-button-black"></div></li>'; $html[] = ' </ul>'; $html[] = ' </div>'; $html[] = ' <div class="rokpad-shortcodes">'; $html[] = ' <ul>'; $html[] = ' <li data-rokpad-shortcode="<h1>{data}{cur}</h1>" class="rokpad-tip" data-original-title="Heading 1" data-placement="below-left"><i class="rokpad-icon-h1"></i></li>'; $html[] = ' <li data-rokpad-shortcode="<h2>{data}{cur}</h2>" class="rokpad-tip" data-original-title="Heading 2" data-placement="below"><i class="rokpad-icon-h2"></i></li>'; $html[] = ' <li data-rokpad-shortcode="<h3>{data}{cur}</h3>" class="rokpad-tip" data-original-title="Heading 3" data-placement="below"><i class="rokpad-icon-h3"></i></li>'; $html[] = ' <li data-rokpad-shortcode="<strong>{data}{cur}</strong>" class="rokpad-tip" data-original-title="Bold/Strong Text" data-placement="below"><i class="rokpad-icon-bold"></i></li>'; $html[] = ' <li data-rokpad-shortcode="<em>{data}{cur}</em>" class="rokpad-tip" data-original-title="Emphasized Text" data-placement="below"><i class="rokpad-icon-italic"></i></li>'; $html[] = ' <li data-rokpad-shortcode="<u>{data}{cur}</u>" class="rokpad-tip" data-original-title="Underlined Text" data-placement="below"><i class="rokpad-icon-underline"></i></li>'; $html[] = ' <li data-rokpad-shortcode="<ol>{n}{t}<li>{data}{cur}</li>{n}</ol>" class="rokpad-tip" data-original-title="Ordered List" data-placement="below"><i class="rokpad-icon-olist"></i></li>'; $html[] = ' <li data-rokpad-shortcode="<ul>{n}{t}<li>{data}{cur}</li>{n}</ul>" class="rokpad-tip" data-original-title="Unordered List" data-placement="below"><i class="rokpad-icon-ulist"></i></li>'; $html[] = ' <li data-rokpad-shortcode="<img src=\'{cur}\' alt=\'{data}\' />" class="rokpad-tip" data-original-title="Image" data-placement="below"><i class="rokpad-icon-image"></i></li>'; $html[] = ' <li data-rokpad-shortcode="<p>{data}{cur}</p>" class="rokpad-tip" data-original-title="Paragraph" data-placement="below"><i class="rokpad-icon-paragraph"></i></li>'; $html[] = ' <li data-rokpad-shortcode="<a href=\'{cur}\'>{data}</a>" class="rokpad-tip" data-original-title="Link" data-placement="below"><i class="rokpad-icon-link"></i></li>'; $html[] = ' <li data-rokpad-shortcode="<hr />" class="rokpad-tip" data-original-title="Horizontal Rule (<hr />)" data-placement="below"><i class="rokpad-icon-hr"></i></li>'; $html[] = ' <li data-rokpad-shortcode="<{cur}>{data}</{cur}>" class="rokpad-tip" data-original-title="Universal Tag. Click and start typing the desired tag (ie, div). Hit ESC when done." data-placement="below"><i class="rokpad-icon-universal"></i></li>'; $html[] = ' </ul>'; $html[] = ' </div>'; $html[] = ' <div class="rokpad-editor-container" data-rokpad-container>'; $html[] = ' <div id="' . $id . '-rokpad-editor" class="rokpad-editor"></div>'; $html[] = ' <textarea data-rokpad-original class="rokpad-editor-original" name="' . $name . '" id="' . $id . '" cols="' . $col . '" rows="' . $row . '">' . $content . '</textarea>'; $html[] = ' </div>'; $html[] = ' <div class="rokpad-actionbar" data-rokpad-actionbar>'; $html[] = ' <ul>'; $html[] = ' <li class="rokpad-column-1">'; $html[] = ' <div class="rok-buttons-group">'; $html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Regular Expression" data-placement="above-left" data-rokpad-action-setting="regExp"><i class="rokpad-icon-regexp"></i></div>'; $html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Case Sensitive" data-placement="above" data-rokpad-action-setting="caseSensitive"><i class="rokpad-icon-casesensi"></i></div>'; $html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Whole Word" data-placement="above" data-rokpad-action-setting="wholeWord"><i class="rokpad-icon-wholeword"></i></div>'; $html[] = ' </div>'; $html[] = ' <div class="rok-buttons-group">'; $html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Reverse Direction" data-placement="above" data-rokpad-action-setting="backwards"><i class="rokpad-icon-reversedir"></i></div>'; $html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="Wrap" data-placement="above" data-rokpad-action-setting="wrap"><i class="rokpad-icon-wrap"></i></div>'; $html[] = ' <div class="rok-button rok-button-unchecked rokpad-tip" data-original-title="In Selection" data-placement="above" data-rokpad-action-setting="scope"><i class="rokpad-icon-inselection"></i></div>'; $html[] = ' </div>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-column-2">'; $html[] = ' <div class="rok-input-wrapper rok-input-row-1" data-rokpad-action-method="find"><input type="text" placeholder="Find..." /></div>'; $html[] = ' <div class="rok-input-wrapper rok-input-row-1" data-rokpad-action-method="goto"><input type="text" placeholder="Goto Line..." /></div>'; $html[] = ' <div class="rok-input-wrapper rok-input-row-2" data-rokpad-action-method="replace"><input type="text" placeholder="Replace..." /></div>'; $html[] = ' </li>'; $html[] = ' <li class="rokpad-column-3">'; $html[] = ' <div class="rok-input-row-1">'; $html[] = ' <div class="rok-buttons-group">'; $html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="find">Find</div>'; $html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="findAll">All</div>'; $html[] = ' </div>'; $html[] = ' <div class="rok-buttons-group">'; $html[] = ' <div class="rok-button rokpad-tip" data-original-title="Find Previous" data-placement="above" data-rokpad-action="findPrevious"><i class="rokpad-icon-prev"></i></div>'; $html[] = ' <div class="rok-button rokpad-tip" data-original-title="Find Next" data-placement="above-right" data-rokpad-action="findNext"><i class="rokpad-icon-next"></i></div>'; $html[] = ' </div>'; $html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="goto">Goto Line</div>'; $html[] = ' </div>'; $html[] = ' <div class="rok-input-row-2">'; $html[] = ' <div class="rok-buttons-group">'; $html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="replace">Replace</div>'; $html[] = ' <div class="rok-button rok-button-noicon" data-rokpad-action="replaceAll">All</div>'; $html[] = ' </div>'; $html[] = ' </div>'; $html[] = ' </li>'; $html[] = ' </ul>'; $html[] = ' </div>'; $html[] = ' <div class="rokpad-statusbar">'; $html[] = ' <ul data-rokpad-dropdown="mode" class="rok-dropdown">'; $html[] = ' <li data-rokpad-mode="css"><a href="#">CSS</a></li>'; $html[] = ' <li data-rokpad-mode="html"><a href="#">HTML</a></li>'; $html[] = ' <li data-rokpad-mode="javascript"><a href="#">JavaScript</a></li>'; $html[] = ' <li data-rokpad-mode="json"><a href="#">JSON</a></li>'; $html[] = ' <li data-rokpad-mode="less"><a href="#">LESS</a></li>'; $html[] = ' <li data-rokpad-mode="markdown"><a href="#">Markdown</a></li>'; $html[] = ' <li data-rokpad-mode="php"><a href="#">PHP</a></li>'; $html[] = ' <li data-rokpad-mode="sql"><a href="#">SQL</a></li>'; $html[] = ' <li data-rokpad-mode="text"><a href="#">Plain Text</a></li>'; $html[] = ' <li data-rokpad-mode="textile"><a href="#">Textile</a></li>'; $html[] = ' <li data-rokpad-mode="xml"><a href="#">XML</a></li>'; $html[] = ' </ul>'; $html[] = ' <ul data-rokpad-dropdown="tabs" class="rok-dropdown">'; $html[] = ' <li data-rokpad-softtabs="0"><a href="#">Indent Using Spaces</a></li>'; $html[] = ' <li class="divider"></li>'; $html[] = ' <li data-rokpad-tabsize="1"><a href="#">Tab Width: 1</a></li>'; $html[] = ' <li data-rokpad-tabsize="2"><a href="#">Tab Width: 2</a></li>'; $html[] = ' <li data-rokpad-tabsize="3"><a href="#">Tab Width: 3</a></li>'; $html[] = ' <li data-rokpad-tabsize="4"><a href="#">Tab Width: 4</a></li>'; $html[] = ' <li data-rokpad-tabsize="5"><a href="#">Tab Width: 5</a></li>'; $html[] = ' <li data-rokpad-tabsize="6"><a href="#">Tab Width: 6</a></li>'; $html[] = ' <li data-rokpad-tabsize="7"><a href="#">Tab Width: 7</a></li>'; $html[] = ' <li data-rokpad-tabsize="8"><a href="#">Tab Width: 8</a></li>'; $html[] = ' </ul>'; $html[] = ' <ul class="rok-left">'; $html[] = ' <li data-rokpad-lastsave>Last save: <span data-rokpad-savedate>never</span></li>'; $html[] = ' </ul>'; $html[] = ' <ul class="rok-right">'; $html[] = ' <li data-rokpad-tabsize data-rokpad-toggle="tabs">Tab Size: <span>4</span></li>'; $html[] = ' <li class="divider"></li>'; $html[] = ' <li data-rokpad-mode data-rokpad-toggle="mode">Mode: <span>HTML</span></li>'; $html[] = ' </ul>'; $html[] = ' </div>'; $html[] = '</div>'; $html[] = $buttons; $output = ""; $output .= implode("\n", $html); return $output; } /** * @param $name * @param $buttons * @param $asset * @param $author * * @return string */ protected function _displayButtons($name, $buttons, $asset, $author) { // Load modal popup behavior JHtml::_('behavior.modal', 'a.modal-button'); $args['name'] = $name; $args['event'] = 'onGetInsertMethod'; $return = ''; $results[] = $this->update($args); foreach ($results as $result) { if (is_string($result) && trim($result)) { $return .= $result; } } if (is_array($buttons) || (is_bool($buttons) && $buttons)) { $results = $this->_subject->getButtons($name, $buttons, $asset, $author); $version = new JVersion(); if (version_compare($version->getShortVersion(), '3.0', '>=')) { /* * This will allow plugins to attach buttons or change the behavior on the fly using AJAX */ $return .= "\n<div id=\"editor-xtd-buttons\" class=\"btn-toolbar pull-left\">\n"; $return .= "\n<div class=\"btn-toolbar\">\n"; foreach ($results as $button) { /* * Results should be an object */ if ( $button->get('name') ) { $modal = ($button->get('modal')) ? ' class="modal-button btn"' : null; $href = ($button->get('link')) ? ' class="btn" href="'.JURI::base().$button->get('link').'"' : null; $onclick = ($button->get('onclick')) ? ' onclick="'.$button->get('onclick').'"' : ''; $title = ($button->get('title')) ? $button->get('title') : $button->get('text'); $return .= '<a' . $modal . ' title="' . $title . '"' . $href . $onclick . ' rel="' . $button->get('options') . '"><i class="icon-' . $button->get('name'). '"></i> ' . $button->get('text') . "</a>\n"; } } $return .= "</div>\n"; $return .= "</div>\n"; } else { // This will allow plugins to attach buttons or change the behavior on the fly using AJAX $return .= "\n".'<div id="editor-xtd-buttons"><div class="btn-toolbar pull-left rokpad-clearfix">'."\n"; foreach ($results as $button) { // Results should be an object if ($button->get('name')) { $modal = ($button->get('modal')) ? 'class="modal-button"' : null; $href = ($button->get('link')) ? 'href="' . JURI::base() . $button->get('link') . '"' : null; $onclick = ($button->get('onclick')) ? 'onclick="' . $button->get('onclick') . '"' : null; $title = ($button->get('title')) ? $button->get('title') : $button->get('text'); $return .= "\n".'<div class="button2-left"><div class="' . $button->get('name') . '">'; $return .= '<a ' . $modal . ' title="' . $title . '" ' . $href . ' ' . $onclick . ' rel="' . $button->get('options') . '">'; $return .= $button->get('text') . '</a>'."\n".'</div>'."\n".'</div>'."\n"; } } $return .= '</div></div>'."\n"; } } return $return; } /** * @return string */ protected function _appendCacheToken() { return '?cache=' . $this->_version; } /** * */ protected function compileLess() { $document = JFactory::getDocument(); $assets = JPATH_PLUGINS . DIRECTORY_SEPARATOR . 'editors' . DIRECTORY_SEPARATOR . 'rokpad' . DIRECTORY_SEPARATOR . 'assets'; @include_once($assets . '/less/mixins/lessc.inc.php'); if (defined('DEV') && DEV) { try { $css_file = $assets . '/styles/rokpad.css'; @unlink($css_file); lessc::ccompile($assets . '/less/global.less', $css_file); } catch (exception $e) { JError::raiseError('LESS Compiler', $e->getMessage()); } } $document->addStyleSheet($this->_basepath . 'assets/styles/rokpad.css' . $this->_appendCacheToken()); } /** * */ protected function compileJS() { $document = JFactory::getDocument(); $rokpad = JPATH_PLUGINS . DIRECTORY_SEPARATOR . 'editors' . DIRECTORY_SEPARATOR . 'rokpad'; if (defined('DEV') && DEV) { $buffer = ""; $assets = $rokpad . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'js' . DIRECTORY_SEPARATOR; $app = $rokpad . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR; $files = array( $assets . 'moofx', $app. 'respond', $app . 'jstorage', $app . 'beautify-html', $app . 'Twipsy', $app . 'RokPad', $app . 'RokPad.ACE', $app. 'RokPad.Functs' ); foreach ($files as $file) { $file = $file . '.js'; $content = false; if (file_exists($file)) $content = file_get_contents($file); $buffer .= (!$content) ? "\n\n !!! File not Found: " . $file . " !!! \n\n" : $content; } file_put_contents($assets . 'rokpad.js', $buffer); } $document->addScript($this->_basepath . 'ace/ace.js' . $this->_appendCacheToken()); $document->addScript($this->_basepath . 'assets/js/rokpad.js' . $this->_appendCacheToken()); } /** * @return string */ protected function getJSParams() { $document = JFactory::getDocument(); $params = $this->params->toArray(); if (!array_key_exists('theme', $params)) { $params = array( 'theme' => 'fluidvision', 'font-size' => '12px', 'fold-style' => 'markbeginend', 'use-wrap-mode' => 'free', 'selection-style' => '1', 'highlight-active-line' => '1', 'highlight-selected-word' => '1', 'show-invisibles' => '0', 'show-gutter' => '1', 'show-print-margin' => '1', 'fade-fold-widgets' => '0', 'autosave-enabled' => '0', 'autosave-time' => '5' ); } $data = ""; $data .= "var RokPadDefaultSettings = {"; foreach ($params as $param => $value) { $data .= "'" . $param . "': '" . $value . "', "; } $data = substr($data, 0, strlen($data) - 2); $data .= "}, RokPadAcePath = '".$this->_acepath."';"; return $data; } }
cnpisit/myangkorpeopel
plugins/editors/rokpad/rokpad.php
PHP
gpl-2.0
50,100
<?php $cfg = require __DIR__ . '/../vendor/mediawiki/mediawiki-phan-config/src/config.php'; $cfg['directory_list'] = array_merge( $cfg['directory_list'], [ '../../extensions/MobileFrontend', '../../extensions/VisualEditor', '../../extensions/CentralAuth', '../../extensions/CirrusSearch', ] ); $cfg['exclude_analysis_directory_list'] = array_merge( $cfg['exclude_analysis_directory_list'], [ '../../extensions/MobileFrontend', '../../extensions/VisualEditor', '../../extensions/CentralAuth', '../../extensions/CirrusSearch', ] ); return $cfg;
wikimedia/mediawiki-extensions-GettingStarted
.phan/config.php
PHP
gpl-2.0
569
package app.astrosoft.ui.cal; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Observable; import java.util.Observer; import javax.swing.*; import javax.swing.event.AncestorEvent; import javax.swing.event.AncestorListener; import javax.swing.plaf.basic.BasicArrowButton; import app.astrosoft.ui.util.UIUtil; public class JCalendarCombo extends JPanel implements Observer { public static final int SUNDAY = 0; public static final int MONDAY = 1; private boolean condition; private JWindow window; private JCalendar calendar; private JTextField textField; private int startYear; private int endYear; public JCalendarCombo( ) { condition = false; startYear = 1801; endYear = 2099; calendar = new JCalendar( ); initializeJCalendarCombo( ); } public JCalendarCombo( int firstDay, boolean showCurrentDate ) { condition = false; startYear = 1801; endYear = 2099; calendar = new JCalendar( firstDay, showCurrentDate ); initializeJCalendarCombo( ); } public JCalendarCombo( int firstDay, boolean showCurrentDate, int startYear, int endYear ) { condition = false; this.startYear = startYear; this.endYear = endYear; calendar = new JCalendar( firstDay, showCurrentDate, startYear, endYear ); initializeJCalendarCombo( ); } private final void initializeJCalendarCombo( ) { textField = new JTextField( 10 ); textField.setEditable( false ); textField.setBackground( new Color( 255, 255, 255 ) ); javax.swing.JButton button = new BasicArrowButton( 5, new Color( 255, 255, 255 ), new Color( 0, 0, 0 ), new Color( 0, 0, 0 ), new Color( 0, 0, 0 ) ); setLayout( new BorderLayout( ) ); add( textField, "Center" ); add( button, "East" ); setSelectedDate( ); button.addActionListener( new ActionListener( ) { public void actionPerformed( ActionEvent e ) { if ( !condition ) { condition = true; window = new JWindow( ( Window ) textField.getTopLevelAncestor( ) ); window.getContentPane( ).setLayout( new BorderLayout( ) ); //window.getContentPane().setBackground(new Color(0,0,0)); calendar.initializeCalendar( ); window.getContentPane( ).add( calendar, "Center" ); window.pack( ); UIUtil.setWindowLocation(window, textField); // TODO: Remove later since this is replaced by UIUtil.setWindowLocation(); /*Point textFieldLocation = textField.getLocationOnScreen( ); Dimension size = textField.getSize( ); Dimension windowSize = window.getSize( ); Dimension screenSize = Toolkit.getDefaultToolkit( ).getScreenSize( ); if ( ( ( textFieldLocation.x - ( windowSize.width - size.width ) ) <= 0 ) && ( ( textFieldLocation.y + size.height + windowSize.height ) >= screenSize.height ) ) { window.setLocation( 0, textFieldLocation.y - windowSize.height ); } else if ( ( textFieldLocation.x - ( windowSize.width - size.width ) ) <= 0 ) { window.setLocation( 0, textFieldLocation.y + size.height ); } else if ( ( textFieldLocation.y + size.height + windowSize.height ) >= screenSize.height ) { window.setLocation( textFieldLocation.x - ( windowSize.width - size.width ), textFieldLocation.y - windowSize.height ); } else { window.setLocation( textFieldLocation.x - ( windowSize.width - size.width ), textFieldLocation.y + size.height ); }*/ window.setVisible( true ); } else { window.dispose( ); setSelectedDate( ); condition = false; } } } ); addAncestorListener( new AncestorListener( ) { public void ancestorAdded( AncestorEvent e ) { if ( condition ) { condition = false; setSelectedDate( ); window.dispose( ); } } public void ancestorMoved( AncestorEvent e ) { if ( condition ) { condition = false; setSelectedDate( ); window.dispose( ); } } public void ancestorRemoved( AncestorEvent e ) { if ( condition ) { condition = false; setSelectedDate( ); window.dispose( ); } } } ); calendar.buttonItemListener.addObserver( this ); } private final void setSelectedDate( ) { textField.setText( calendar.getDay( ) + "/" + calendar.getMonth( ) + "/" + calendar.getYear( ) ); condition = false; } public final void setSelectedDate( int year, int month, int day ) { calendar.setDay( ( new Integer( day ) ).toString( ) ); calendar.setMonth( ( new Integer( month ) ).toString( ) ); calendar.setYear( ( new Integer( year ) ).toString( ) ); calendar.showCalendarForDate( year, month ); textField.setText( calendar.getDay( ) + "/" + calendar.getMonth( ) + "/" + calendar.getYear( ) ); condition = false; } public final String getSelectedDate( ) { return textField.getText( ); } public final String getSelectedDay( ) { return calendar.getDay( ); } public final String getSelectedMonth( ) { return calendar.getMonth( ); } public final String getSelectedYear( ) { return calendar.getYear( ); } public void update( Observable observable, Object object ) { window.dispose( ); setSelectedDate( ); } }
erajasekar/Astrosoft
src/app/astrosoft/ui/cal/JCalendarCombo.java
Java
gpl-2.0
7,350
/* $Id: ldrkStuff.cpp $ */ /** @file * IPRT - Binary Image Loader, kLdr Interface. */ /* * Copyright (C) 2006-2007 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 * *******************************************************************************/ #define LOG_GROUP RTLOGGROUP_LDR #include <iprt/ldr.h> #include "internal/iprt.h" #include <iprt/file.h> #include <iprt/alloc.h> #include <iprt/alloca.h> #include <iprt/assert.h> #include <iprt/string.h> #include <iprt/path.h> #include <iprt/log.h> #include <iprt/param.h> #include <iprt/err.h> #include "internal/ldr.h" #define KLDR_ALREADY_INCLUDE_STD_TYPES #define KLDR_NO_KLDR_H_INCLUDES #include <k/kLdr.h> #include <k/kRdrAll.h> #include <k/kErr.h> #include <k/kErrors.h> #include <k/kMagics.h> /******************************************************************************* * Structures and Typedefs * *******************************************************************************/ /** * kLdr file provider. */ typedef struct RTKLDRRDR { /** The core. */ KRDR Core; /** The IPRT bit reader. */ PRTLDRREADER pReader; } RTKLDRRDR, *PRTKLDRRDR; /** * IPRT module. */ typedef struct RTLDRMODKLDR { /** The Core module structure. */ RTLDRMODINTERNAL Core; /** The kLdr module. */ PKLDRMOD pMod; } RTLDRMODKLDR, *PRTLDRMODKLDR; /** * Arguments for a RTLDRMODKLDR callback wrapper. */ typedef struct RTLDRMODKLDRARGS { union { PFNRT pfn; PFNRTLDRENUMDBG pfnEnumDbgInfo; PFNRTLDRENUMSYMS pfnEnumSyms; PFNRTLDRIMPORT pfnGetImport; } u; void *pvUser; const void *pvBits; PRTLDRMODKLDR pMod; int rc; } RTLDRMODKLDRARGS, *PRTLDRMODKLDRARGS; /** * Converts a kLdr error code to an IPRT one. */ static int rtkldrConvertError(int krc) { if (!krc) return VINF_SUCCESS; switch (krc) { case KERR_INVALID_PARAMETER: return VERR_INVALID_PARAMETER; case KERR_INVALID_HANDLE: return VERR_INVALID_HANDLE; case KERR_NO_MEMORY: return VERR_NO_MEMORY; case KLDR_ERR_UNKNOWN_FORMAT: case KLDR_ERR_MZ_NOT_SUPPORTED: return VERR_MZ_EXE_NOT_SUPPORTED; case KLDR_ERR_NE_NOT_SUPPORTED: return VERR_NE_EXE_NOT_SUPPORTED; case KLDR_ERR_LX_NOT_SUPPORTED: return VERR_LX_EXE_NOT_SUPPORTED; case KLDR_ERR_LE_NOT_SUPPORTED: return VERR_LE_EXE_NOT_SUPPORTED; case KLDR_ERR_PE_NOT_SUPPORTED: return VERR_PE_EXE_NOT_SUPPORTED; case KLDR_ERR_ELF_NOT_SUPPORTED: return VERR_ELF_EXE_NOT_SUPPORTED; case KLDR_ERR_MACHO_NOT_SUPPORTED: return VERR_INVALID_EXE_SIGNATURE; case KLDR_ERR_AOUT_NOT_SUPPORTED: return VERR_AOUT_EXE_NOT_SUPPORTED; case KLDR_ERR_MODULE_NOT_FOUND: return VERR_MODULE_NOT_FOUND; case KLDR_ERR_PREREQUISITE_MODULE_NOT_FOUND: return VERR_MODULE_NOT_FOUND; case KLDR_ERR_MAIN_STACK_ALLOC_FAILED: return VERR_NO_MEMORY; case KERR_BUFFER_OVERFLOW: return VERR_BUFFER_OVERFLOW; case KLDR_ERR_SYMBOL_NOT_FOUND: return VERR_SYMBOL_NOT_FOUND; case KLDR_ERR_FORWARDER_SYMBOL: return VERR_BAD_EXE_FORMAT; case KLDR_ERR_BAD_FIXUP: AssertMsgFailedReturn(("KLDR_ERR_BAD_FIXUP\n"), VERR_BAD_EXE_FORMAT); case KLDR_ERR_IMPORT_ORDINAL_OUT_OF_BOUNDS: return VERR_BAD_EXE_FORMAT; case KLDR_ERR_NO_DEBUG_INFO: return VERR_FILE_NOT_FOUND; case KLDR_ERR_ALREADY_MAPPED: return VERR_WRONG_ORDER; case KLDR_ERR_NOT_MAPPED: return VERR_WRONG_ORDER; case KLDR_ERR_ADDRESS_OVERFLOW: return VERR_NUMBER_TOO_BIG; case KLDR_ERR_TODO: return VERR_NOT_IMPLEMENTED; case KLDR_ERR_NOT_LOADED_DYNAMICALLY: case KCPU_ERR_ARCH_CPU_NOT_COMPATIBLE: case KLDR_ERR_TOO_LONG_FORWARDER_CHAIN: case KLDR_ERR_MODULE_TERMINATING: case KLDR_ERR_PREREQUISITE_MODULE_TERMINATING: case KLDR_ERR_MODULE_INIT_FAILED: case KLDR_ERR_PREREQUISITE_MODULE_INIT_FAILED: case KLDR_ERR_MODULE_INIT_FAILED_ALREADY: case KLDR_ERR_PREREQUISITE_MODULE_INIT_FAILED_ALREADY: case KLDR_ERR_PREREQUISITE_RECURSED_TOO_DEEPLY: case KLDR_ERR_THREAD_ATTACH_FAILED: case KRDR_ERR_TOO_MANY_MAPPINGS: case KLDR_ERR_NOT_DLL: case KLDR_ERR_NOT_EXE: AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_GENERAL_FAILURE); case KLDR_ERR_PE_UNSUPPORTED_MACHINE: case KLDR_ERR_PE_BAD_FILE_HEADER: case KLDR_ERR_PE_BAD_OPTIONAL_HEADER: case KLDR_ERR_PE_BAD_SECTION_HEADER: case KLDR_ERR_PE_BAD_FORWARDER: case KLDR_ERR_PE_FORWARDER_IMPORT_NOT_FOUND: case KLDR_ERR_PE_BAD_FIXUP: case KLDR_ERR_PE_BAD_IMPORT: AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_GENERAL_FAILURE); case KLDR_ERR_LX_BAD_HEADER: case KLDR_ERR_LX_BAD_LOADER_SECTION: case KLDR_ERR_LX_BAD_FIXUP_SECTION: case KLDR_ERR_LX_BAD_OBJECT_TABLE: case KLDR_ERR_LX_BAD_PAGE_MAP: case KLDR_ERR_LX_BAD_ITERDATA: case KLDR_ERR_LX_BAD_ITERDATA2: case KLDR_ERR_LX_BAD_BUNDLE: case KLDR_ERR_LX_NO_SONAME: case KLDR_ERR_LX_BAD_SONAME: case KLDR_ERR_LX_BAD_FORWARDER: case KLDR_ERR_LX_NRICHAIN_NOT_SUPPORTED: AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_GENERAL_FAILURE); case KLDR_ERR_MACHO_OTHER_ENDIAN_NOT_SUPPORTED: case KLDR_ERR_MACHO_BAD_HEADER: case KLDR_ERR_MACHO_UNSUPPORTED_FILE_TYPE: case KLDR_ERR_MACHO_UNSUPPORTED_MACHINE: case KLDR_ERR_MACHO_BAD_LOAD_COMMAND: case KLDR_ERR_MACHO_UNKNOWN_LOAD_COMMAND: case KLDR_ERR_MACHO_UNSUPPORTED_LOAD_COMMAND: case KLDR_ERR_MACHO_BAD_SECTION: case KLDR_ERR_MACHO_UNSUPPORTED_SECTION: #ifdef KLDR_ERR_MACHO_UNSUPPORTED_INIT_SECTION case KLDR_ERR_MACHO_UNSUPPORTED_INIT_SECTION: case KLDR_ERR_MACHO_UNSUPPORTED_TERM_SECTION: #endif case KLDR_ERR_MACHO_UNKNOWN_SECTION: case KLDR_ERR_MACHO_BAD_SECTION_ORDER: case KLDR_ERR_MACHO_BIT_MIX: case KLDR_ERR_MACHO_BAD_OBJECT_FILE: case KLDR_ERR_MACHO_BAD_SYMBOL: case KLDR_ERR_MACHO_UNSUPPORTED_FIXUP_TYPE: AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_GENERAL_FAILURE); default: if (RT_FAILURE(krc)) return krc; AssertMsgFailedReturn(("krc=%d (%#x): %s\n", krc, krc, kErrName(krc)), VERR_NO_TRANSLATION); } } /** * Converts a IPRT error code to an kLdr one. */ static int rtkldrConvertErrorFromIPRT(int rc) { if (RT_SUCCESS(rc)) return 0; switch (rc) { case VERR_NO_MEMORY: return KERR_NO_MEMORY; case VERR_INVALID_PARAMETER: return KERR_INVALID_PARAMETER; case VERR_INVALID_HANDLE: return KERR_INVALID_HANDLE; case VERR_BUFFER_OVERFLOW: return KERR_BUFFER_OVERFLOW; default: return rc; } } /** @copydoc KLDRRDROPS::pfnCreate * @remark This is a dummy which isn't used. */ static int rtkldrRdr_Create( PPKRDR ppRdr, const char *pszFilename) { NOREF(ppRdr); NOREF(pszFilename); AssertReleaseFailed(); return -1; } /** @copydoc KLDRRDROPS::pfnDestroy */ static int rtkldrRdr_Destroy( PKRDR pRdr) { PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader; int rc = pReader->pfnDestroy(pReader); return rtkldrConvertErrorFromIPRT(rc); } /** @copydoc KLDRRDROPS::pfnRead */ static int rtkldrRdr_Read( PKRDR pRdr, void *pvBuf, KSIZE cb, KFOFF off) { PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader; int rc = pReader->pfnRead(pReader, pvBuf, cb, off); return rtkldrConvertErrorFromIPRT(rc); } /** @copydoc KLDRRDROPS::pfnAllMap */ static int rtkldrRdr_AllMap( PKRDR pRdr, const void **ppvBits) { PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader; int rc = pReader->pfnMap(pReader, ppvBits); return rtkldrConvertErrorFromIPRT(rc); } /** @copydoc KLDRRDROPS::pfnAllUnmap */ static int rtkldrRdr_AllUnmap(PKRDR pRdr, const void *pvBits) { PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader; int rc = pReader->pfnUnmap(pReader, pvBits); return rtkldrConvertErrorFromIPRT(rc); } /** @copydoc KLDRRDROPS::pfnSize */ static KFOFF rtkldrRdr_Size( PKRDR pRdr) { PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader; return (KFOFF)pReader->pfnSize(pReader); } /** @copydoc KLDRRDROPS::pfnTell */ static KFOFF rtkldrRdr_Tell( PKRDR pRdr) { PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader; return (KFOFF)pReader->pfnTell(pReader); } /** @copydoc KLDRRDROPS::pfnName */ static const char * rtkldrRdr_Name(PKRDR pRdr) { PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader; return pReader->pfnLogName(pReader); } /** @copydoc KLDRRDROPS::pfnNativeFH */ static KIPTR rtkldrRdr_NativeFH(PKRDR pRdr) { NOREF(pRdr); AssertFailed(); return -1; } /** @copydoc KLDRRDROPS::pfnPageSize */ static KSIZE rtkldrRdr_PageSize(PKRDR pRdr) { NOREF(pRdr); return PAGE_SIZE; } /** @copydoc KLDRRDROPS::pfnMap */ static int rtkldrRdr_Map( PKRDR pRdr, void **ppvBase, KU32 cSegments, PCKLDRSEG paSegments, KBOOL fFixed) { //PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader; NOREF(pRdr); NOREF(ppvBase); NOREF(cSegments); NOREF(paSegments); NOREF(fFixed); AssertFailed(); return -1; } /** @copydoc KLDRRDROPS::pfnRefresh */ static int rtkldrRdr_Refresh( PKRDR pRdr, void *pvBase, KU32 cSegments, PCKLDRSEG paSegments) { //PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader; NOREF(pRdr); NOREF(pvBase); NOREF(cSegments); NOREF(paSegments); AssertFailed(); return -1; } /** @copydoc KLDRRDROPS::pfnProtect */ static int rtkldrRdr_Protect( PKRDR pRdr, void *pvBase, KU32 cSegments, PCKLDRSEG paSegments, KBOOL fUnprotectOrProtect) { //PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader; NOREF(pRdr); NOREF(pvBase); NOREF(cSegments); NOREF(paSegments); NOREF(fUnprotectOrProtect); AssertFailed(); return -1; } /** @copydoc KLDRRDROPS::pfnUnmap */ static int rtkldrRdr_Unmap( PKRDR pRdr, void *pvBase, KU32 cSegments, PCKLDRSEG paSegments) { //PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader; NOREF(pRdr); NOREF(pvBase); NOREF(cSegments); NOREF(paSegments); AssertFailed(); return -1; } /** @copydoc KLDRRDROPS::pfnDone */ static void rtkldrRdr_Done( PKRDR pRdr) { NOREF(pRdr); //PRTLDRREADER pReader = ((PRTKLDRRDR)pRdr)->pReader; } /** * The file reader operations. * We provide our own based on IPRT instead of using the kLdr ones. */ extern "C" const KRDROPS g_kLdrRdrFileOps; extern "C" const KRDROPS g_kLdrRdrFileOps = { /* .pszName = */ "IPRT", /* .pNext = */ NULL, /* .pfnCreate = */ rtkldrRdr_Create, /* .pfnDestroy = */ rtkldrRdr_Destroy, /* .pfnRead = */ rtkldrRdr_Read, /* .pfnAllMap = */ rtkldrRdr_AllMap, /* .pfnAllUnmap = */ rtkldrRdr_AllUnmap, /* .pfnSize = */ rtkldrRdr_Size, /* .pfnTell = */ rtkldrRdr_Tell, /* .pfnName = */ rtkldrRdr_Name, /* .pfnNativeFH = */ rtkldrRdr_NativeFH, /* .pfnPageSize = */ rtkldrRdr_PageSize, /* .pfnMap = */ rtkldrRdr_Map, /* .pfnRefresh = */ rtkldrRdr_Refresh, /* .pfnProtect = */ rtkldrRdr_Protect, /* .pfnUnmap = */ rtkldrRdr_Unmap, /* .pfnDone = */ rtkldrRdr_Done, /* .u32Dummy = */ 42 }; /** @copydoc RTLDROPS::pfnClose */ static DECLCALLBACK(int) rtkldr_Close(PRTLDRMODINTERNAL pMod) { PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod; int rc = kLdrModClose(pModkLdr); return rtkldrConvertError(rc); } /** @copydoc RTLDROPS::pfnDone */ static DECLCALLBACK(int) rtkldr_Done(PRTLDRMODINTERNAL pMod) { PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod; int rc = kLdrModMostlyDone(pModkLdr); return rtkldrConvertError(rc); } /** @copydoc FNKLDRMODENUMSYMS */ static int rtkldrEnumSymbolsWrapper(PKLDRMOD pMod, uint32_t iSymbol, const char *pchSymbol, KSIZE cchSymbol, const char *pszVersion, KLDRADDR uValue, uint32_t fKind, void *pvUser) { PRTLDRMODKLDRARGS pArgs = (PRTLDRMODKLDRARGS)pvUser; NOREF(pMod); NOREF(pszVersion); NOREF(fKind); /* If not zero terminated we'll have to use a temporary buffer. */ const char *pszSymbol = pchSymbol; if (pchSymbol && pchSymbol[cchSymbol]) { char *psz = (char *)alloca(cchSymbol + 1); memcpy(psz, pchSymbol, cchSymbol); psz[cchSymbol] = '\0'; pszSymbol = psz; } #if defined(RT_OS_OS2) || defined(RT_OS_DARWIN) /* skip the underscore prefix. */ if (*pszSymbol == '_') pszSymbol++; #endif int rc = pArgs->u.pfnEnumSyms(&pArgs->pMod->Core, pszSymbol, iSymbol, uValue, pArgs->pvUser); if (RT_FAILURE(rc)) return rc; /* don't bother converting. */ return 0; } /** @copydoc RTLDROPS::pfnEnumSymbols */ static DECLCALLBACK(int) rtkldr_EnumSymbols(PRTLDRMODINTERNAL pMod, unsigned fFlags, const void *pvBits, RTUINTPTR BaseAddress, PFNRTLDRENUMSYMS pfnCallback, void *pvUser) { PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod; RTLDRMODKLDRARGS Args; Args.pvUser = pvUser; Args.u.pfnEnumSyms = pfnCallback; Args.pMod = (PRTLDRMODKLDR)pMod; Args.pvBits = pvBits; Args.rc = VINF_SUCCESS; int rc = kLdrModEnumSymbols(pModkLdr, pvBits, BaseAddress, fFlags & RTLDR_ENUM_SYMBOL_FLAGS_ALL ? KLDRMOD_ENUM_SYMS_FLAGS_ALL : 0, rtkldrEnumSymbolsWrapper, &Args); if (Args.rc != VINF_SUCCESS) rc = Args.rc; else rc = rtkldrConvertError(rc); return rc; } /** @copydoc RTLDROPS::pfnGetImageSize */ static DECLCALLBACK(size_t) rtkldr_GetImageSize(PRTLDRMODINTERNAL pMod) { PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod; return kLdrModSize(pModkLdr); } /** @copydoc FNKLDRMODGETIMPORT */ static int rtkldrGetImportWrapper(PKLDRMOD pMod, uint32_t iImport, uint32_t iSymbol, const char *pchSymbol, KSIZE cchSymbol, const char *pszVersion, PKLDRADDR puValue, uint32_t *pfKind, void *pvUser) { PRTLDRMODKLDRARGS pArgs = (PRTLDRMODKLDRARGS)pvUser; NOREF(pMod); NOREF(pszVersion); NOREF(pfKind); /* If not zero terminated we'll have to use a temporary buffer. */ const char *pszSymbol = pchSymbol; if (pchSymbol && pchSymbol[cchSymbol]) { char *psz = (char *)alloca(cchSymbol + 1); memcpy(psz, pchSymbol, cchSymbol); psz[cchSymbol] = '\0'; pszSymbol = psz; } #if defined(RT_OS_OS2) || defined(RT_OS_DARWIN) /* skip the underscore prefix. */ if (*pszSymbol == '_') pszSymbol++; #endif /* get the import module name - TODO: cache this */ const char *pszModule = NULL; if (iImport != NIL_KLDRMOD_IMPORT) { char *pszBuf = (char *)alloca(64); int rc = kLdrModGetImport(pMod, pArgs->pvBits, iImport, pszBuf, 64); if (rc) return rc; pszModule = pszBuf; } /* do the query */ RTUINTPTR Value; int rc = pArgs->u.pfnGetImport(&pArgs->pMod->Core, pszModule, pszSymbol, pszSymbol ? ~0 : iSymbol, &Value, pArgs->pvUser); if (RT_SUCCESS(rc)) { *puValue = Value; return 0; } return rtkldrConvertErrorFromIPRT(rc); } /** @copydoc RTLDROPS::pfnGetBits */ static DECLCALLBACK(int) rtkldr_GetBits(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR BaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser) { PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod; RTLDRMODKLDRARGS Args; Args.pvUser = pvUser; Args.u.pfnGetImport = pfnGetImport; Args.pMod = (PRTLDRMODKLDR)pMod; Args.pvBits = pvBits; Args.rc = VINF_SUCCESS; int rc = kLdrModGetBits(pModkLdr, pvBits, BaseAddress, rtkldrGetImportWrapper, &Args); if (Args.rc != VINF_SUCCESS) rc = Args.rc; else rc = rtkldrConvertError(rc); return rc; } /** @copydoc RTLDROPS::pfnRelocate */ static DECLCALLBACK(int) rtkldr_Relocate(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR NewBaseAddress, RTUINTPTR OldBaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser) { PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod; RTLDRMODKLDRARGS Args; Args.pvUser = pvUser; Args.u.pfnGetImport = pfnGetImport; Args.pMod = (PRTLDRMODKLDR)pMod; Args.pvBits = pvBits; Args.rc = VINF_SUCCESS; int rc = kLdrModRelocateBits(pModkLdr, pvBits, NewBaseAddress, OldBaseAddress, rtkldrGetImportWrapper, &Args); if (Args.rc != VINF_SUCCESS) rc = Args.rc; else rc = rtkldrConvertError(rc); return rc; } /** @copydoc RTLDROPS::pfnGetSymbolEx */ static DECLCALLBACK(int) rtkldr_GetSymbolEx(PRTLDRMODINTERNAL pMod, const void *pvBits, RTUINTPTR BaseAddress, const char *pszSymbol, RTUINTPTR *pValue) { PKLDRMOD pModkLdr = ((PRTLDRMODKLDR)pMod)->pMod; KLDRADDR uValue; #if defined(RT_OS_OS2) || defined(RT_OS_DARWIN) /* * Add underscore prefix. */ if (pszSymbol) { size_t cch = strlen(pszSymbol); char *psz = (char *)alloca(cch + 2); memcpy(psz + 1, pszSymbol, cch + 1); *psz = '_'; pszSymbol = psz; } #endif int rc = kLdrModQuerySymbol(pModkLdr, pvBits, BaseAddress, NIL_KLDRMOD_SYM_ORDINAL, pszSymbol, strlen(pszSymbol), NULL, NULL, NULL, &uValue, NULL); if (!rc) { *pValue = uValue; return VINF_SUCCESS; } return rtkldrConvertError(rc); } /** @copydoc FNKLDRENUMDBG */ static int rtkldrEnumDbgInfoWrapper(PKLDRMOD pMod, KU32 iDbgInfo, KLDRDBGINFOTYPE enmType, KI16 iMajorVer, KI16 iMinorVer, const char *pszPartNm, KLDRFOFF offFile, KLDRADDR LinkAddress, KLDRSIZE cb, const char *pszExtFile, void *pvUser) { PRTLDRMODKLDRARGS pArgs = (PRTLDRMODKLDRARGS)pvUser; NOREF(pMod); RTLDRDBGINFOTYPE enmMyType; switch (enmType) { case KLDRDBGINFOTYPE_UNKNOWN: enmMyType = RTLDRDBGINFOTYPE_UNKNOWN; break; case KLDRDBGINFOTYPE_STABS: enmMyType = RTLDRDBGINFOTYPE_STABS; break; case KLDRDBGINFOTYPE_DWARF: enmMyType = RTLDRDBGINFOTYPE_DWARF; break; case KLDRDBGINFOTYPE_CODEVIEW: enmMyType = RTLDRDBGINFOTYPE_CODEVIEW; break; case KLDRDBGINFOTYPE_WATCOM: enmMyType = RTLDRDBGINFOTYPE_WATCOM; break; case KLDRDBGINFOTYPE_HLL: enmMyType = RTLDRDBGINFOTYPE_HLL; break; default: AssertFailed(); enmMyType = RTLDRDBGINFOTYPE_UNKNOWN; break; } int rc = pArgs->u.pfnEnumDbgInfo(&pArgs->pMod->Core, iDbgInfo, enmMyType, iMajorVer, iMinorVer, pszPartNm, offFile, LinkAddress, cb, pszExtFile, pArgs->pvUser); if (RT_FAILURE(rc)) return rc; /* don't bother converting. */ return 0; } /** @copydoc RTLDROPS::pfnEnumDbgInfo */ static DECLCALLBACK(int) rtkldr_EnumDbgInfo(PRTLDRMODINTERNAL pMod, const void *pvBits, PFNRTLDRENUMDBG pfnCallback, void *pvUser) { PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod; RTLDRMODKLDRARGS Args; Args.pvUser = pvUser; Args.u.pfnEnumDbgInfo = pfnCallback; Args.pvBits = pvBits; Args.pMod = pThis; Args.rc = VINF_SUCCESS; int rc = kLdrModEnumDbgInfo(pThis->pMod, pvBits, rtkldrEnumDbgInfoWrapper, &Args); if (Args.rc != VINF_SUCCESS) rc = Args.rc; return rc; } /** @copydoc RTLDROPS::pfnEnumSegments. */ static DECLCALLBACK(int) rtkldr_EnumSegments(PRTLDRMODINTERNAL pMod, PFNRTLDRENUMSEGS pfnCallback, void *pvUser) { PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod; uint32_t const cSegments = pThis->pMod->cSegments; PCKLDRSEG paSegments = &pThis->pMod->aSegments[0]; for (uint32_t iSeg = 0; iSeg < cSegments; iSeg++) { RTLDRSEG Seg; Seg.pchName = paSegments[iSeg].pchName; Seg.cchName = paSegments[iSeg].cchName; Seg.SelFlat = paSegments[iSeg].SelFlat; Seg.Sel16bit = paSegments[iSeg].Sel16bit; Seg.fFlags = paSegments[iSeg].fFlags; AssertCompile(KLDRSEG_FLAG_16BIT == RTLDRSEG_FLAG_16BIT ); AssertCompile(KLDRSEG_FLAG_OS2_ALIAS16 == RTLDRSEG_FLAG_OS2_ALIAS16); AssertCompile(KLDRSEG_FLAG_OS2_CONFORM == RTLDRSEG_FLAG_OS2_CONFORM); AssertCompile(KLDRSEG_FLAG_OS2_IOPL == RTLDRSEG_FLAG_OS2_IOPL ); switch (paSegments[iSeg].enmProt) { default: AssertMsgFailed(("%d\n", paSegments[iSeg].enmProt)); case KPROT_NOACCESS: Seg.fProt = 0; break; case KPROT_READONLY: Seg.fProt = RTMEM_PROT_READ; break; case KPROT_READWRITE: Seg.fProt = RTMEM_PROT_READ | RTMEM_PROT_WRITE; break; case KPROT_WRITECOPY: Seg.fProt = RTMEM_PROT_WRITE; break; case KPROT_EXECUTE: Seg.fProt = RTMEM_PROT_EXEC; break; case KPROT_EXECUTE_READ: Seg.fProt = RTMEM_PROT_EXEC | RTMEM_PROT_READ; break; case KPROT_EXECUTE_READWRITE: Seg.fProt = RTMEM_PROT_EXEC | RTMEM_PROT_READ | RTMEM_PROT_WRITE; break; case KPROT_EXECUTE_WRITECOPY: Seg.fProt = RTMEM_PROT_EXEC | RTMEM_PROT_WRITE; break; } Seg.cb = paSegments[iSeg].cb; Seg.Alignment = paSegments[iSeg].Alignment; Seg.LinkAddress = paSegments[iSeg].LinkAddress; Seg.offFile = paSegments[iSeg].offFile; Seg.cbFile = paSegments[iSeg].cbFile; Seg.RVA = paSegments[iSeg].RVA; Seg.cbMapped = paSegments[iSeg].cbMapped; int rc = pfnCallback(pMod, &Seg, pvUser); if (rc != VINF_SUCCESS) return rc; } return VINF_SUCCESS; } /** @copydoc RTLDROPS::pfnLinkAddressToSegOffset. */ static DECLCALLBACK(int) rtkldr_LinkAddressToSegOffset(PRTLDRMODINTERNAL pMod, RTLDRADDR LinkAddress, uint32_t *piSeg, PRTLDRADDR poffSeg) { PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod; uint32_t const cSegments = pThis->pMod->cSegments; PCKLDRSEG paSegments = &pThis->pMod->aSegments[0]; for (uint32_t iSeg = 0; iSeg < cSegments; iSeg++) { KLDRADDR offSeg = LinkAddress - paSegments[iSeg].LinkAddress; if ( offSeg < paSegments[iSeg].cbMapped || offSeg < paSegments[iSeg].cb) { *piSeg = iSeg; *poffSeg = offSeg; return VINF_SUCCESS; } } return VERR_LDR_INVALID_LINK_ADDRESS; } /** @copydoc RTLDROPS::pfnLinkAddressToRva. */ static DECLCALLBACK(int) rtkldr_LinkAddressToRva(PRTLDRMODINTERNAL pMod, RTLDRADDR LinkAddress, PRTLDRADDR pRva) { PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod; uint32_t const cSegments = pThis->pMod->cSegments; PCKLDRSEG paSegments = &pThis->pMod->aSegments[0]; for (uint32_t iSeg = 0; iSeg < cSegments; iSeg++) { KLDRADDR offSeg = LinkAddress - paSegments[iSeg].LinkAddress; if ( offSeg < paSegments[iSeg].cbMapped || offSeg < paSegments[iSeg].cb) { *pRva = paSegments[iSeg].RVA + offSeg; return VINF_SUCCESS; } } return VERR_LDR_INVALID_RVA; } /** @copydoc RTLDROPS::pfnSegOffsetToRva. */ static DECLCALLBACK(int) rtkldr_SegOffsetToRva(PRTLDRMODINTERNAL pMod, uint32_t iSeg, RTLDRADDR offSeg, PRTLDRADDR pRva) { PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod; if (iSeg >= pThis->pMod->cSegments) return VERR_LDR_INVALID_SEG_OFFSET; PCKLDRSEG const pSegment = &pThis->pMod->aSegments[iSeg]; if ( offSeg > pSegment->cbMapped && offSeg > pSegment->cb && ( pSegment->cbFile < 0 || offSeg > (uint64_t)pSegment->cbFile)) return VERR_LDR_INVALID_SEG_OFFSET; *pRva = pSegment->RVA + offSeg; return VINF_SUCCESS; } /** @copydoc RTLDROPS::pfnRvaToSegOffset. */ static DECLCALLBACK(int) rtkldr_RvaToSegOffset(PRTLDRMODINTERNAL pMod, RTLDRADDR Rva, uint32_t *piSeg, PRTLDRADDR poffSeg) { PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod; uint32_t const cSegments = pThis->pMod->cSegments; PCKLDRSEG paSegments = &pThis->pMod->aSegments[0]; for (uint32_t iSeg = 0; iSeg < cSegments; iSeg++) { KLDRADDR offSeg = Rva - paSegments[iSeg].RVA; if ( offSeg < paSegments[iSeg].cbMapped || offSeg < paSegments[iSeg].cb) { *piSeg = iSeg; *poffSeg = offSeg; return VINF_SUCCESS; } } return VERR_LDR_INVALID_RVA; } /** * Operations for a kLdr module. */ static const RTLDROPS g_rtkldrOps = { "kLdr", rtkldr_Close, NULL, rtkldr_Done, rtkldr_EnumSymbols, /* ext */ rtkldr_GetImageSize, rtkldr_GetBits, rtkldr_Relocate, rtkldr_GetSymbolEx, rtkldr_EnumDbgInfo, rtkldr_EnumSegments, rtkldr_LinkAddressToSegOffset, rtkldr_LinkAddressToRva, rtkldr_SegOffsetToRva, rtkldr_RvaToSegOffset, 42 }; /** * Open a image using kLdr. * * @returns iprt status code. * @param pReader The loader reader instance which will provide the raw image bits. * @param fFlags Reserved, MBZ. * @param enmArch CPU architecture specifier for the image to be loaded. * @param phLdrMod Where to store the handle. */ int rtldrkLdrOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod) { /* Convert enmArch to k-speak. */ KCPUARCH enmCpuArch; switch (enmArch) { case RTLDRARCH_WHATEVER: enmCpuArch = KCPUARCH_UNKNOWN; break; case RTLDRARCH_X86_32: enmCpuArch = KCPUARCH_X86_32; break; case RTLDRARCH_AMD64: enmCpuArch = KCPUARCH_AMD64; break; default: return VERR_INVALID_PARAMETER; } /* Create a rtkldrRdr_ instance. */ PRTKLDRRDR pRdr = (PRTKLDRRDR)RTMemAllocZ(sizeof(*pRdr)); if (!pRdr) return VERR_NO_MEMORY; pRdr->Core.u32Magic = KRDR_MAGIC; pRdr->Core.pOps = &g_kLdrRdrFileOps; pRdr->pReader = pReader; /* Try open it. */ PKLDRMOD pMod; int krc = kLdrModOpenFromRdr(&pRdr->Core, fFlags, enmCpuArch, &pMod); if (!krc) { /* Create a module wrapper for it. */ PRTLDRMODKLDR pNewMod = (PRTLDRMODKLDR)RTMemAllocZ(sizeof(*pNewMod)); if (pNewMod) { pNewMod->Core.u32Magic = RTLDRMOD_MAGIC; pNewMod->Core.eState = LDR_STATE_OPENED; pNewMod->Core.pOps = &g_rtkldrOps; pNewMod->pMod = pMod; *phLdrMod = &pNewMod->Core; #ifdef LOG_ENABLED Log(("rtldrkLdrOpen: '%s' (%s) %u segments\n", pMod->pszName, pMod->pszFilename, pMod->cSegments)); for (unsigned iSeg = 0; iSeg < pMod->cSegments; iSeg++) { Log(("Segment #%-2u: RVA=%08llx cb=%08llx '%.*s'\n", iSeg, pMod->aSegments[iSeg].RVA, pMod->aSegments[iSeg].cb, pMod->aSegments[iSeg].cchName, pMod->aSegments[iSeg].pchName)); } #endif return VINF_SUCCESS; } kLdrModClose(pMod); krc = KERR_NO_MEMORY; } return rtkldrConvertError(krc); }
VirtualMonitor/VirtualMonitor
src/VBox/Runtime/common/ldr/ldrkStuff.cpp
C++
gpl-2.0
30,065
<?php /* Twando.com Free PHP Twitter Application http://www.twando.com/ */ if (!$content_id) { exit; } global $q1a, $pass_msg; ?> <h2>Tweet Settings for <?=htmlentities($q1a['screen_name'])?></h2> <?php if ($q1a['id'] == "") { echo mainFuncs::push_response(7); } else { //List all options here ?> <div class="tab_row"> <div class="tab_main" id="tab1"> <a href="javascript:ajax_tweet_settings_tab('tab1');">Post Quick Tweet</a> </div><div class="tab_main" id="tab2"> <a href="javascript:ajax_tweet_settings_tab('tab2');">Scheduled Tweets</a> </div><div class="tab_main" id="tab3"> <a href="javascript:ajax_tweet_settings_tab('tab3');">Schedule a Tweet</a> </div><div class="tab_main" id="tab3"> <a href="javascript:ajax_tweet_settings_tab('tab5');">Schedule a Tweet With Image</a> </div><div class="tab_main" id="tab4"> <a href="javascript:ajax_tweet_settings_tab('tab4');">Bulk CSV Tweet Upload</a> </div> </div> <br style="clear: both;" /> <div id="update_div"> &nbsp; </div> <form> <input type="hidden" name="twitter_id" id="twitter_id" value="<?=$q1a['id']?>" /> <input type="hidden" name="page_id" id="page_id" value="1" /> <input type="hidden" name="pass_msg" id="pass_msg" value="<?=$pass_msg?>" /> </form> <form method="post" action="" name="deltweet" id="deltweet"> <input type="hidden" name="a" id="a" value="deletetweet" /> <input type="hidden" name="deltweet_id" id="deltweet_id" value="" /> </form> <form method="post" action="" name="edittweet" id="edittweet"> <input type="hidden" name="a" id="a" value="edittweet" /> <input type="hidden" name="edittweet_id" id="edittweet_id" value="" /> <input type="hidden" name="everyday" id="everyday" value="" /> </form> <?php //End of valid id } ?> <br style="clear: both;" /> <a href="<?=BASE_LINK_URL?>">Return to main admin screen</a>
txt3rob/twando
inc/content/english/tweet_settings.php
PHP
gpl-2.0
1,874
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * Contains the DB_common base class * * PHP versions 4 and 5 * * LICENSE: This source file is subject to version 3.0 of the PHP license * that is available through the world-wide-web at the following URI: * http://www.php.net/license/3_0.txt. If you did not receive a copy of * the PHP License and are unable to obtain it through the web, please * send a note to license@php.net so we can mail you a copy immediately. * * @category Database * @package DB * @author Stig Bakken <ssb@php.net> * @author Tomas V.V. Cox <cox@idecnet.com> * @author Daniel Convissor <danielc@php.net> * @copyright 1997-2005 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id$ * @link http://pear.php.net/package/DB */ /** * Obtain the PEAR class so it can be extended from */ require_once dirname(__FILE__).'/../PEAR.php'; /** * DB_common is the base class from which each database driver class extends * * All common methods are declared here. If a given DBMS driver contains * a particular method, that method will overload the one here. * * @category Database * @package DB * @author Stig Bakken <ssb@php.net> * @author Tomas V.V. Cox <cox@idecnet.com> * @author Daniel Convissor <danielc@php.net> * @copyright 1997-2005 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: @package_version@ * @link http://pear.php.net/package/DB */ class DB_common extends PEAR { // {{{ properties /** * The current default fetch mode * @var integer */ var $fetchmode = DB_FETCHMODE_ORDERED; /** * The name of the class into which results should be fetched when * DB_FETCHMODE_OBJECT is in effect * * @var string */ var $fetchmode_object_class = 'stdClass'; /** * Was a connection present when the object was serialized()? * @var bool * @see DB_common::__sleep(), DB_common::__wake() */ var $was_connected = null; /** * The most recently executed query * @var string */ var $last_query = ''; /** * Run-time configuration options * * The 'optimize' option has been deprecated. Use the 'portability' * option instead. * * @var array * @see DB_common::setOption() */ var $options = array( 'result_buffering' => 500, 'persistent' => false, 'ssl' => false, 'debug' => 0, 'seqname_format' => '%s_seq', 'autofree' => false, 'portability' => DB_PORTABILITY_NONE, 'optimize' => 'performance', // Deprecated. Use 'portability'. ); /** * The parameters from the most recently executed query * @var array * @since Property available since Release 1.7.0 */ var $last_parameters = array(); /** * The elements from each prepared statement * @var array */ var $prepare_tokens = array(); /** * The data types of the various elements in each prepared statement * @var array */ var $prepare_types = array(); /** * The prepared queries * @var array */ var $prepared_queries = array(); // }}} // {{{ DB_common /** * This constructor calls <kbd>$this->PEAR('DB_Error')</kbd> * * @return void */ function DB_common() { $this->PEAR('DB_Error'); } // }}} // {{{ __sleep() /** * Automatically indicates which properties should be saved * when PHP's serialize() function is called * * @return array the array of properties names that should be saved */ function __sleep() { if ($this->connection) { // Don't disconnect(), people use serialize() for many reasons $this->was_connected = true; } else { $this->was_connected = false; } if (isset($this->autocommit)) { return array('autocommit', 'dbsyntax', 'dsn', 'features', 'fetchmode', 'fetchmode_object_class', 'options', 'was_connected', ); } else { return array('dbsyntax', 'dsn', 'features', 'fetchmode', 'fetchmode_object_class', 'options', 'was_connected', ); } } // }}} // {{{ __wakeup() /** * Automatically reconnects to the database when PHP's unserialize() * function is called * * The reconnection attempt is only performed if the object was connected * at the time PHP's serialize() function was run. * * @return void */ function __wakeup() { if ($this->was_connected) { $this->connect($this->dsn, $this->options); } } // }}} // {{{ __toString() /** * Automatic string conversion for PHP 5 * * @return string a string describing the current PEAR DB object * * @since Method available since Release 1.7.0 */ function __toString() { $info = strtolower(get_class($this)); $info .= ': (phptype=' . $this->phptype . ', dbsyntax=' . $this->dbsyntax . ')'; if ($this->connection) { $info .= ' [connected]'; } return $info; } // }}} // {{{ toString() /** * DEPRECATED: String conversion method * * @return string a string describing the current PEAR DB object * * @deprecated Method deprecated in Release 1.7.0 */ function toString() { return $this->__toString(); } // }}} // {{{ quoteString() /** * DEPRECATED: Quotes a string so it can be safely used within string * delimiters in a query * * @param string $string the string to be quoted * * @return string the quoted string * * @see DB_common::quoteSmart(), DB_common::escapeSimple() * @deprecated Method deprecated some time before Release 1.2 */ function quoteString($string) { $string = $this->quote($string); if ($string{0} == "'") { return substr($string, 1, -1); } return $string; } // }}} // {{{ quote() /** * DEPRECATED: Quotes a string so it can be safely used in a query * * @param string $string the string to quote * * @return string the quoted string or the string <samp>NULL</samp> * if the value submitted is <kbd>null</kbd>. * * @see DB_common::quoteSmart(), DB_common::escapeSimple() * @deprecated Deprecated in release 1.6.0 */ function quote($string = null) { return ($string === null) ? 'NULL' : "'" . str_replace("'", "''", $string) . "'"; } // }}} // {{{ quoteIdentifier() /** * Quotes a string so it can be safely used as a table or column name * * Delimiting style depends on which database driver is being used. * * NOTE: just because you CAN use delimited identifiers doesn't mean * you SHOULD use them. In general, they end up causing way more * problems than they solve. * * Portability is broken by using the following characters inside * delimited identifiers: * + backtick (<kbd>`</kbd>) -- due to MySQL * + double quote (<kbd>"</kbd>) -- due to Oracle * + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access * * Delimited identifiers are known to generally work correctly under * the following drivers: * + mssql * + mysql * + mysqli * + oci8 * + odbc(access) * + odbc(db2) * + pgsql * + sqlite * + sybase (must execute <kbd>set quoted_identifier on</kbd> sometime * prior to use) * * InterBase doesn't seem to be able to use delimited identifiers * via PHP 4. They work fine under PHP 5. * * @param string $str the identifier name to be quoted * * @return string the quoted identifier * * @since Method available since Release 1.6.0 */ function quoteIdentifier($str) { return '"' . str_replace('"', '""', $str) . '"'; } // }}} // {{{ quoteSmart() /** * Formats input so it can be safely used in a query * * The output depends on the PHP data type of input and the database * type being used. * * @param mixed $in the data to be formatted * * @return mixed the formatted data. The format depends on the input's * PHP type: * <ul> * <li> * <kbd>input</kbd> -> <samp>returns</samp> * </li> * <li> * <kbd>null</kbd> -> the string <samp>NULL</samp> * </li> * <li> * <kbd>integer</kbd> or <kbd>double</kbd> -> the unquoted number * </li> * <li> * <kbd>bool</kbd> -> output depends on the driver in use * Most drivers return integers: <samp>1</samp> if * <kbd>true</kbd> or <samp>0</samp> if * <kbd>false</kbd>. * Some return strings: <samp>TRUE</samp> if * <kbd>true</kbd> or <samp>FALSE</samp> if * <kbd>false</kbd>. * Finally one returns strings: <samp>T</samp> if * <kbd>true</kbd> or <samp>F</samp> if * <kbd>false</kbd>. Here is a list of each DBMS, * the values returned and the suggested column type: * <ul> * <li> * <kbd>dbase</kbd> -> <samp>T/F</samp> * (<kbd>Logical</kbd>) * </li> * <li> * <kbd>fbase</kbd> -> <samp>TRUE/FALSE</samp> * (<kbd>BOOLEAN</kbd>) * </li> * <li> * <kbd>ibase</kbd> -> <samp>1/0</samp> * (<kbd>SMALLINT</kbd>) [1] * </li> * <li> * <kbd>ifx</kbd> -> <samp>1/0</samp> * (<kbd>SMALLINT</kbd>) [1] * </li> * <li> * <kbd>msql</kbd> -> <samp>1/0</samp> * (<kbd>INTEGER</kbd>) * </li> * <li> * <kbd>mssql</kbd> -> <samp>1/0</samp> * (<kbd>BIT</kbd>) * </li> * <li> * <kbd>mysql</kbd> -> <samp>1/0</samp> * (<kbd>TINYINT(1)</kbd>) * </li> * <li> * <kbd>mysqli</kbd> -> <samp>1/0</samp> * (<kbd>TINYINT(1)</kbd>) * </li> * <li> * <kbd>oci8</kbd> -> <samp>1/0</samp> * (<kbd>NUMBER(1)</kbd>) * </li> * <li> * <kbd>odbc</kbd> -> <samp>1/0</samp> * (<kbd>SMALLINT</kbd>) [1] * </li> * <li> * <kbd>pgsql</kbd> -> <samp>TRUE/FALSE</samp> * (<kbd>BOOLEAN</kbd>) * </li> * <li> * <kbd>sqlite</kbd> -> <samp>1/0</samp> * (<kbd>INTEGER</kbd>) * </li> * <li> * <kbd>sybase</kbd> -> <samp>1/0</samp> * (<kbd>TINYINT(1)</kbd>) * </li> * </ul> * [1] Accommodate the lowest common denominator because not all * versions of have <kbd>BOOLEAN</kbd>. * </li> * <li> * other (including strings and numeric strings) -> * the data with single quotes escaped by preceeding * single quotes, backslashes are escaped by preceeding * backslashes, then the whole string is encapsulated * between single quotes * </li> * </ul> * * @see DB_common::escapeSimple() * @since Method available since Release 1.6.0 */ function quoteSmart($in) { if (is_int($in) || is_double($in)) { return $in; } elseif (is_bool($in)) { return $in ? 1 : 0; } elseif (is_null($in)) { return 'NULL'; } else { return "'" . $this->escapeSimple($in) . "'"; } } // }}} // {{{ escapeSimple() /** * Escapes a string according to the current DBMS's standards * * In SQLite, this makes things safe for inserts/updates, but may * cause problems when performing text comparisons against columns * containing binary data. See the * {@link http://php.net/sqlite_escape_string PHP manual} for more info. * * @param string $str the string to be escaped * * @return string the escaped string * * @see DB_common::quoteSmart() * @since Method available since Release 1.6.0 */ function escapeSimple($str) { return str_replace("'", "''", $str); } // }}} // {{{ provides() /** * Tells whether the present driver supports a given feature * * @param string $feature the feature you're curious about * * @return bool whether this driver supports $feature */ function provides($feature) { return $this->features[$feature]; } // }}} // {{{ setFetchMode() /** * Sets the fetch mode that should be used by default for query results * * @param integer $fetchmode DB_FETCHMODE_ORDERED, DB_FETCHMODE_ASSOC * or DB_FETCHMODE_OBJECT * @param string $object_class the class name of the object to be returned * by the fetch methods when the * DB_FETCHMODE_OBJECT mode is selected. * If no class is specified by default a cast * to object from the assoc array row will be * done. There is also the posibility to use * and extend the 'DB_row' class. * * @see DB_FETCHMODE_ORDERED, DB_FETCHMODE_ASSOC, DB_FETCHMODE_OBJECT */ function setFetchMode($fetchmode, $object_class = 'stdClass') { switch ($fetchmode) { case DB_FETCHMODE_OBJECT: $this->fetchmode_object_class = $object_class; case DB_FETCHMODE_ORDERED: case DB_FETCHMODE_ASSOC: $this->fetchmode = $fetchmode; break; default: return $this->raiseError('invalid fetchmode mode'); } } // }}} // {{{ setOption() /** * Sets run-time configuration options for PEAR DB * * Options, their data types, default values and description: * <ul> * <li> * <var>autofree</var> <kbd>boolean</kbd> = <samp>false</samp> * <br />should results be freed automatically when there are no * more rows? * </li><li> * <var>result_buffering</var> <kbd>integer</kbd> = <samp>500</samp> * <br />how many rows of the result set should be buffered? * <br />In mysql: mysql_unbuffered_query() is used instead of * mysql_query() if this value is 0. (Release 1.7.0) * <br />In oci8: this value is passed to ocisetprefetch(). * (Release 1.7.0) * </li><li> * <var>debug</var> <kbd>integer</kbd> = <samp>0</samp> * <br />debug level * </li><li> * <var>persistent</var> <kbd>boolean</kbd> = <samp>false</samp> * <br />should the connection be persistent? * </li><li> * <var>portability</var> <kbd>integer</kbd> = <samp>DB_PORTABILITY_NONE</samp> * <br />portability mode constant (see below) * </li><li> * <var>seqname_format</var> <kbd>string</kbd> = <samp>%s_seq</samp> * <br />the sprintf() format string used on sequence names. This * format is applied to sequence names passed to * createSequence(), nextID() and dropSequence(). * </li><li> * <var>ssl</var> <kbd>boolean</kbd> = <samp>false</samp> * <br />use ssl to connect? * </li> * </ul> * * ----------------------------------------- * * PORTABILITY MODES * * These modes are bitwised, so they can be combined using <kbd>|</kbd> * and removed using <kbd>^</kbd>. See the examples section below on how * to do this. * * <samp>DB_PORTABILITY_NONE</samp> * turn off all portability features * * This mode gets automatically turned on if the deprecated * <var>optimize</var> option gets set to <samp>performance</samp>. * * * <samp>DB_PORTABILITY_LOWERCASE</samp> * convert names of tables and fields to lower case when using * <kbd>get*()</kbd>, <kbd>fetch*()</kbd> and <kbd>tableInfo()</kbd> * * This mode gets automatically turned on in the following databases * if the deprecated option <var>optimize</var> gets set to * <samp>portability</samp>: * + oci8 * * * <samp>DB_PORTABILITY_RTRIM</samp> * right trim the data output by <kbd>get*()</kbd> <kbd>fetch*()</kbd> * * * <samp>DB_PORTABILITY_DELETE_COUNT</samp> * force reporting the number of rows deleted * * Some DBMS's don't count the number of rows deleted when performing * simple <kbd>DELETE FROM tablename</kbd> queries. This portability * mode tricks such DBMS's into telling the count by adding * <samp>WHERE 1=1</samp> to the end of <kbd>DELETE</kbd> queries. * * This mode gets automatically turned on in the following databases * if the deprecated option <var>optimize</var> gets set to * <samp>portability</samp>: * + fbsql * + mysql * + mysqli * + sqlite * * * <samp>DB_PORTABILITY_NUMROWS</samp> * enable hack that makes <kbd>numRows()</kbd> work in Oracle * * This mode gets automatically turned on in the following databases * if the deprecated option <var>optimize</var> gets set to * <samp>portability</samp>: * + oci8 * * * <samp>DB_PORTABILITY_ERRORS</samp> * makes certain error messages in certain drivers compatible * with those from other DBMS's * * + mysql, mysqli: change unique/primary key constraints * DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT * * + odbc(access): MS's ODBC driver reports 'no such field' as code * 07001, which means 'too few parameters.' When this option is on * that code gets mapped to DB_ERROR_NOSUCHFIELD. * DB_ERROR_MISMATCH -> DB_ERROR_NOSUCHFIELD * * <samp>DB_PORTABILITY_NULL_TO_EMPTY</samp> * convert null values to empty strings in data output by get*() and * fetch*(). Needed because Oracle considers empty strings to be null, * while most other DBMS's know the difference between empty and null. * * * <samp>DB_PORTABILITY_ALL</samp> * turn on all portability features * * ----------------------------------------- * * Example 1. Simple setOption() example * <code> * $db->setOption('autofree', true); * </code> * * Example 2. Portability for lowercasing and trimming * <code> * $db->setOption('portability', * DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_RTRIM); * </code> * * Example 3. All portability options except trimming * <code> * $db->setOption('portability', * DB_PORTABILITY_ALL ^ DB_PORTABILITY_RTRIM); * </code> * * @param string $option option name * @param mixed $value value for the option * * @return int DB_OK on success. A DB_Error object on failure. * * @see DB_common::$options */ function setOption($option, $value) { if (isset($this->options[$option])) { $this->options[$option] = $value; /* * Backwards compatibility check for the deprecated 'optimize' * option. Done here in case settings change after connecting. */ if ($option == 'optimize') { if ($value == 'portability') { switch ($this->phptype) { case 'oci8': $this->options['portability'] = DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_NUMROWS; break; case 'fbsql': case 'mysql': case 'mysqli': case 'sqlite': $this->options['portability'] = DB_PORTABILITY_DELETE_COUNT; break; } } else { $this->options['portability'] = DB_PORTABILITY_NONE; } } return DB_OK; } return $this->raiseError("unknown option $option"); } // }}} // {{{ getOption() /** * Returns the value of an option * * @param string $option the option name you're curious about * * @return mixed the option's value */ function getOption($option) { if (isset($this->options[$option])) { return $this->options[$option]; } return $this->raiseError("unknown option $option"); } // }}} // {{{ prepare() /** * Prepares a query for multiple execution with execute() * * Creates a query that can be run multiple times. Each time it is run, * the placeholders, if any, will be replaced by the contents of * execute()'s $data argument. * * Three types of placeholders can be used: * + <kbd>?</kbd> scalar value (i.e. strings, integers). The system * will automatically quote and escape the data. * + <kbd>!</kbd> value is inserted 'as is' * + <kbd>&</kbd> requires a file name. The file's contents get * inserted into the query (i.e. saving binary * data in a db) * * Example 1. * <code> * $sth = $db->prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)'); * $data = array( * "John's text", * "'it''s good'", * 'filename.txt' * ); * $res = $db->execute($sth, $data); * </code> * * Use backslashes to escape placeholder characters if you don't want * them to be interpreted as placeholders: * <pre> * "UPDATE foo SET col=? WHERE col='over \& under'" * </pre> * * With some database backends, this is emulated. * * {@internal ibase and oci8 have their own prepare() methods.}} * * @param string $query the query to be prepared * * @return mixed DB statement resource on success. A DB_Error object * on failure. * * @see DB_common::execute() */ function prepare($query) { $tokens = preg_split('/((?<!\\\)[&?!])/', $query, -1, PREG_SPLIT_DELIM_CAPTURE); $token = 0; $types = array(); $newtokens = array(); foreach ($tokens as $val) { switch ($val) { case '?': $types[$token++] = DB_PARAM_SCALAR; break; case '&': $types[$token++] = DB_PARAM_OPAQUE; break; case '!': $types[$token++] = DB_PARAM_MISC; break; default: $newtokens[] = preg_replace('/\\\([&?!])/', "\\1", $val); } } $this->prepare_tokens[] = &$newtokens; end($this->prepare_tokens); $k = key($this->prepare_tokens); $this->prepare_types[$k] = $types; $this->prepared_queries[$k] = implode(' ', $newtokens); return $k; } // }}} // {{{ autoPrepare() /** * Automaticaly generates an insert or update query and pass it to prepare() * * @param string $table the table name * @param array $table_fields the array of field names * @param int $mode a type of query to make: * DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE * @param string $where for update queries: the WHERE clause to * append to the SQL statement. Don't * include the "WHERE" keyword. * * @return resource the query handle * * @uses DB_common::prepare(), DB_common::buildManipSQL() */ function autoPrepare($table, $table_fields, $mode = DB_AUTOQUERY_INSERT, $where = false) { $query = $this->buildManipSQL($table, $table_fields, $mode, $where); if (DB::isError($query)) { return $query; } return $this->prepare($query); } // }}} // {{{ autoExecute() /** * Automaticaly generates an insert or update query and call prepare() * and execute() with it * * @param string $table the table name * @param array $fields_values the associative array where $key is a * field name and $value its value * @param int $mode a type of query to make: * DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE * @param string $where for update queries: the WHERE clause to * append to the SQL statement. Don't * include the "WHERE" keyword. * * @return mixed a new DB_result object for successful SELECT queries * or DB_OK for successul data manipulation queries. * A DB_Error object on failure. * * @uses DB_common::autoPrepare(), DB_common::execute() */ function autoExecute($table, $fields_values, $mode = DB_AUTOQUERY_INSERT, $where = false) { $sth = $this->autoPrepare($table, array_keys($fields_values), $mode, $where); if (DB::isError($sth)) { return $sth; } $ret =& $this->execute($sth, array_values($fields_values)); $this->freePrepared($sth); return $ret; } // }}} // {{{ buildManipSQL() /** * Produces an SQL query string for autoPrepare() * * Example: * <pre> * buildManipSQL('table_sql', array('field1', 'field2', 'field3'), * DB_AUTOQUERY_INSERT); * </pre> * * That returns * <samp> * INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?) * </samp> * * NOTES: * - This belongs more to a SQL Builder class, but this is a simple * facility. * - Be carefull! If you don't give a $where param with an UPDATE * query, all the records of the table will be updated! * * @param string $table the table name * @param array $table_fields the array of field names * @param int $mode a type of query to make: * DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE * @param string $where for update queries: the WHERE clause to * append to the SQL statement. Don't * include the "WHERE" keyword. * * @return string the sql query for autoPrepare() */ function buildManipSQL($table, $table_fields, $mode, $where = false) { if (count($table_fields) == 0) { return $this->raiseError(DB_ERROR_NEED_MORE_DATA); } $first = true; switch ($mode) { case DB_AUTOQUERY_INSERT: $values = ''; $names = ''; foreach ($table_fields as $value) { if ($first) { $first = false; } else { $names .= ','; $values .= ','; } $names .= $value; $values .= '?'; } return "INSERT INTO $table ($names) VALUES ($values)"; case DB_AUTOQUERY_UPDATE: $set = ''; foreach ($table_fields as $value) { if ($first) { $first = false; } else { $set .= ','; } $set .= "$value = ?"; } $sql = "UPDATE $table SET $set"; if ($where) { $sql .= " WHERE $where"; } return $sql; default: return $this->raiseError(DB_ERROR_SYNTAX); } } // }}} // {{{ execute() /** * Executes a DB statement prepared with prepare() * * Example 1. * <code> * $sth = $db->prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)'); * $data = array( * "John's text", * "'it''s good'", * 'filename.txt' * ); * $res =& $db->execute($sth, $data); * </code> * * @param resource $stmt a DB statement resource returned from prepare() * @param mixed $data array, string or numeric data to be used in * execution of the statement. Quantity of items * passed must match quantity of placeholders in * query: meaning 1 placeholder for non-array * parameters or 1 placeholder per array element. * * @return mixed a new DB_result object for successful SELECT queries * or DB_OK for successul data manipulation queries. * A DB_Error object on failure. * * {@internal ibase and oci8 have their own execute() methods.}} * * @see DB_common::prepare() */ function &execute($stmt, $data = array()) { $realquery = $this->executeEmulateQuery($stmt, $data); if (DB::isError($realquery)) { return $realquery; } $result = $this->simpleQuery($realquery); if ($result === DB_OK || DB::isError($result)) { return $result; } else { $tmp =& new DB_result($this, $result); return $tmp; } } // }}} // {{{ executeEmulateQuery() /** * Emulates executing prepared statements if the DBMS not support them * * @param resource $stmt a DB statement resource returned from execute() * @param mixed $data array, string or numeric data to be used in * execution of the statement. Quantity of items * passed must match quantity of placeholders in * query: meaning 1 placeholder for non-array * parameters or 1 placeholder per array element. * * @return mixed a string containing the real query run when emulating * prepare/execute. A DB_Error object on failure. * * @access protected * @see DB_common::execute() */ function executeEmulateQuery($stmt, $data = array()) { $stmt = (int)$stmt; $data = (array)$data; $this->last_parameters = $data; if (count($this->prepare_types[$stmt]) != count($data)) { $this->last_query = $this->prepared_queries[$stmt]; return $this->raiseError(DB_ERROR_MISMATCH); } $realquery = $this->prepare_tokens[$stmt][0]; $i = 0; foreach ($data as $value) { if ($this->prepare_types[$stmt][$i] == DB_PARAM_SCALAR) { $realquery .= $this->quoteSmart($value); } elseif ($this->prepare_types[$stmt][$i] == DB_PARAM_OPAQUE) { $fp = @fopen($value, 'rb'); if (!$fp) { return $this->raiseError(DB_ERROR_ACCESS_VIOLATION); } $realquery .= $this->quoteSmart(fread($fp, filesize($value))); fclose($fp); } else { $realquery .= $value; } $realquery .= $this->prepare_tokens[$stmt][++$i]; } return $realquery; } // }}} // {{{ executeMultiple() /** * Performs several execute() calls on the same statement handle * * $data must be an array indexed numerically * from 0, one execute call is done for every "row" in the array. * * If an error occurs during execute(), executeMultiple() does not * execute the unfinished rows, but rather returns that error. * * @param resource $stmt query handle from prepare() * @param array $data numeric array containing the * data to insert into the query * * @return int DB_OK on success. A DB_Error object on failure. * * @see DB_common::prepare(), DB_common::execute() */ function executeMultiple($stmt, $data) { foreach ($data as $value) { $res =& $this->execute($stmt, $value); if (DB::isError($res)) { return $res; } } return DB_OK; } // }}} // {{{ freePrepared() /** * Frees the internal resources associated with a prepared query * * @param resource $stmt the prepared statement's PHP resource * @param bool $free_resource should the PHP resource be freed too? * Use false if you need to get data * from the result set later. * * @return bool TRUE on success, FALSE if $result is invalid * * @see DB_common::prepare() */ function freePrepared($stmt, $free_resource = true) { $stmt = (int)$stmt; if (isset($this->prepare_tokens[$stmt])) { unset($this->prepare_tokens[$stmt]); unset($this->prepare_types[$stmt]); unset($this->prepared_queries[$stmt]); return true; } return false; } // }}} // {{{ modifyQuery() /** * Changes a query string for various DBMS specific reasons * * It is defined here to ensure all drivers have this method available. * * @param string $query the query string to modify * * @return string the modified query string * * @access protected * @see DB_mysql::modifyQuery(), DB_oci8::modifyQuery(), * DB_sqlite::modifyQuery() */ function modifyQuery($query) { return $query; } // }}} // {{{ modifyLimitQuery() /** * Adds LIMIT clauses to a query string according to current DBMS standards * * It is defined here to assure that all implementations * have this method defined. * * @param string $query the query to modify * @param int $from the row to start to fetching (0 = the first row) * @param int $count the numbers of rows to fetch * @param mixed $params array, string or numeric data to be used in * execution of the statement. Quantity of items * passed must match quantity of placeholders in * query: meaning 1 placeholder for non-array * parameters or 1 placeholder per array element. * * @return string the query string with LIMIT clauses added * * @access protected */ function modifyLimitQuery($query, $from, $count, $params = array()) { return $query; } // }}} // {{{ query() /** * Sends a query to the database server * * The query string can be either a normal statement to be sent directly * to the server OR if <var>$params</var> are passed the query can have * placeholders and it will be passed through prepare() and execute(). * * @param string $query the SQL query or the statement to prepare * @param mixed $params array, string or numeric data to be used in * execution of the statement. Quantity of items * passed must match quantity of placeholders in * query: meaning 1 placeholder for non-array * parameters or 1 placeholder per array element. * * @return mixed a new DB_result object for successful SELECT queries * or DB_OK for successul data manipulation queries. * A DB_Error object on failure. * * @see DB_result, DB_common::prepare(), DB_common::execute() */ function &query($query, $params = array()) { if (sizeof($params) > 0) { $sth = $this->prepare($query); if (DB::isError($sth)) { return $sth; } $ret =& $this->execute($sth, $params); $this->freePrepared($sth, false); return $ret; } else { $this->last_parameters = array(); $result = $this->simpleQuery($query); if ($result === DB_OK || DB::isError($result)) { return $result; } else { $tmp =& new DB_result($this, $result); return $tmp; } } } // }}} // {{{ limitQuery() /** * Generates and executes a LIMIT query * * @param string $query the query * @param intr $from the row to start to fetching (0 = the first row) * @param int $count the numbers of rows to fetch * @param mixed $params array, string or numeric data to be used in * execution of the statement. Quantity of items * passed must match quantity of placeholders in * query: meaning 1 placeholder for non-array * parameters or 1 placeholder per array element. * * @return mixed a new DB_result object for successful SELECT queries * or DB_OK for successul data manipulation queries. * A DB_Error object on failure. */ function &limitQuery($query, $from, $count, $params = array()) { $query = $this->modifyLimitQuery($query, $from, $count, $params); if (DB::isError($query)){ return $query; } $result =& $this->query($query, $params); if (is_a($result, 'DB_result')) { $result->setOption('limit_from', $from); $result->setOption('limit_count', $count); } return $result; } // }}} // {{{ getOne() /** * Fetches the first column of the first row from a query result * * Takes care of doing the query and freeing the results when finished. * * @param string $query the SQL query * @param mixed $params array, string or numeric data to be used in * execution of the statement. Quantity of items * passed must match quantity of placeholders in * query: meaning 1 placeholder for non-array * parameters or 1 placeholder per array element. * * @return mixed the returned value of the query. * A DB_Error object on failure. */ function &getOne($query, $params = array()) { $params = (array)$params; // modifyLimitQuery() would be nice here, but it causes BC issues if (sizeof($params) > 0) { $sth = $this->prepare($query); if (DB::isError($sth)) { return $sth; } $res =& $this->execute($sth, $params); $this->freePrepared($sth); } else { $res =& $this->query($query); } if (DB::isError($res)) { return $res; } $err = $res->fetchInto($row, DB_FETCHMODE_ORDERED); $res->free(); if ($err !== DB_OK) { return $err; } return $row[0]; } // }}} // {{{ getRow() /** * Fetches the first row of data returned from a query result * * Takes care of doing the query and freeing the results when finished. * * @param string $query the SQL query * @param mixed $params array, string or numeric data to be used in * execution of the statement. Quantity of items * passed must match quantity of placeholders in * query: meaning 1 placeholder for non-array * parameters or 1 placeholder per array element. * @param int $fetchmode the fetch mode to use * * @return array the first row of results as an array. * A DB_Error object on failure. */ function &getRow($query, $params = array(), $fetchmode = DB_FETCHMODE_DEFAULT) { // compat check, the params and fetchmode parameters used to // have the opposite order if (!is_array($params)) { if (is_array($fetchmode)) { if ($params === null) { $tmp = DB_FETCHMODE_DEFAULT; } else { $tmp = $params; } $params = $fetchmode; $fetchmode = $tmp; } elseif ($params !== null) { $fetchmode = $params; $params = array(); } } // modifyLimitQuery() would be nice here, but it causes BC issues if (sizeof($params) > 0) { $sth = $this->prepare($query); if (DB::isError($sth)) { return $sth; } $res =& $this->execute($sth, $params); $this->freePrepared($sth); } else { $res =& $this->query($query); } if (DB::isError($res)) { return $res; } $err = $res->fetchInto($row, $fetchmode); $res->free(); if ($err !== DB_OK) { return $err; } return $row; } // }}} // {{{ getCol() /** * Fetches a single column from a query result and returns it as an * indexed array * * @param string $query the SQL query * @param mixed $col which column to return (integer [column number, * starting at 0] or string [column name]) * @param mixed $params array, string or numeric data to be used in * execution of the statement. Quantity of items * passed must match quantity of placeholders in * query: meaning 1 placeholder for non-array * parameters or 1 placeholder per array element. * * @return array the results as an array. A DB_Error object on failure. * * @see DB_common::query() */ function &getCol($query, $col = 0, $params = array()) { $params = (array)$params; if (sizeof($params) > 0) { $sth = $this->prepare($query); if (DB::isError($sth)) { return $sth; } $res =& $this->execute($sth, $params); $this->freePrepared($sth); } else { $res =& $this->query($query); } if (DB::isError($res)) { return $res; } $fetchmode = is_int($col) ? DB_FETCHMODE_ORDERED : DB_FETCHMODE_ASSOC; if (!is_array($row = $res->fetchRow($fetchmode))) { $ret = array(); } else { if (!array_key_exists($col, $row)) { $ret =& $this->raiseError(DB_ERROR_NOSUCHFIELD); } else { $ret = array($row[$col]); while (is_array($row = $res->fetchRow($fetchmode))) { $ret[] = $row[$col]; } } } $res->free(); if (DB::isError($row)) { $ret = $row; } return $ret; } // }}} // {{{ getAssoc() /** * Fetches an entire query result and returns it as an * associative array using the first column as the key * * If the result set contains more than two columns, the value * will be an array of the values from column 2-n. If the result * set contains only two columns, the returned value will be a * scalar with the value of the second column (unless forced to an * array with the $force_array parameter). A DB error code is * returned on errors. If the result set contains fewer than two * columns, a DB_ERROR_TRUNCATED error is returned. * * For example, if the table "mytable" contains: * * <pre> * ID TEXT DATE * -------------------------------- * 1 'one' 944679408 * 2 'two' 944679408 * 3 'three' 944679408 * </pre> * * Then the call getAssoc('SELECT id,text FROM mytable') returns: * <pre> * array( * '1' => 'one', * '2' => 'two', * '3' => 'three', * ) * </pre> * * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns: * <pre> * array( * '1' => array('one', '944679408'), * '2' => array('two', '944679408'), * '3' => array('three', '944679408') * ) * </pre> * * If the more than one row occurs with the same value in the * first column, the last row overwrites all previous ones by * default. Use the $group parameter if you don't want to * overwrite like this. Example: * * <pre> * getAssoc('SELECT category,id,name FROM mytable', false, null, * DB_FETCHMODE_ASSOC, true) returns: * * array( * '1' => array(array('id' => '4', 'name' => 'number four'), * array('id' => '6', 'name' => 'number six') * ), * '9' => array(array('id' => '4', 'name' => 'number four'), * array('id' => '6', 'name' => 'number six') * ) * ) * </pre> * * Keep in mind that database functions in PHP usually return string * values for results regardless of the database's internal type. * * @param string $query the SQL query * @param bool $force_array used only when the query returns * exactly two columns. If true, the values * of the returned array will be one-element * arrays instead of scalars. * @param mixed $params array, string or numeric data to be used in * execution of the statement. Quantity of * items passed must match quantity of * placeholders in query: meaning 1 * placeholder for non-array parameters or * 1 placeholder per array element. * @param int $fetchmode the fetch mode to use * @param bool $group if true, the values of the returned array * is wrapped in another array. If the same * key value (in the first column) repeats * itself, the values will be appended to * this array instead of overwriting the * existing values. * * @return array the associative array containing the query results. * A DB_Error object on failure. */ function &getAssoc($query, $force_array = false, $params = array(), $fetchmode = DB_FETCHMODE_DEFAULT, $group = false) { $params = (array)$params; if (sizeof($params) > 0) { $sth = $this->prepare($query); if (DB::isError($sth)) { return $sth; } $res =& $this->execute($sth, $params); $this->freePrepared($sth); } else { $res =& $this->query($query); } if (DB::isError($res)) { return $res; } if ($fetchmode == DB_FETCHMODE_DEFAULT) { $fetchmode = $this->fetchmode; } $cols = $res->numCols(); if ($cols < 2) { $tmp =& $this->raiseError(DB_ERROR_TRUNCATED); return $tmp; } $results = array(); if ($cols > 2 || $force_array) { // return array values // XXX this part can be optimized if ($fetchmode == DB_FETCHMODE_ASSOC) { while (is_array($row = $res->fetchRow(DB_FETCHMODE_ASSOC))) { reset($row); $key = current($row); unset($row[key($row)]); if ($group) { $results[$key][] = $row; } else { $results[$key] = $row; } } } elseif ($fetchmode == DB_FETCHMODE_OBJECT) { while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT)) { $arr = get_object_vars($row); $key = current($arr); if ($group) { $results[$key][] = $row; } else { $results[$key] = $row; } } } else { while (is_array($row = $res->fetchRow(DB_FETCHMODE_ORDERED))) { // we shift away the first element to get // indices running from 0 again $key = array_shift($row); if ($group) { $results[$key][] = $row; } else { $results[$key] = $row; } } } if (DB::isError($row)) { $results = $row; } } else { // return scalar values while (is_array($row = $res->fetchRow(DB_FETCHMODE_ORDERED))) { if ($group) { $results[$row[0]][] = $row[1]; } else { $results[$row[0]] = $row[1]; } } if (DB::isError($row)) { $results = $row; } } $res->free(); return $results; } // }}} // {{{ getAll() /** * Fetches all of the rows from a query result * * @param string $query the SQL query * @param mixed $params array, string or numeric data to be used in * execution of the statement. Quantity of * items passed must match quantity of * placeholders in query: meaning 1 * placeholder for non-array parameters or * 1 placeholder per array element. * @param int $fetchmode the fetch mode to use: * + DB_FETCHMODE_ORDERED * + DB_FETCHMODE_ASSOC * + DB_FETCHMODE_ORDERED | DB_FETCHMODE_FLIPPED * + DB_FETCHMODE_ASSOC | DB_FETCHMODE_FLIPPED * * @return array the nested array. A DB_Error object on failure. */ function &getAll($query, $params = array(), $fetchmode = DB_FETCHMODE_DEFAULT) { // compat check, the params and fetchmode parameters used to // have the opposite order if (!is_array($params)) { if (is_array($fetchmode)) { if ($params === null) { $tmp = DB_FETCHMODE_DEFAULT; } else { $tmp = $params; } $params = $fetchmode; $fetchmode = $tmp; } elseif ($params !== null) { $fetchmode = $params; $params = array(); } } if (sizeof($params) > 0) { $sth = $this->prepare($query); if (DB::isError($sth)) { return $sth; } $res =& $this->execute($sth, $params); $this->freePrepared($sth); } else { $res =& $this->query($query); } if ($res === DB_OK || DB::isError($res)) { return $res; } $results = array(); while (DB_OK === $res->fetchInto($row, $fetchmode)) { if ($fetchmode & DB_FETCHMODE_FLIPPED) { foreach ($row as $key => $val) { $results[$key][] = $val; } } else { $results[] = $row; } } $res->free(); if (DB::isError($row)) { $tmp =& $this->raiseError($row); return $tmp; } return $results; } // }}} // {{{ autoCommit() /** * Enables or disables automatic commits * * @param bool $onoff true turns it on, false turns it off * * @return int DB_OK on success. A DB_Error object if the driver * doesn't support auto-committing transactions. */ function autoCommit($onoff = false) { return $this->raiseError(DB_ERROR_NOT_CAPABLE); } // }}} // {{{ commit() /** * Commits the current transaction * * @return int DB_OK on success. A DB_Error object on failure. */ function commit() { return $this->raiseError(DB_ERROR_NOT_CAPABLE); } // }}} // {{{ rollback() /** * Reverts the current transaction * * @return int DB_OK on success. A DB_Error object on failure. */ function rollback() { return $this->raiseError(DB_ERROR_NOT_CAPABLE); } // }}} // {{{ numRows() /** * Determines the number of rows in a query result * * @param resource $result the query result idenifier produced by PHP * * @return int the number of rows. A DB_Error object on failure. */ function numRows($result) { return $this->raiseError(DB_ERROR_NOT_CAPABLE); } // }}} // {{{ affectedRows() /** * Determines the number of rows affected by a data maniuplation query * * 0 is returned for queries that don't manipulate data. * * @return int the number of rows. A DB_Error object on failure. */ function affectedRows() { return $this->raiseError(DB_ERROR_NOT_CAPABLE); } // }}} // {{{ getSequenceName() /** * Generates the name used inside the database for a sequence * * The createSequence() docblock contains notes about storing sequence * names. * * @param string $sqn the sequence's public name * * @return string the sequence's name in the backend * * @access protected * @see DB_common::createSequence(), DB_common::dropSequence(), * DB_common::nextID(), DB_common::setOption() */ function getSequenceName($sqn) { return sprintf($this->getOption('seqname_format'), preg_replace('/[^a-z0-9_.]/i', '_', $sqn)); } // }}} // {{{ nextId() /** * Returns the next free id in a sequence * * @param string $seq_name name of the sequence * @param boolean $ondemand when true, the seqence is automatically * created if it does not exist * * @return int the next id number in the sequence. * A DB_Error object on failure. * * @see DB_common::createSequence(), DB_common::dropSequence(), * DB_common::getSequenceName() */ function nextId($seq_name, $ondemand = true) { return $this->raiseError(DB_ERROR_NOT_CAPABLE); } // }}} // {{{ createSequence() /** * Creates a new sequence * * The name of a given sequence is determined by passing the string * provided in the <var>$seq_name</var> argument through PHP's sprintf() * function using the value from the <var>seqname_format</var> option as * the sprintf()'s format argument. * * <var>seqname_format</var> is set via setOption(). * * @param string $seq_name name of the new sequence * * @return int DB_OK on success. A DB_Error object on failure. * * @see DB_common::dropSequence(), DB_common::getSequenceName(), * DB_common::nextID() */ function createSequence($seq_name) { return $this->raiseError(DB_ERROR_NOT_CAPABLE); } // }}} // {{{ dropSequence() /** * Deletes a sequence * * @param string $seq_name name of the sequence to be deleted * * @return int DB_OK on success. A DB_Error object on failure. * * @see DB_common::createSequence(), DB_common::getSequenceName(), * DB_common::nextID() */ function dropSequence($seq_name) { return $this->raiseError(DB_ERROR_NOT_CAPABLE); } // }}} // {{{ raiseError() /** * Communicates an error and invoke error callbacks, etc * * Basically a wrapper for PEAR::raiseError without the message string. * * @param mixed integer error code, or a PEAR error object (all * other parameters are ignored if this parameter is * an object * @param int error mode, see PEAR_Error docs * @param mixed if error mode is PEAR_ERROR_TRIGGER, this is the * error level (E_USER_NOTICE etc). If error mode is * PEAR_ERROR_CALLBACK, this is the callback function, * either as a function name, or as an array of an * object and method name. For other error modes this * parameter is ignored. * @param string extra debug information. Defaults to the last * query and native error code. * @param mixed native error code, integer or string depending the * backend * * @return object the PEAR_Error object * * @see PEAR_Error */ function &raiseError($code = DB_ERROR, $mode = null, $options = null, $userinfo = null, $nativecode = null) { // The error is yet a DB error object if (is_object($code)) { // because we the static PEAR::raiseError, our global // handler should be used if it is set if ($mode === null && !empty($this->_default_error_mode)) { $mode = $this->_default_error_mode; $options = $this->_default_error_options; } $tmp = PEAR::raiseError($code, null, $mode, $options, null, null, true); return $tmp; } if ($userinfo === null) { $userinfo = $this->last_query; } if ($nativecode) { $userinfo .= ' [nativecode=' . trim($nativecode) . ']'; } else { $userinfo .= ' [DB Error: ' . DB::errorMessage($code) . ']'; } $tmp = PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'DB_Error', true); return $tmp; } // }}} // {{{ errorNative() /** * Gets the DBMS' native error code produced by the last query * * @return mixed the DBMS' error code. A DB_Error object on failure. */ function errorNative() { return $this->raiseError(DB_ERROR_NOT_CAPABLE); } // }}} // {{{ errorCode() /** * Maps native error codes to DB's portable ones * * Uses the <var>$errorcode_map</var> property defined in each driver. * * @param string|int $nativecode the error code returned by the DBMS * * @return int the portable DB error code. Return DB_ERROR if the * current driver doesn't have a mapping for the * $nativecode submitted. */ function errorCode($nativecode) { if (isset($this->errorcode_map[$nativecode])) { return $this->errorcode_map[$nativecode]; } // Fall back to DB_ERROR if there was no mapping. return DB_ERROR; } // }}} // {{{ errorMessage() /** * Maps a DB error code to a textual message * * @param integer $dbcode the DB error code * * @return string the error message corresponding to the error code * submitted. FALSE if the error code is unknown. * * @see DB::errorMessage() */ function errorMessage($dbcode) { return DB::errorMessage($this->errorcode_map[$dbcode]); } // }}} // {{{ tableInfo() /** * Returns information about a table or a result set * * The format of the resulting array depends on which <var>$mode</var> * you select. The sample output below is based on this query: * <pre> * SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId * FROM tblFoo * JOIN tblBar ON tblFoo.fldId = tblBar.fldId * </pre> * * <ul> * <li> * * <kbd>null</kbd> (default) * <pre> * [0] => Array ( * [table] => tblFoo * [name] => fldId * [type] => int * [len] => 11 * [flags] => primary_key not_null * ) * [1] => Array ( * [table] => tblFoo * [name] => fldPhone * [type] => string * [len] => 20 * [flags] => * ) * [2] => Array ( * [table] => tblBar * [name] => fldId * [type] => int * [len] => 11 * [flags] => primary_key not_null * ) * </pre> * * </li><li> * * <kbd>DB_TABLEINFO_ORDER</kbd> * * <p>In addition to the information found in the default output, * a notation of the number of columns is provided by the * <samp>num_fields</samp> element while the <samp>order</samp> * element provides an array with the column names as the keys and * their location index number (corresponding to the keys in the * the default output) as the values.</p> * * <p>If a result set has identical field names, the last one is * used.</p> * * <pre> * [num_fields] => 3 * [order] => Array ( * [fldId] => 2 * [fldTrans] => 1 * ) * </pre> * * </li><li> * * <kbd>DB_TABLEINFO_ORDERTABLE</kbd> * * <p>Similar to <kbd>DB_TABLEINFO_ORDER</kbd> but adds more * dimensions to the array in which the table names are keys and * the field names are sub-keys. This is helpful for queries that * join tables which have identical field names.</p> * * <pre> * [num_fields] => 3 * [ordertable] => Array ( * [tblFoo] => Array ( * [fldId] => 0 * [fldPhone] => 1 * ) * [tblBar] => Array ( * [fldId] => 2 * ) * ) * </pre> * * </li> * </ul> * * The <samp>flags</samp> element contains a space separated list * of extra information about the field. This data is inconsistent * between DBMS's due to the way each DBMS works. * + <samp>primary_key</samp> * + <samp>unique_key</samp> * + <samp>multiple_key</samp> * + <samp>not_null</samp> * * Most DBMS's only provide the <samp>table</samp> and <samp>flags</samp> * elements if <var>$result</var> is a table name. The following DBMS's * provide full information from queries: * + fbsql * + mysql * * If the 'portability' option has <samp>DB_PORTABILITY_LOWERCASE</samp> * turned on, the names of tables and fields will be lowercased. * * @param object|string $result DB_result object from a query or a * string containing the name of a table. * While this also accepts a query result * resource identifier, this behavior is * deprecated. * @param int $mode either unused or one of the tableInfo modes: * <kbd>DB_TABLEINFO_ORDERTABLE</kbd>, * <kbd>DB_TABLEINFO_ORDER</kbd> or * <kbd>DB_TABLEINFO_FULL</kbd> (which does both). * These are bitwise, so the first two can be * combined using <kbd>|</kbd>. * * @return array an associative array with the information requested. * A DB_Error object on failure. * * @see DB_common::setOption() */ function tableInfo($result, $mode = null) { /* * If the DB_<driver> class has a tableInfo() method, that one * overrides this one. But, if the driver doesn't have one, * this method runs and tells users about that fact. */ return $this->raiseError(DB_ERROR_NOT_CAPABLE); } // }}} // {{{ getTables() /** * Lists the tables in the current database * * @return array the list of tables. A DB_Error object on failure. * * @deprecated Method deprecated some time before Release 1.2 */ function getTables() { return $this->getListOf('tables'); } // }}} // {{{ getListOf() /** * Lists internal database information * * @param string $type type of information being sought. * Common items being sought are: * tables, databases, users, views, functions * Each DBMS's has its own capabilities. * * @return array an array listing the items sought. * A DB DB_Error object on failure. */ function getListOf($type) { $sql = $this->getSpecialQuery($type); if ($sql === null) { $this->last_query = ''; return $this->raiseError(DB_ERROR_UNSUPPORTED); } elseif (is_int($sql) || DB::isError($sql)) { // Previous error return $this->raiseError($sql); } elseif (is_array($sql)) { // Already the result return $sql; } // Launch this query return $this->getCol($sql); } // }}} // {{{ getSpecialQuery() /** * Obtains the query string needed for listing a given type of objects * * @param string $type the kind of objects you want to retrieve * * @return string the SQL query string or null if the driver doesn't * support the object type requested * * @access protected * @see DB_common::getListOf() */ function getSpecialQuery($type) { return $this->raiseError(DB_ERROR_UNSUPPORTED); } // }}} // {{{ _rtrimArrayValues() /** * Right-trims all strings in an array * * @param array $array the array to be trimmed (passed by reference) * * @return void * * @access protected */ function _rtrimArrayValues(&$array) { foreach ($array as $key => $value) { if (is_string($value)) { $array[$key] = rtrim($value); } } } // }}} // {{{ _convertNullArrayValuesToEmpty() /** * Converts all null values in an array to empty strings * * @param array $array the array to be de-nullified (passed by reference) * * @return void * * @access protected */ function _convertNullArrayValuesToEmpty(&$array) { foreach ($array as $key => $value) { if (is_null($value)) { $array[$key] = ''; } } } // }}} } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: */ ?>
mikexstudios/xcomic
includes/DB/common.php
PHP
gpl-2.0
69,476
package conf; /** * Enthält die Konfigurationseinstellungen * @author CreaByte * */ public final class Conf { /** * Frames pro Sekunde */ public static final int fps = 22; /** * Standard-Zeitschritt für die Simulation */ public static final long defaultTimeStep = 1000/fps; // 22fps /** * Effektive Umrechnung Längeneinheiten in Pixel * LINKS OBEN ist der Nullpunkt "der Welt" */ public static double pixelPerMeter=4; public static final double MAX_ZOOM=10,MIN_ZOOM=0.01; public static int convertToPixel(double meters) { return (int)(meters * pixelPerMeter); } /** * Typische Größen */ public static final double carWidth = 1.5; // Meter public static final double carLength = 3; // Meter public static final double laneWidth = 3; // Meter /** * Typische Größen für die Autobewegung */ public static final double L = 10; // [m] Typische Längeneinheit public static final double V = 10; // [km/h] Typische Geschwindigkeit public static final double T = L/V; // [h] Typische Zeiteinheit public static final double d = 1; // [m] Standard-Sicherheitsabstand public static final double c = 1; // [] Wie schnell wird beim auffahren gebremst? public static final double v0 = 10; // [km/h] Standard - Wunschgeschwindigkeit public static final double tau = 1; // [Sek] Standard - Relaxionszeit in (wie schnell p public static final double a = 3.85; // [m/s²] Typische Längeneinheit in Metern public static final double minCarDistance = 2; // Meter public static final double eyeSight = 10; // Meter /** * Grenze der Stationen zum Rand des Stadtgebiets in Meter */ public static final double border = 4; // Meter public static int random(int max) { return (int)Math.round(Math.random() * max); } }
rondiplomatico/traffic
src/conf/Conf.java
Java
gpl-2.0
1,922
/* * (c) Copyright 2009-2013 by Volker Bergmann. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, is permitted under the terms of the * GNU General Public License. * * For redistributing this software or a derivative work under a license other * than the GPL-compatible Free Software License as defined by the Free * Software Foundation or approved by OSI, you must first obtain a commercial * license to this software product from Volker Bergmann. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * WITHOUT A WARRANTY OF ANY KIND. ALL EXPRESS OR IMPLIED CONDITIONS, * REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE * HEREBY EXCLUDED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.databene.benerator.wrapper; import org.databene.benerator.Generator; /** * Converts the {@link Number} products of another {@link Generator} to {@link Integer}.<br/> * <br/> * Created at 23.06.2009 22:58:26 * @since 0.6.0 * @author Volker Bergmann */ public class AsIntegerGeneratorWrapper<E extends Number> extends GeneratorWrapper<E, Integer> { public AsIntegerGeneratorWrapper(Generator<E> source) { super(source); } @Override public Class<Integer> getGeneratedType() { return Integer.class; } @Override public ProductWrapper<Integer> generate(ProductWrapper<Integer> wrapper) { assertInitialized(); ProductWrapper<E> tmp = generateFromSource(); if (tmp == null) return null; E unwrappedValue = tmp.unwrap(); return wrapper.wrap(unwrappedValue != null ? unwrappedValue.intValue() : null); } }
raphaelfeng/benerator
src/org/databene/benerator/wrapper/AsIntegerGeneratorWrapper.java
Java
gpl-2.0
2,256
from bs4 import BeautifulSoup import urllib.request html = urllib.request.urlopen('http://www.nlotto.co.kr/common.do?method=main&#8217;') soup = BeautifulSoup(html) hoi = soup.find("span", id="lottoDrwNo") numbers=[] for n in range(1,7): strV ="drwtNo" + str(n) first = soup.find('img', id=strV)['alt'] numbers.append(first) bonus = soup.find('img', id="bnusNo")['alt'] print('Lotto numbers') print(hoi.string + "results") print(" ".join(numbers)) print('Bonus_number: '+bonus)
YongJang/PythonTelegram
examples/referenced/a.py
Python
gpl-2.0
497
<?php $lang['plugin']['categories'] = array( 'subject' => 'Kategorie' ); ?>
evacchi/flatpress
fp-plugins/categories/lang/lang.cs-cz.php
PHP
gpl-2.0
89
package polarbear.acceptance.order; import static com.polarbear.util.Constants.ResultState.*; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static polarbear.acceptance.Request.anRequest; import static polarbear.integration.service.order.assertutil.AssertUtil.assertThatOrder; import static polarbear.integration.service.order.factory.ExpectOrderFactory.expectOrder2; import static polarbear.test.util.Constants.ORDER_DETAIL_URL; import static polarbear.test.util.Constants.ORDER_SIGN_URL; import static polarbear.test.util.JsonResultConvertUtil.resultBody; import static polarbear.test.util.JsonResultConvertUtil.resultState; import static polarbear.test.util.LoginEncoder.encodeLoginUser; import static polarbear.testdata.acceptance.testdata.OrderAcceptanceTestDataFactory.*; import static polarbear.testdata.acceptance.testdata.UserAcceptanceTestDataFactory.createUser1; import java.io.UnsupportedEncodingException; import org.junit.Test; import polarbear.acceptance.Request.ResultCallback; import com.polarbear.domain.Order; import com.polarbear.util.JsonResult; import com.polarbear.util.Constants.ORDER_STATE; import com.polarbear.web.login.front.LoginController; public class SignOrderTest { @Test public void shouldSuccessWhenSignOrder() { final String signOrderId = createUser1_2ProductDeliveryOrder2().getId().toString(); anRequest(ORDER_SIGN_URL) .withCookie(LoginController.USER_LOGIN_COOKIE, encodeLoginUser(createUser1())) .addParams("orderId", signOrderId) .post(new ResultCallback() { public void onSuccess(JsonResult jsonResult) throws UnsupportedEncodingException { assertThat(resultState(jsonResult), is(SUCCESS)); assertOrder(signOrderId); } }); } @Test public void shouldFailWhenSignOrderInCancleState() { final String signOrderId = createUser1_2ProductUnpayOrder1().getId().toString(); anRequest(ORDER_SIGN_URL) .withCookie(LoginController.USER_LOGIN_COOKIE, encodeLoginUser(createUser1())) .addParams("orderId", signOrderId) .post(new ResultCallback() { public void onSuccess(JsonResult jsonResult) throws UnsupportedEncodingException { assertThat(resultState(jsonResult), is(ORDER_OPREATE_ERR)); } }); } private void assertOrder(String orderId) { anRequest(ORDER_DETAIL_URL) .withCookie(LoginController.USER_LOGIN_COOKIE, encodeLoginUser(createUser1())) .addParams("orderId", orderId) .post(new ResultCallback() { public void onSuccess(JsonResult jsonResult) throws UnsupportedEncodingException { assertThat(resultState(jsonResult), is(SUCCESS)); Order actOrder = resultBody(jsonResult, Order.class); assertThatOrder(actOrder, expectOrder2(ORDER_STATE.SUCCESS)); } }); } }
polargull/polar
polarbear/src/test/java/polarbear/acceptance/order/SignOrderTest.java
Java
gpl-2.0
3,093
<?php /** * @copyright Copyright(c) 2010 jooyea.net * @file curd_action.php * @brief 实现系统的自动增删改查 * @author webning * @date 2010-12-23 * @version 0.6 */ /** * @brief 完成用户的自动增加删除修改功能DURD类 * @class ICURDAction */ class ICURDAction extends IAction { /** * @brief 处理curd动作 * @return String */ public function curd() { $action = $this->id; $controller = $this->controller; $curdinfo = $this->initinfo(); if(is_array($curdinfo)) { $modelName = $curdinfo['model']; $key = $curdinfo['key']; $actions = $curdinfo['actions']; switch($action) { case 'add': case 'upd': { if(method_exists($controller,'getValidate')) $validate = $controller->getValidate(); else $validate =null; if($validate!=null) { $formValidate = new IFormValidation($validate); $data = $formValidate->run(); } $model = new IModel($modelName); if(isset($data) && $data!==null) { $model->setData($data[$modelName]); if($action = 'add') $flag = $model->add(); else $flag = $model->upd("$key = '".IReq::get($key)."'"); } if(isset($flag) && $flag) { $_GET['action'] = $actions['success']; } else { $_GET['action'] = $actions['fail']; } $controller->run(); return true; } case 'del': { $model = new IModel($modelName); $flag = $model->del("$key = '".IReq::get($key)."'"); if($flag) { $_GET['action']=$actions['success']; } else { $_GET['action'] = $actions['fail']; } $controller->run(); return true; } case 'get': { $model = new IModel($modelName); $rs = $model->getObj("$key = '".IReq::get($key)."'"); echo JSON::encode($rs); return false; } } } } /** * @brief 分析curd的配置信息 * @return mixed */ private function initinfo() { $action = $this->id; $controller = $this->controller; if(method_exists($controller,'curd')) { $curdinfo = $controller->curd(); $modelName = isset($curdinfo['model'])?$curdinfo['model']:null; if($modelName !==null) { $key = isset($curdinfo['key'])?$curdinfo['key']:'id'; $actions = isset($curdinfo['actions'])?$curdinfo['actions']:null; if(is_array($actions)) { if(isset($actions[$action])) { $current = $actions[$action]; } else { $current = isset($actions['*'])?$actions['*']:null; } if($current!==null) { $fail = isset($current['fail'])?$current['fail']:(isset($current[1])?$current[1]:'index'); $success = isset($current['success'])?$current['success']:(isset($current[0])?$current[0]:'index'); return array('model'=>$modelName,'key'=>$key, 'actions' =>array('success'=>$success,'fail'=>$fail) ); } else { throw new IException('class '.get_class($controller).' have curd error'); } } } } return null; } /** * @brief Action的运行方法 */ public function run() { $this->curd(); } } ?>
zatol/iws
lib/web/action/curd_action.php
PHP
gpl-2.0
4,566